@openclaw/mattermost 2026.7.2-beta.5 → 2026.8.1-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.
@@ -1,37 +1,45 @@
1
1
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { _ as updateMattermostPost, a as createMattermostPost, f as fetchMattermostUserTeams, g as sendMattermostTyping, l as fetchMattermostMe, m as readMattermostError, n as buildMattermostApiUrl, o as deleteMattermostPost, p as normalizeMattermostBaseUrl, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostUser } from "./client-w0lkxuKh.js";
3
- import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy, T as resolveDefaultGroupPolicy, _ as logInboundDrop, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, x as registerPluginHttpRoute, y as parseTcpPort } from "./monitor-auth-BOh6zLW9.js";
4
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-B4gg-KRm.js";
5
- import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-BR6Nl5Qf.js";
6
- import { a as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-DLBTUlbh.js";
7
- import { _ as isSlashCommandsEnabled, a as sendMessageMattermost, b as resolveSlashCommandConfig, c as deliverMattermostReplyPayload, d as parseMattermostModelPickerContext, f as renderMattermostModelsPickerView, g as cleanupSlashCommands, h as DEFAULT_COMMAND_SPECS, l as toMattermostChannelDeliveryResult, m as resolveMattermostModelPickerCurrentModel, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as renderMattermostProviderPickerView, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as buildMattermostAllowedModelRefs, v as registerSlashCommands, y as resolveCallbackUrl } from "./slash-state-VCRdqj5F.js";
2
+ import { a as createMattermostPost, d as fetchMattermostUser, g as readMattermostError, l as fetchMattermostChannelPosts, m as normalizeMattermostBaseUrl, 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-B_hd-kwM.js";
3
+ import { S as resolveChannelMediaMaxBytes, T as warnMissingProviderGroupPolicyFallbackOnce, _ as logInboundDrop, b as registerPluginHttpRoute, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, w as resolveDefaultGroupPolicy, x as resolveAllowlistProviderRuntimeGroupPolicy$1 } from "./monitor-auth-CVd_4FPD.js";
4
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-Du_EJMeN.js";
5
+ import { a as resolveMattermostReplyToMode, i as resolveMattermostAccount, n as listMattermostAccountIds, t as inspectMattermostAccount } from "./accounts-DspH-NMT.js";
6
+ import { i as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-Dxt8Zv1j.js";
7
+ import { _ as isSlashCommandsEnabled, a as sendMessageMattermost, b as resolveSlashCommandConfig, c as deliverMattermostReplyPayload, d as parseMattermostModelPickerContext, f as renderMattermostModelsPickerView, g as cleanupSlashCommands, h as DEFAULT_COMMAND_SPECS, l as joinMattermostVisibleContent, m as resolveMattermostModelPickerCurrentModel, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as renderMattermostProviderPickerView, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as buildMattermostAllowedModelRefs, v as registerSlashCommands, y as resolveCallbackUrl } from "./slash-state-DUowGLl4.js";
8
8
  import { randomUUID } from "node:crypto";
9
+ import { resolveGatewayPort } from "openclaw/plugin-sdk/core";
9
10
  import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
10
11
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
12
+ import { buildChannelInboundMediaPayload, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
13
+ import { formatErrorMessage, toErrorObject } from "openclaw/plugin-sdk/error-runtime";
11
14
  import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
12
15
  import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
13
16
  import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
14
17
  import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
15
18
  import { z } from "zod";
16
- import { buildChannelInboundMediaPayload, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, resolveInboundMentionDecision, toInboundMediaFacts } from "openclaw/plugin-sdk/channel-inbound";
17
- import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
19
+ import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createMessageReceiptFromOutboundResults, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
20
+ import { resolveAllowlistProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
18
21
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
19
22
  import { fanInChannelIngressLifecycles, resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
20
- import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
23
+ import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
24
+ import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
25
+ import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
21
26
  import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
22
27
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
23
28
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
24
29
  import { runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
25
30
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
26
- import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
27
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
31
+ import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
28
32
  import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
29
33
  import WebSocket from "ws";
34
+ import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
35
+ import { resolveChannelContextVisibilityMode, shouldIncludeSupplementalContext } from "openclaw/plugin-sdk/context-visibility-runtime";
36
+ import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
30
37
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
31
38
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
39
+ import { createPluginStateErrorReporter } from "openclaw/plugin-sdk/plugin-state-runtime";
32
40
  //#region extensions/mattermost/src/mattermost/directory.ts
33
41
  function buildClient(params) {
34
- const account = resolveMattermostAccount({
42
+ const account = inspectMattermostAccount({
35
43
  cfg: params.cfg,
36
44
  accountId: params.accountId
37
45
  });
@@ -93,7 +101,7 @@ async function listMattermostDirectoryGroups(params) {
93
101
  }
94
102
  seenIds.add(ch.id);
95
103
  entries.push({
96
- kind: "group",
104
+ kind: resolveMattermostTrustedChatKind({ channelType: ch.type }) === "group" ? "group" : "channel",
97
105
  id: `channel:${ch.id}`,
98
106
  name: ch.name ?? void 0,
99
107
  handle: ch.display_name ?? void 0
@@ -208,6 +216,8 @@ const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
208
216
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
209
217
  const MattermostEventPayloadSchema = z.object({
210
218
  event: z.string().optional(),
219
+ status: z.string().optional(),
220
+ seq_reply: z.number().optional(),
211
221
  data: z.object({
212
222
  post: z.unknown().optional(),
213
223
  reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
@@ -271,6 +281,7 @@ function createMattermostConnectOnce(opts) {
271
281
  let protocolPingTimer;
272
282
  let protocolPongTimer;
273
283
  let initialUpdateAt;
284
+ let authenticationSeq;
274
285
  const clearTimers = () => {
275
286
  if (healthCheckTimer !== void 0) {
276
287
  clearTimeout(healthCheckTimer);
@@ -370,11 +381,11 @@ function createMattermostConnectOnce(opts) {
370
381
  });
371
382
  opts.statusSink?.({
372
383
  connected: true,
373
- lastConnectedAt: Date.now(),
374
- lastError: null
384
+ lifecycle: "starting"
375
385
  });
386
+ authenticationSeq = opts.nextSeq();
376
387
  const authPayload = JSON.stringify({
377
- seq: opts.nextSeq(),
388
+ seq: authenticationSeq,
378
389
  action: "authentication_challenge",
379
390
  data: { token: opts.botToken }
380
391
  });
@@ -412,6 +423,10 @@ function createMattermostConnectOnce(opts) {
412
423
  const raw = rawDataToString(data);
413
424
  const payload = parseMattermostEventPayload(raw);
414
425
  if (!payload) return;
426
+ if (payload.status === "OK" && payload.seq_reply === authenticationSeq) {
427
+ opts.statusSink?.(channelReadyPatch());
428
+ return;
429
+ }
415
430
  if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
416
431
  if (!opts.onReaction) return;
417
432
  try {
@@ -443,6 +458,7 @@ function createMattermostConnectOnce(opts) {
443
458
  const message = reasonToString(reason);
444
459
  opts.statusSink?.({
445
460
  connected: false,
461
+ lifecycle: "recovering",
446
462
  lastDisconnect: {
447
463
  at: Date.now(),
448
464
  status: code,
@@ -465,7 +481,11 @@ function createMattermostConnectOnce(opts) {
465
481
  meta: { subsystem: "mattermost-websocket" }
466
482
  });
467
483
  opts.runtime.error?.(`mattermost websocket error: ${String(err)}`);
468
- opts.statusSink?.({ lastError: String(err) });
484
+ opts.statusSink?.({
485
+ connected: false,
486
+ lifecycle: "recovering",
487
+ lastError: String(err)
488
+ });
469
489
  try {
470
490
  ws.close();
471
491
  } catch {}
@@ -485,21 +505,7 @@ function reasonToString(reason) {
485
505
  //#region extensions/mattermost/src/mattermost/monitor-ingress.ts
486
506
  const MATTERMOST_INGRESS_PAYLOAD_VERSION = 1;
487
507
  const MATTERMOST_INGRESS_POLL_INTERVAL_MS = 1e3;
488
- const MATTERMOST_INGRESS_PRUNE_INTERVAL_MS = 3600 * 1e3;
489
- const MATTERMOST_INGRESS_COMPLETED_TTL_MS = 720 * 60 * 60 * 1e3;
490
- const MATTERMOST_INGRESS_COMPLETED_MAX_ENTRIES = 2e4;
491
- const MATTERMOST_INGRESS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
492
- const MATTERMOST_INGRESS_FAILED_MAX_ENTRIES = 2e4;
493
- var MattermostIngressPermanentError = class extends Error {
494
- constructor(reason, message, options) {
495
- super(message, options);
496
- this.reason = reason;
497
- this.name = "MattermostIngressPermanentError";
498
- }
499
- };
500
- function isRecord(value) {
501
- return typeof value === "object" && value !== null && !Array.isArray(value);
502
- }
508
+ const MattermostIngressPermanentError = createChannelIngressError("MattermostIngressPermanentError", { withReason: true });
503
509
  function parseRawObject(raw, subject) {
504
510
  let parsed;
505
511
  try {
@@ -583,13 +589,7 @@ function createMattermostIngressMonitor(options) {
583
589
  },
584
590
  pollIntervalMs: options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS,
585
591
  waitForDeliveryIdleBeforeRepump: true,
586
- retention: {
587
- pruneIntervalMs: MATTERMOST_INGRESS_PRUNE_INTERVAL_MS,
588
- completedTtlMs: MATTERMOST_INGRESS_COMPLETED_TTL_MS,
589
- completedMaxEntries: MATTERMOST_INGRESS_COMPLETED_MAX_ENTRIES,
590
- failedTtlMs: MATTERMOST_INGRESS_FAILED_TTL_MS,
591
- failedMaxEntries: MATTERMOST_INGRESS_FAILED_MAX_ENTRIES
592
- },
592
+ retention: "standard",
593
593
  drain: {
594
594
  resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
595
595
  ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
@@ -640,7 +640,7 @@ function formatMattermostNoVisibleReplyLog(params) {
640
640
  //#endregion
641
641
  //#region extensions/mattermost/src/mattermost/monitor-context.ts
642
642
  function shouldUpdateMattermostDraftToolProgress(account) {
643
- return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
643
+ return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, true, account.streamingMode);
644
644
  }
645
645
  function shouldSuppressMattermostDefaultToolProgressMessages(account) {
646
646
  return account.streamingMode !== "off";
@@ -650,12 +650,25 @@ function buildMattermostModelPickerSelectMessageSid(params) {
650
650
  const model = normalizeLowercaseStringOrEmpty(params.model);
651
651
  return `interaction:${params.postId}:select:${provider}/${model}`;
652
652
  }
653
+ function buildMattermostButtonInteractionMessageSid(params) {
654
+ return `interaction:${params.postId}:${params.actionId}`;
655
+ }
653
656
  function resolveMattermostReplyRootId(params) {
654
657
  const threadRootId = normalizeOptionalString(params.threadRootId);
655
658
  if (params.kind === "direct" && !threadRootId) return;
656
659
  if (threadRootId) return threadRootId;
657
660
  return normalizeOptionalString(params.replyToId);
658
661
  }
662
+ function resolveMattermostInteractionReplyRootId(params) {
663
+ const interactionMessageSid = normalizeOptionalString(params.interactionMessageSid);
664
+ const replyToId = normalizeOptionalString(params.replyToId);
665
+ const providerReplyToId = replyToId === interactionMessageSid ? normalizeOptionalString(params.sourcePostId) : replyToId;
666
+ return resolveMattermostReplyRootId({
667
+ kind: params.kind,
668
+ threadRootId: params.threadRootId,
669
+ replyToId: providerReplyToId
670
+ });
671
+ }
659
672
  function canFinalizeMattermostPreviewInPlace(params) {
660
673
  return resolveMattermostReplyRootId({
661
674
  kind: params.kind,
@@ -859,10 +872,15 @@ function registerMattermostInteractions(params) {
859
872
  return eventPlan.thread.sessionKey;
860
873
  },
861
874
  dispatchButtonClick: async (button) => {
875
+ const sourcePostId = button.post.id || button.postId;
876
+ const interactionMessageSid = buildMattermostButtonInteractionMessageSid({
877
+ postId: button.postId,
878
+ actionId: button.actionId
879
+ });
862
880
  const eventPlan = await buildMattermostEventPlan(monitor, {
863
881
  channelId: button.channelId,
864
882
  senderId: button.userId,
865
- postId: button.post.id || button.postId,
883
+ postId: sourcePostId,
866
884
  threadRootId: button.post.root_id,
867
885
  dropLabel: "interaction dispatch"
868
886
  });
@@ -877,7 +895,7 @@ function registerMattermostInteractions(params) {
877
895
  ConversationLabel: `mattermost:${button.userName}`,
878
896
  GroupSubject: kind !== "direct" ? channelDisplay || button.channelId : void 0,
879
897
  SenderName: button.userName,
880
- MessageSid: `interaction:${button.postId}:${button.actionId}`,
898
+ MessageSid: interactionMessageSid,
881
899
  WasMentioned: true,
882
900
  CommandAuthorized: false
883
901
  });
@@ -893,24 +911,27 @@ function registerMattermostInteractions(params) {
893
911
  },
894
912
  ctxPayload,
895
913
  delivery: {
914
+ observeMessageSent: true,
896
915
  deliver: async (payload) => {
897
- const result = toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
916
+ const result = await deliverMattermostReplyPayload({
898
917
  core,
899
918
  cfg,
900
919
  payload,
901
920
  to,
902
921
  accountId: account.accountId,
903
922
  agentId: route.agentId,
904
- replyToId: resolveMattermostReplyRootId({
923
+ replyToId: resolveMattermostInteractionReplyRootId({
905
924
  kind,
906
925
  threadRootId: thread.effectiveReplyToId,
907
- replyToId: payload.replyToId
926
+ replyToId: payload.replyToId,
927
+ interactionMessageSid,
928
+ sourcePostId
908
929
  }),
909
930
  textLimit,
910
931
  tableMode,
911
932
  sendMessage: sendMessageMattermost,
912
933
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
913
- }));
934
+ });
914
935
  if (result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
915
936
  return result;
916
937
  },
@@ -932,7 +953,9 @@ function registerMattermostInteractions(params) {
932
953
  pluginId: "mattermost",
933
954
  source: "mattermost-interactions",
934
955
  accountId: account.accountId,
935
- log: (message) => runtime.log?.(message)
956
+ log: (message) => runtime.log?.(message),
957
+ replaceExisting: true,
958
+ throwOnFailure: true
936
959
  });
937
960
  }
938
961
  //#endregion
@@ -969,28 +992,31 @@ function createMattermostModelPickerInteractionHandler(monitor) {
969
992
  },
970
993
  ctxPayload,
971
994
  delivery: {
995
+ observeMessageSent: true,
972
996
  deliver: async (payload) => {
973
997
  const trimmedPayload = {
974
998
  ...payload,
975
999
  text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
976
1000
  };
977
- return toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
1001
+ return await deliverMattermostReplyPayload({
978
1002
  core,
979
1003
  cfg,
980
1004
  payload: trimmedPayload,
981
1005
  to,
982
1006
  accountId: account.accountId,
983
1007
  agentId: route.agentId,
984
- replyToId: resolveMattermostReplyRootId({
1008
+ replyToId: resolveMattermostInteractionReplyRootId({
985
1009
  kind,
986
1010
  threadRootId: thread.effectiveReplyToId,
987
- replyToId: trimmedPayload.replyToId
1011
+ replyToId: trimmedPayload.replyToId,
1012
+ interactionMessageSid: params.messageSid,
1013
+ sourcePostId: params.sourcePostId
988
1014
  }),
989
1015
  textLimit,
990
1016
  tableMode: "off",
991
1017
  sendMessage: sendMessageMattermost,
992
1018
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
993
- }));
1019
+ });
994
1020
  },
995
1021
  onError: (err, info) => {
996
1022
  runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
@@ -1094,37 +1120,37 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1094
1120
  }
1095
1121
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
1096
1122
  if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
1097
- (async () => {
1098
- try {
1099
- await runModelPickerCommand({
1100
- commandText: `/model ${targetModelRef}`,
1101
- commandAuthorized: auth.commandAuthorized,
1102
- eventPlan,
1103
- senderName: params.userName,
1104
- messageSid: buildMattermostModelPickerSelectMessageSid({
1105
- postId: params.payload.post_id,
1106
- provider: pickerState.provider,
1107
- model: pickerState.model
1108
- })
1109
- });
1110
- const currentModel = resolveMattermostModelPickerCurrentModel({
1111
- cfg,
1112
- route: modelSessionRoute,
1113
- data,
1114
- readConsistency: "latest"
1115
- });
1116
- const view = renderMattermostModelsPickerView({
1117
- ownerUserId: pickerState.ownerUserId,
1118
- data,
1119
- provider: pickerState.provider,
1120
- page: pickerState.page,
1121
- currentModel
1122
- });
1123
- await updatePickerPost(view.text, view.buttons);
1124
- } catch (err) {
1125
- runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
1126
- }
1127
- })();
1123
+ const messageSid = buildMattermostModelPickerSelectMessageSid({
1124
+ postId: params.payload.post_id,
1125
+ provider: pickerState.provider,
1126
+ model: pickerState.model
1127
+ });
1128
+ runDetachedWebhookWork(async () => {
1129
+ await runModelPickerCommand({
1130
+ commandText: `/model ${targetModelRef}`,
1131
+ commandAuthorized: auth.commandAuthorized,
1132
+ eventPlan,
1133
+ senderName: params.userName,
1134
+ messageSid,
1135
+ sourcePostId: params.post.id || params.payload.post_id
1136
+ });
1137
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1138
+ cfg,
1139
+ route: modelSessionRoute,
1140
+ data,
1141
+ readConsistency: "latest"
1142
+ });
1143
+ const view = renderMattermostModelsPickerView({
1144
+ ownerUserId: pickerState.ownerUserId,
1145
+ data,
1146
+ provider: pickerState.provider,
1147
+ page: pickerState.page,
1148
+ currentModel
1149
+ });
1150
+ await updatePickerPost(view.text, view.buttons);
1151
+ }).catch((err) => {
1152
+ runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
1153
+ });
1128
1154
  return {};
1129
1155
  };
1130
1156
  }
@@ -1175,8 +1201,12 @@ function stripOncharPrefix(text, prefixes) {
1175
1201
  }
1176
1202
  //#endregion
1177
1203
  //#region extensions/mattermost/src/mattermost/monitor-resources.ts
1178
- function buildMattermostInboundMediaPayload(media) {
1179
- return buildChannelInboundMediaPayload(toInboundMediaFacts(media));
1204
+ async function buildMattermostInboundMediaPayload(media) {
1205
+ const facts = await toInboundMediaFactsWithMetadata(media);
1206
+ return {
1207
+ ...buildChannelInboundMediaPayload(facts),
1208
+ media: facts
1209
+ };
1180
1210
  }
1181
1211
  function formatMattermostPendingMediaText(params) {
1182
1212
  return [params.body, formatMediaPlaceholderText(params.media)].filter(Boolean).join("\n").trim();
@@ -1327,6 +1357,13 @@ function normalizeMattermostDraftText(text, maxChars) {
1327
1357
  if (trimmed.length <= maxChars) return trimmed;
1328
1358
  return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
1329
1359
  }
1360
+ function consumeMattermostPublishedChunk(params) {
1361
+ const chunk = params.chunk.trim();
1362
+ if (!chunk) return params.offset;
1363
+ let offset = params.offset;
1364
+ while (offset < params.source.length && /\s/.test(params.source[offset] ?? "")) offset += 1;
1365
+ return params.source.startsWith(chunk, offset) ? offset + chunk.length : void 0;
1366
+ }
1330
1367
  function createMattermostDraftPreviewBoundaryController(params) {
1331
1368
  let hasStreamedContent = false;
1332
1369
  return {
@@ -1348,12 +1385,20 @@ function createMattermostDraftStream(params) {
1348
1385
  stopped: false,
1349
1386
  final: false
1350
1387
  };
1388
+ let terminalAcceptedDeliveryError;
1389
+ const assertNoAcceptedDeliveryFailure = () => {
1390
+ if (terminalAcceptedDeliveryError !== void 0) throw terminalAcceptedDeliveryError;
1391
+ };
1351
1392
  let currentGeneration = {
1352
1393
  lastSentText: "",
1353
1394
  latestSourceText: "",
1354
1395
  ready: Promise.resolve()
1355
1396
  };
1356
1397
  const sealedAssistantTexts = [];
1398
+ const publishedAssistantParts = /* @__PURE__ */ new Map();
1399
+ const trackPublishedAssistantPart = (part) => {
1400
+ publishedAssistantParts.set(part.messageId, part);
1401
+ };
1357
1402
  const sendOrEditStreamMessage = async (text) => {
1358
1403
  if (streamState.stopped && !streamState.final) return false;
1359
1404
  const target = currentGeneration;
@@ -1363,25 +1408,24 @@ function createMattermostDraftStream(params) {
1363
1408
  if (streamState.stopped && !streamState.final) return false;
1364
1409
  if (normalized === target.lastSentText) return true;
1365
1410
  try {
1366
- if (target.postId) await updateMattermostPost(params.client, target.postId, { message: normalized });
1411
+ if (target.postId) target.lastProviderText = (await updateMattermostPost(params.client, target.postId, { message: normalized })).message ?? normalized;
1367
1412
  else {
1368
- const postId = (await createMattermostPost(params.client, {
1413
+ const sent = await createMattermostPost(params.client, {
1369
1414
  channelId: params.channelId,
1370
1415
  message: normalized,
1371
1416
  rootId: params.rootId
1372
- })).id?.trim();
1373
- if (!postId) {
1374
- streamState.stopped = true;
1375
- params.warn?.("mattermost stream preview stopped (missing post id from create)");
1376
- return false;
1377
- }
1378
- target.postId = postId;
1417
+ });
1418
+ target.postId = sent.id;
1419
+ target.lastProviderText = sent.message ?? normalized;
1379
1420
  }
1380
1421
  target.lastSentText = normalized;
1381
1422
  return true;
1382
1423
  } catch (err) {
1383
1424
  streamState.stopped = true;
1425
+ const acceptedDeliveryError = isChannelPartialDeliveryError(err) ? toErrorObject(err, "Mattermost accepted delivery failed") : void 0;
1426
+ if (acceptedDeliveryError) terminalAcceptedDeliveryError = acceptedDeliveryError;
1384
1427
  params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
1428
+ if (acceptedDeliveryError) throw acceptedDeliveryError;
1385
1429
  return false;
1386
1430
  }
1387
1431
  };
@@ -1404,36 +1448,109 @@ function createMattermostDraftStream(params) {
1404
1448
  warnPrefix: "mattermost stream preview cleanup failed"
1405
1449
  });
1406
1450
  const forceNewMessage = () => {
1451
+ if (terminalAcceptedDeliveryError !== void 0) return Promise.reject(terminalAcceptedDeliveryError);
1407
1452
  if (streamState.stopped || streamState.final) return Promise.resolve();
1408
1453
  const pendingText = loop.takePending();
1409
1454
  const inFlightAtBoundary = loop.waitForInFlight();
1410
1455
  const sealed = currentGeneration;
1456
+ const assistantText = sealed.latestAssistantText?.trim();
1457
+ let publishedAssistantOffset = 0;
1411
1458
  const boundary = (async () => {
1412
1459
  try {
1413
1460
  await sealed.ready;
1461
+ assertNoAcceptedDeliveryFailure();
1414
1462
  await inFlightAtBoundary;
1415
- if (streamState.stopped && !streamState.final) return;
1463
+ assertNoAcceptedDeliveryFailure();
1464
+ if (streamState.stopped && !streamState.final) {
1465
+ assertNoAcceptedDeliveryFailure();
1466
+ return;
1467
+ }
1416
1468
  const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
1417
1469
  const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
1418
1470
  const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
1419
1471
  const firstChunk = chunks[0];
1420
1472
  if (!firstChunk) return;
1421
1473
  if (sealed.postId) {
1422
- if (firstChunk !== sealed.lastSentText) await updateMattermostPost(params.client, sealed.postId, { message: firstChunk });
1423
- } else await createMattermostPost(params.client, {
1424
- channelId: params.channelId,
1425
- message: firstChunk,
1426
- rootId: params.rootId
1427
- });
1428
- for (const chunk of chunks.slice(1)) await createMattermostPost(params.client, {
1429
- channelId: params.channelId,
1430
- message: chunk,
1431
- rootId: params.rootId
1474
+ if (assistantText && (sealed.lastProviderText || sealed.lastSentText)) {
1475
+ const publishedContent = sealed.lastProviderText ?? sealed.lastSentText;
1476
+ trackPublishedAssistantPart({
1477
+ messageId: sealed.postId,
1478
+ content: publishedContent
1479
+ });
1480
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1481
+ source: assistantText,
1482
+ offset: 0,
1483
+ chunk: publishedContent
1484
+ }) ?? 0;
1485
+ }
1486
+ let providerFirstChunk = sealed.lastProviderText ?? firstChunk;
1487
+ if (firstChunk !== sealed.lastSentText) providerFirstChunk = (await updateMattermostPost(params.client, sealed.postId, { message: firstChunk })).message ?? firstChunk;
1488
+ if (assistantText) {
1489
+ trackPublishedAssistantPart({
1490
+ messageId: sealed.postId,
1491
+ content: providerFirstChunk
1492
+ });
1493
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1494
+ source: assistantText,
1495
+ offset: 0,
1496
+ chunk: providerFirstChunk
1497
+ }) ?? 0;
1498
+ }
1499
+ } else {
1500
+ const firstPost = await createMattermostPost(params.client, {
1501
+ channelId: params.channelId,
1502
+ message: firstChunk,
1503
+ rootId: params.rootId
1504
+ });
1505
+ if (assistantText) {
1506
+ const publishedContent = firstPost.message ?? firstChunk;
1507
+ trackPublishedAssistantPart({
1508
+ messageId: firstPost.id,
1509
+ content: publishedContent
1510
+ });
1511
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1512
+ source: assistantText,
1513
+ offset: 0,
1514
+ chunk: publishedContent
1515
+ }) ?? 0;
1516
+ }
1517
+ }
1518
+ for (const chunk of chunks.slice(1)) {
1519
+ const post = await createMattermostPost(params.client, {
1520
+ channelId: params.channelId,
1521
+ message: chunk,
1522
+ rootId: params.rootId
1523
+ });
1524
+ if (assistantText) {
1525
+ const publishedContent = post.message ?? chunk;
1526
+ trackPublishedAssistantPart({
1527
+ messageId: post.id,
1528
+ content: publishedContent
1529
+ });
1530
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1531
+ source: assistantText,
1532
+ offset: publishedAssistantOffset,
1533
+ chunk: publishedContent
1534
+ }) ?? publishedAssistantOffset;
1535
+ }
1536
+ }
1537
+ if (assistantText) sealedAssistantTexts.push({
1538
+ text: assistantText,
1539
+ requiresBlockBoundary: true
1432
1540
  });
1433
- const assistantText = sealed.latestAssistantText?.trim();
1434
- if (assistantText) sealedAssistantTexts.push(assistantText);
1435
1541
  } catch (err) {
1542
+ const acceptedDeliveryError = isChannelPartialDeliveryError(err) ? toErrorObject(err, "Mattermost accepted delivery failed") : void 0;
1543
+ if (acceptedDeliveryError) {
1544
+ streamState.stopped = true;
1545
+ terminalAcceptedDeliveryError = acceptedDeliveryError;
1546
+ }
1547
+ const publishedAssistantPrefix = assistantText?.slice(0, publishedAssistantOffset).trim();
1548
+ if (publishedAssistantPrefix) sealedAssistantTexts.push({
1549
+ text: publishedAssistantPrefix,
1550
+ requiresBlockBoundary: false
1551
+ });
1436
1552
  params.warn?.(`mattermost stream preview boundary flush failed: ${err instanceof Error ? err.message : String(err)}`);
1553
+ if (acceptedDeliveryError) throw acceptedDeliveryError;
1437
1554
  }
1438
1555
  })();
1439
1556
  currentGeneration = {
@@ -1445,23 +1562,33 @@ function createMattermostDraftStream(params) {
1445
1562
  return boundary;
1446
1563
  };
1447
1564
  const flush = async () => {
1565
+ assertNoAcceptedDeliveryFailure();
1448
1566
  await loop.flush();
1449
1567
  await currentGeneration.ready;
1568
+ assertNoAcceptedDeliveryFailure();
1450
1569
  };
1451
1570
  const discardPending = async () => {
1571
+ assertNoAcceptedDeliveryFailure();
1452
1572
  await stopForClear();
1453
1573
  await currentGeneration.ready;
1574
+ assertNoAcceptedDeliveryFailure();
1454
1575
  };
1455
1576
  const clear = async () => {
1577
+ assertNoAcceptedDeliveryFailure();
1456
1578
  await clearWithStop(discardPending);
1579
+ assertNoAcceptedDeliveryFailure();
1457
1580
  };
1458
1581
  const seal = async () => {
1582
+ assertNoAcceptedDeliveryFailure();
1459
1583
  await sealLifecycle();
1460
1584
  await currentGeneration.ready;
1585
+ assertNoAcceptedDeliveryFailure();
1461
1586
  };
1462
1587
  const stop = async () => {
1588
+ assertNoAcceptedDeliveryFailure();
1463
1589
  await stopLifecycle();
1464
1590
  await currentGeneration.ready;
1591
+ assertNoAcceptedDeliveryFailure();
1465
1592
  };
1466
1593
  const update = (text) => {
1467
1594
  currentGeneration.latestSourceText = text;
@@ -1474,37 +1601,48 @@ function createMattermostDraftStream(params) {
1474
1601
  updateLifecycle(text);
1475
1602
  };
1476
1603
  const settleBoundaries = async () => {
1604
+ assertNoAcceptedDeliveryFailure();
1477
1605
  await currentGeneration.ready;
1606
+ assertNoAcceptedDeliveryFailure();
1478
1607
  };
1479
1608
  const resolveFinalText = (text) => {
1609
+ const publishedParts = [...publishedAssistantParts.values()];
1480
1610
  if (sealedAssistantTexts.length === 0) return {
1481
1611
  kind: "full",
1482
- text
1612
+ text,
1613
+ publishedParts
1483
1614
  };
1484
1615
  let remainingText = text.trim();
1485
1616
  for (const sealedText of sealedAssistantTexts) {
1486
- const completed = sealedText.trim();
1617
+ const completed = sealedText.text.trim();
1487
1618
  if (!completed || !remainingText.startsWith(completed)) return {
1488
1619
  kind: "full",
1489
- text
1620
+ text,
1621
+ publishedParts
1490
1622
  };
1491
1623
  const suffix = remainingText.slice(completed.length);
1492
- if (suffix && !/^\r?\n/.test(suffix)) return {
1624
+ if (sealedText.requiresBlockBoundary && suffix && !/^\r?\n/.test(suffix)) return {
1493
1625
  kind: "full",
1494
- text
1626
+ text,
1627
+ publishedParts
1495
1628
  };
1496
- remainingText = suffix.replace(/^(?:\r?\n)+/, "");
1629
+ remainingText = suffix.replace(sealedText.requiresBlockBoundary ? /^(?:\r?\n)+/ : /^\s+/, "");
1497
1630
  }
1498
1631
  const currentText = currentGeneration.latestAssistantText?.trim() ?? "";
1499
1632
  const remaining = remainingText.trim();
1500
1633
  if (currentText && !remaining.startsWith(currentText)) return {
1501
1634
  kind: "full",
1502
- text
1635
+ text,
1636
+ publishedParts
1503
1637
  };
1504
1638
  return remaining ? {
1505
1639
  kind: "remaining",
1506
- text: remaining
1507
- } : { kind: "already-delivered" };
1640
+ text: remaining,
1641
+ publishedParts
1642
+ } : {
1643
+ kind: "already-delivered",
1644
+ publishedParts
1645
+ };
1508
1646
  };
1509
1647
  params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
1510
1648
  return {
@@ -1523,54 +1661,147 @@ function createMattermostDraftStream(params) {
1523
1661
  }
1524
1662
  //#endregion
1525
1663
  //#region extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
1664
+ function combineMattermostVisibleDeliveryResults(results) {
1665
+ const visibleResults = results.filter((result) => result?.visibleReplySent === true);
1666
+ if (visibleResults.length === 0) return;
1667
+ const receiptResults = [];
1668
+ for (const result of visibleResults) if (result.receipt) receiptResults.push({ receipt: result.receipt });
1669
+ else receiptResults.push(...(result.messageIds ?? []).map((messageId) => ({ messageId })));
1670
+ const receipt = createMessageReceiptFromOutboundResults({ results: receiptResults });
1671
+ return {
1672
+ outcome: visibleResults.some((result) => result.outcome === "media") ? "media" : "text",
1673
+ messageIds: listMessageReceiptPlatformIds(receipt),
1674
+ receipt,
1675
+ visibleReplySent: true,
1676
+ content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1677
+ };
1678
+ }
1526
1679
  async function deliverMattermostReplyWithDraftPreview(params) {
1527
- if (isReasoningReplyPayload(params.payload)) return;
1528
- await deliverWithFinalizableLivePreviewAdapter({
1529
- kind: params.info.kind,
1530
- payload: params.payload,
1531
- adapter: defineFinalizableLivePreviewAdapter({
1532
- draft: {
1533
- flush: params.draftStream.flush,
1534
- clear: params.draftStream.clear,
1535
- discardPending: params.draftStream.discardPending,
1536
- seal: params.draftStream.seal,
1537
- id: params.draftStream.postId
1538
- },
1539
- buildFinalEdit: (payload) => {
1540
- const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
1541
- const ttsSupplement = getReplyPayloadTtsSupplement(payload);
1542
- const previewFinalText = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
1543
- if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1544
- kind: params.kind,
1545
- previewRootId: params.effectiveReplyToId,
1546
- threadRootId: params.effectiveReplyToId,
1547
- replyToId: payload.replyToId
1548
- })) return;
1549
- return { message: previewFinalText };
1550
- },
1551
- editFinal: async (previewPostId, edit) => {
1552
- await updateMattermostPost(params.client, previewPostId, edit);
1553
- },
1554
- onPreviewFinalized: () => {
1555
- params.previewState.finalizedViaPreviewPost = true;
1556
- params.recordThreadParticipation?.();
1557
- },
1558
- buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
1559
- deliverSupplemental: async (payload) => {
1560
- await params.deliverPayload(payload);
1561
- },
1562
- logPreviewEditFailure: (err) => {
1563
- params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
1680
+ if (isReasoningReplyPayload(params.payload)) return {
1681
+ outcome: "reasoning_skipped",
1682
+ visibleReplySent: false,
1683
+ suppression: { reason: "no_visible_result" }
1684
+ };
1685
+ let normalDeliveryResult;
1686
+ let supplementalDeliveryResult;
1687
+ let previewDeliveryResult;
1688
+ let confirmedPreviewDelivery;
1689
+ let previewFinalDeliveryText;
1690
+ let previewFinalTextAlreadyDelivered = false;
1691
+ let useConfirmedPreviewAsWholeFinal = false;
1692
+ let pendingPreviewFinalContent;
1693
+ let finalizedPreviewPost;
1694
+ try {
1695
+ if ((await deliverWithFinalizableLivePreviewAdapter({
1696
+ kind: params.info.kind,
1697
+ payload: params.payload,
1698
+ adapter: defineFinalizableLivePreviewAdapter({
1699
+ ...params.previewState.finalizedViaPreviewPost ? {} : { draft: {
1700
+ flush: params.draftStream.flush,
1701
+ clear: params.draftStream.clear,
1702
+ discardPending: params.draftStream.discardPending,
1703
+ seal: params.draftStream.seal,
1704
+ id: params.draftStream.postId
1705
+ } },
1706
+ buildFinalEdit: (payload) => {
1707
+ const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
1708
+ const ttsSupplement = getReplyPayloadTtsSupplement(payload);
1709
+ const previewFinalResolution = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
1710
+ confirmedPreviewDelivery = previewFinalResolution?.confirmedDelivery;
1711
+ previewFinalDeliveryText = previewFinalResolution?.deliveryText;
1712
+ previewFinalTextAlreadyDelivered = previewFinalResolution?.alreadyDelivered === true && payload.isError !== true;
1713
+ useConfirmedPreviewAsWholeFinal = previewFinalTextAlreadyDelivered && !resolveSendableOutboundReplyParts(payload).hasMedia;
1714
+ const previewFinalText = previewFinalResolution?.editText;
1715
+ if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1716
+ kind: params.kind,
1717
+ previewRootId: params.effectiveReplyToId,
1718
+ threadRootId: params.effectiveReplyToId,
1719
+ replyToId: payload.replyToId
1720
+ })) return;
1721
+ pendingPreviewFinalContent = previewFinalText;
1722
+ return { message: previewFinalText };
1723
+ },
1724
+ editFinal: async (previewPostId, edit) => {
1725
+ finalizedPreviewPost = await updateMattermostPost(params.client, previewPostId, edit);
1726
+ },
1727
+ resolveFinalizedId: (previewPostId) => finalizedPreviewPost?.id ?? previewPostId,
1728
+ onPreviewFinalized: (_previewPostId, receipt) => {
1729
+ params.previewState.finalizedViaPreviewPost = true;
1730
+ previewFinalTextAlreadyDelivered = true;
1731
+ previewDeliveryResult = {
1732
+ outcome: "text",
1733
+ messageIds: listMessageReceiptPlatformIds(receipt),
1734
+ receipt,
1735
+ visibleReplySent: true,
1736
+ content: finalizedPreviewPost?.message ?? pendingPreviewFinalContent ?? ""
1737
+ };
1738
+ params.recordThreadParticipation?.();
1739
+ },
1740
+ buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
1741
+ deliverSupplemental: async (payload) => {
1742
+ supplementalDeliveryResult = await params.deliverPayload(payload);
1743
+ return supplementalDeliveryResult.visibleReplySent;
1744
+ },
1745
+ logPreviewEditFailure: (err) => {
1746
+ params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
1747
+ }
1748
+ }),
1749
+ deliverNormally: async (payload) => {
1750
+ if (useConfirmedPreviewAsWholeFinal && confirmedPreviewDelivery?.visibleReplySent === true) return true;
1751
+ const supplement = getReplyPayloadTtsSupplement(payload);
1752
+ const resolvedDeliveryText = previewFinalDeliveryText ?? (previewFinalTextAlreadyDelivered ? "" : void 0);
1753
+ const payloadText = payload.text?.trim();
1754
+ const deliveryPayload = payload.isError !== true && supplement && (previewFinalTextAlreadyDelivered || !payloadText && supplement.visibleTextAlreadyDelivered === true) ? buildTtsSupplementMediaPayload(payload) : payload.isError !== true && supplement && !payloadText ? {
1755
+ ...payload,
1756
+ text: resolvedDeliveryText?.trim() ? resolvedDeliveryText : supplement.spokenText
1757
+ } : payload.isError !== true && typeof resolvedDeliveryText === "string" ? {
1758
+ ...payload,
1759
+ text: resolvedDeliveryText
1760
+ } : payload;
1761
+ normalDeliveryResult = await params.deliverPayload(deliveryPayload);
1762
+ return normalDeliveryResult.visibleReplySent;
1564
1763
  }
1565
- }),
1566
- deliverNormally: async (payload) => {
1567
- const supplement = getReplyPayloadTtsSupplement(payload);
1568
- await params.deliverPayload(supplement && !payload.text?.trim() && supplement.visibleTextAlreadyDelivered !== true ? {
1569
- ...payload,
1570
- text: supplement.spokenText
1571
- } : payload);
1764
+ })).kind !== "preview-finalized" || !previewDeliveryResult?.receipt) return combineMattermostVisibleDeliveryResults([confirmedPreviewDelivery, normalDeliveryResult]) ?? {
1765
+ outcome: "empty",
1766
+ visibleReplySent: false,
1767
+ suppression: { reason: "no_visible_result" }
1768
+ };
1769
+ return combineMattermostVisibleDeliveryResults([
1770
+ confirmedPreviewDelivery,
1771
+ previewDeliveryResult,
1772
+ supplementalDeliveryResult,
1773
+ normalDeliveryResult
1774
+ ]) ?? previewDeliveryResult;
1775
+ } catch (error) {
1776
+ const completedVisibleResults = [];
1777
+ const completedReceiptResults = [];
1778
+ for (const result of [
1779
+ confirmedPreviewDelivery,
1780
+ previewDeliveryResult,
1781
+ normalDeliveryResult,
1782
+ supplementalDeliveryResult
1783
+ ]) {
1784
+ if (result?.visibleReplySent !== true) continue;
1785
+ completedVisibleResults.push(result);
1786
+ if (result.receipt) completedReceiptResults.push({ receipt: result.receipt });
1787
+ else completedReceiptResults.push(...(result.messageIds ?? []).map((messageId) => ({ messageId })));
1572
1788
  }
1573
- });
1789
+ if (completedVisibleResults.length === 0) throw error;
1790
+ const failedPartial = isChannelPartialDeliveryError(error) ? error.deliveryResult : void 0;
1791
+ const receipt = createMessageReceiptFromOutboundResults({ results: [...completedReceiptResults, ...failedPartial?.receipt ? [{ receipt: failedPartial.receipt }] : (failedPartial?.messageIds ?? []).map((messageId) => ({ messageId }))] });
1792
+ throw createChannelPartialDeliveryError(error, {
1793
+ messageIds: listMessageReceiptPlatformIds(receipt),
1794
+ receipt,
1795
+ visibleReplySent: true,
1796
+ content: joinMattermostVisibleContent([
1797
+ confirmedPreviewDelivery?.content,
1798
+ previewDeliveryResult?.content,
1799
+ normalDeliveryResult?.content,
1800
+ supplementalDeliveryResult?.content,
1801
+ failedPartial?.content
1802
+ ])
1803
+ });
1804
+ }
1574
1805
  }
1575
1806
  //#endregion
1576
1807
  //#region extensions/mattermost/src/mattermost/thread-participation.ts
@@ -1582,14 +1813,8 @@ const threadParticipation = createPersistentDedupeCache({
1582
1813
  namespace: "mattermost.thread-participation",
1583
1814
  maxEntries: 1e3,
1584
1815
  openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1585
- logError: (error) => {
1586
- try {
1587
- getOptionalMattermostRuntime()?.logging.getChildLogger({
1588
- plugin: "mattermost",
1589
- feature: "thread-participation-state"
1590
- }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
1591
- } catch {}
1592
- }
1816
+ logError: createPluginStateErrorReporter(getOptionalMattermostRuntime, "mattermost", "thread-participation-state", "Mattermost persistent thread participation state failed"),
1817
+ readTimestamp: ({ repliedAt }) => repliedAt
1593
1818
  }
1594
1819
  });
1595
1820
  function makeKey(accountId, channelId, threadRootId) {
@@ -1623,7 +1848,8 @@ function createDisabledMattermostDraftStream() {
1623
1848
  settleBoundaries: noopAsync,
1624
1849
  resolveFinalText: (text) => ({
1625
1850
  kind: "full",
1626
- text
1851
+ text,
1852
+ publishedParts: []
1627
1853
  })
1628
1854
  };
1629
1855
  }
@@ -1641,9 +1867,10 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1641
1867
  accountId: account.accountId,
1642
1868
  typing: baseReplyPipeline.typing
1643
1869
  });
1644
- const draftPreviewEnabled = account.streamingMode !== "off";
1645
- const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
1646
- const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
1870
+ const hookRunner = getGlobalHookRunner();
1871
+ const draftPreviewEnabled = !((hookRunner?.hasHooks("reply_payload_sending") ?? false) || (hookRunner?.hasHooks("message_sending") ?? false)) && account.streamingMode !== "off";
1872
+ const draftToolProgressEnabled = draftPreviewEnabled && shouldUpdateMattermostDraftToolProgress(account);
1873
+ const suppressDefaultToolProgressMessages = draftPreviewEnabled && shouldSuppressMattermostDefaultToolProgressMessages(account);
1647
1874
  const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
1648
1875
  client,
1649
1876
  channelId,
@@ -1689,17 +1916,51 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1689
1916
  };
1690
1917
  const previewState = { finalizedViaPreviewPost: false };
1691
1918
  const resolvePreviewFinalText = (text) => {
1692
- if (typeof text !== "string") return;
1693
- const resolution = draftStream.resolveFinalText(text);
1919
+ const resolution = draftStream.resolveFinalText(typeof text === "string" ? text : "");
1920
+ const confirmedDelivery = resolution.publishedParts.length > 0 ? (() => {
1921
+ const receipt = createMessageReceiptFromOutboundResults({
1922
+ results: resolution.publishedParts.map((part) => ({
1923
+ channel: "mattermost",
1924
+ messageId: part.messageId,
1925
+ channelId
1926
+ })),
1927
+ kind: "preview",
1928
+ ...effectiveReplyToId ? { replyToId: effectiveReplyToId } : {}
1929
+ });
1930
+ return {
1931
+ outcome: "text",
1932
+ messageIds: listMessageReceiptPlatformIds(receipt),
1933
+ receipt,
1934
+ visibleReplySent: true,
1935
+ content: joinMattermostVisibleContent(resolution.publishedParts.map((part) => part.content))
1936
+ };
1937
+ })() : void 0;
1694
1938
  const deliveryText = resolution.kind === "already-delivered" ? "" : resolution.text;
1695
1939
  const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
1696
1940
  const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
1697
1941
  if (!chunks.length && formatted) chunks.push(formatted);
1698
- if (chunks.length !== 1) return;
1942
+ if (chunks.length !== 1) return {
1943
+ deliveryText,
1944
+ confirmedDelivery,
1945
+ alreadyDelivered: resolution.kind === "already-delivered"
1946
+ };
1699
1947
  const trimmed = chunks[0]?.trim();
1700
- if (!trimmed) return;
1701
- if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
1702
- return trimmed;
1948
+ if (!trimmed) return {
1949
+ deliveryText,
1950
+ confirmedDelivery,
1951
+ alreadyDelivered: resolution.kind === "already-delivered"
1952
+ };
1953
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return {
1954
+ deliveryText,
1955
+ confirmedDelivery,
1956
+ alreadyDelivered: false
1957
+ };
1958
+ return {
1959
+ editText: trimmed,
1960
+ deliveryText,
1961
+ confirmedDelivery,
1962
+ alreadyDelivered: false
1963
+ };
1703
1964
  };
1704
1965
  const updateDraftFromPartial = (text) => {
1705
1966
  const cleaned = text?.trim();
@@ -1725,16 +1986,21 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1725
1986
  typingCallbacks
1726
1987
  };
1727
1988
  const delivery = {
1989
+ observeMessageSent: true,
1728
1990
  deliver: async (payloadEntry, info) => {
1729
1991
  if (info.kind === "final") {
1730
1992
  await enterBlockPreviewActivity("text");
1731
1993
  await draftStream.settleBoundaries();
1732
1994
  progressDraft.markFinalReplyStarted();
1733
1995
  }
1996
+ let threadParticipationRecorded = false;
1734
1997
  const markThreadParticipation = () => {
1735
- if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
1998
+ if (!threadParticipationRecorded && kind !== "direct" && effectiveReplyToId) {
1999
+ threadParticipationRecorded = true;
2000
+ recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2001
+ }
1736
2002
  };
1737
- await deliverMattermostReplyWithDraftPreview({
2003
+ const result = await deliverMattermostReplyWithDraftPreview({
1738
2004
  payload: payloadEntry,
1739
2005
  info,
1740
2006
  kind,
@@ -1751,7 +2017,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1751
2017
  ...payloadToDeliver,
1752
2018
  text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
1753
2019
  } : payloadToDeliver;
1754
- const outcome = await deliverMattermostReplyPayload({
2020
+ const deliveryResult = await deliverMattermostReplyPayload({
1755
2021
  core,
1756
2022
  cfg,
1757
2023
  payload: resolvedPayload,
@@ -1767,20 +2033,32 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1767
2033
  tableMode,
1768
2034
  sendMessage: sendMessageMattermost,
1769
2035
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2036
+ }).catch((error) => {
2037
+ if (isChannelPartialDeliveryError(error)) markThreadParticipation();
2038
+ throw error;
1770
2039
  });
1771
- if (outcome === "text" || outcome === "media") markThreadParticipation();
1772
- else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
2040
+ if (deliveryResult.outcome === "text" || deliveryResult.outcome === "media") markThreadParticipation();
2041
+ else if (deliveryResult.outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
1773
2042
  const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
1774
- outcome,
2043
+ outcome: deliveryResult.outcome,
1775
2044
  payload: resolvedPayload,
1776
2045
  to,
1777
2046
  accountId: account.accountId,
1778
2047
  agentId: route.agentId
1779
2048
  });
1780
2049
  if (deliveryLog) runtime.log?.(deliveryLog);
2050
+ return deliveryResult;
1781
2051
  }
2052
+ }).catch((error) => {
2053
+ if (isChannelPartialDeliveryError(error)) {
2054
+ markThreadParticipation();
2055
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2056
+ }
2057
+ throw error;
1782
2058
  });
2059
+ if (result.visibleReplySent) markThreadParticipation();
1783
2060
  if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2061
+ return result;
1784
2062
  },
1785
2063
  onError: (err, info) => {
1786
2064
  runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
@@ -1848,35 +2126,35 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1848
2126
  disableBlockStreaming: draftPreviewEnabled ? true : replyOptions.disableBlockStreaming,
1849
2127
  ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
1850
2128
  onModelSelected,
1851
- onPartialReply: (payloadResult) => account.streamingMode === "progress" ? void 0 : updateDraftFromPartial(payloadResult.text),
2129
+ onPartialReply: (payloadResult) => account.streamingMode === "progress" ? false : updateDraftFromPartial(payloadResult.text),
1852
2130
  onAssistantMessageStart: () => {
1853
2131
  lastPartialText = "";
1854
2132
  progressDraft.resetReasoningProgress();
1855
2133
  if (account.streamingMode === "block") {
1856
2134
  blockPreviewAssistantMessagePending = true;
1857
- return;
2135
+ return false;
1858
2136
  }
1859
2137
  if (account.streamingMode !== "progress") progressDraft.reset();
2138
+ return false;
1860
2139
  },
1861
2140
  onReasoningEnd: () => {
1862
2141
  lastPartialText = "";
1863
2142
  progressDraft.resetReasoningProgress();
1864
2143
  if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
2144
+ return false;
1865
2145
  },
1866
2146
  onReasoningStream: async (payloadResult) => {
1867
- if (account.streamingMode === "progress") {
1868
- await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
1869
- return;
1870
- }
2147
+ if (account.streamingMode === "progress") return await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
1871
2148
  if (!lastPartialText) {
1872
2149
  const boundarySettled = enterBlockPreviewActivity("reasoning");
1873
2150
  draftStream.update("Thinking…");
1874
2151
  previewBoundaryController.noteUpdate();
1875
2152
  await boundarySettled;
1876
2153
  }
2154
+ return false;
1877
2155
  },
1878
2156
  onToolStart: async (payloadValue) => {
1879
- if (!draftToolProgressEnabled) return;
2157
+ if (!draftToolProgressEnabled) return false;
1880
2158
  const boundarySettled = enterBlockPreviewActivity("tool");
1881
2159
  const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
1882
2160
  event: "tool",
@@ -1887,10 +2165,11 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1887
2165
  args: payloadValue.args
1888
2166
  }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
1889
2167
  previewBoundaryController.noteUpdate();
1890
- await Promise.all([boundarySettled, progressSettled]);
2168
+ const [, visible] = await Promise.all([boundarySettled, progressSettled]);
2169
+ return visible;
1891
2170
  },
1892
2171
  onItemEvent: async (payloadLocal) => {
1893
- if (!draftToolProgressEnabled) return;
2172
+ if (!draftToolProgressEnabled) return false;
1894
2173
  const boundarySettled = enterBlockPreviewActivity("tool");
1895
2174
  const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
1896
2175
  event: "item",
@@ -1905,7 +2184,8 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1905
2184
  meta: payloadLocal.meta
1906
2185
  }), { startImmediately: true });
1907
2186
  previewBoundaryController.noteUpdate();
1908
- await Promise.all([boundarySettled, progressSettled]);
2187
+ const [, visible] = await Promise.all([boundarySettled, progressSettled]);
2188
+ return visible;
1909
2189
  }
1910
2190
  }
1911
2191
  })
@@ -1966,6 +2246,35 @@ function createMattermostPostHandler(monitor) {
1966
2246
  const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
1967
2247
  const rawPostText = typeof post.message === "string" ? post.message : "";
1968
2248
  const rawText = normalizeOptionalString(rawPostText) ?? "";
2249
+ const { effectiveReplyToId, sessionKey } = thread;
2250
+ const { envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
2251
+ cfg,
2252
+ agentId: route.agentId,
2253
+ sessionKey
2254
+ });
2255
+ const historyKey = resolveMattermostPendingHistoryKey({
2256
+ kind,
2257
+ sessionKey
2258
+ });
2259
+ const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2260
+ const nativeMedia = fileIds.map(() => ({}));
2261
+ const pendingBody = formatMattermostPendingMediaText({
2262
+ body: rawText,
2263
+ media: nativeMedia
2264
+ });
2265
+ const recordPendingHistory = () => {
2266
+ const trimmed = pendingBody.trim();
2267
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
2268
+ limit: historyLimit,
2269
+ historyKey: historyKey ?? "",
2270
+ entry: historyKey && trimmed ? {
2271
+ sender: senderName,
2272
+ body: trimmed,
2273
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2274
+ messageId: post.id
2275
+ } : null
2276
+ });
2277
+ };
1969
2278
  const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1970
2279
  cfg,
1971
2280
  surface: "mattermost"
@@ -2029,6 +2338,15 @@ function createMattermostPostHandler(monitor) {
2029
2338
  return;
2030
2339
  }
2031
2340
  if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
2341
+ if (shouldIncludeSupplementalContext({
2342
+ mode: resolveChannelContextVisibilityMode({
2343
+ cfg,
2344
+ channel: "mattermost",
2345
+ accountId: account.accountId
2346
+ }),
2347
+ kind: "history",
2348
+ senderAllowed: false
2349
+ })) recordPendingHistory();
2032
2350
  monitor.logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
2033
2351
  return;
2034
2352
  }
@@ -2044,32 +2362,8 @@ function createMattermostPostHandler(monitor) {
2044
2362
  });
2045
2363
  return;
2046
2364
  }
2047
- const { effectiveReplyToId, sessionKey } = thread;
2048
- const historyKey = resolveMattermostPendingHistoryKey({
2049
- kind,
2050
- sessionKey
2051
- });
2052
- const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2053
- const nativeMedia = fileIds.map(() => ({}));
2054
2365
  const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2055
2366
  const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2056
- const pendingBody = formatMattermostPendingMediaText({
2057
- body: rawText,
2058
- media: nativeMedia
2059
- });
2060
- const recordPendingHistory = () => {
2061
- const trimmed = pendingBody.trim();
2062
- createChannelHistoryWindow({ historyMap: channelHistories }).record({
2063
- limit: historyLimit,
2064
- historyKey: historyKey ?? "",
2065
- entry: historyKey && trimmed ? {
2066
- sender: senderName,
2067
- body: trimmed,
2068
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2069
- messageId: post.id
2070
- } : null
2071
- });
2072
- };
2073
2367
  const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2074
2368
  const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2075
2369
  const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
@@ -2151,7 +2445,9 @@ function createMattermostPostHandler(monitor) {
2151
2445
  sender: {
2152
2446
  name: senderName,
2153
2447
  id: senderId
2154
- }
2448
+ },
2449
+ previousTimestamp,
2450
+ envelope: envelopeOptions
2155
2451
  });
2156
2452
  if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2157
2453
  historyKey,
@@ -2163,7 +2459,8 @@ function createMattermostPostHandler(monitor) {
2163
2459
  timestamp: entry.timestamp,
2164
2460
  body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2165
2461
  chatType: kind,
2166
- senderLabel: entry.sender
2462
+ senderLabel: entry.sender,
2463
+ envelope: envelopeOptions
2167
2464
  })
2168
2465
  });
2169
2466
  const commandBody = rawText.trim();
@@ -2189,7 +2486,7 @@ function createMattermostPostHandler(monitor) {
2189
2486
  WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2190
2487
  CommandAuthorized: commandAuthorized,
2191
2488
  CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2192
- ...buildMattermostInboundMediaPayload(mediaList)
2489
+ ...await buildMattermostInboundMediaPayload(mediaList)
2193
2490
  });
2194
2491
  const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2195
2492
  dmScope: cfg.session?.dmScope,
@@ -2345,7 +2642,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2345
2642
  const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
2346
2643
  const slashCallbackUrl = resolveCallbackUrl({
2347
2644
  config: slashConfig,
2348
- gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
2645
+ gatewayPort: resolveGatewayPort(params.cfg),
2349
2646
  gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
2350
2647
  });
2351
2648
  warnOnSuspiciousCallbackUrl({
@@ -2466,6 +2763,13 @@ function sleepAbortable(ms, signal) {
2466
2763
  }
2467
2764
  //#endregion
2468
2765
  //#region extensions/mattermost/src/mattermost/monitor.ts
2766
+ function publishMattermostRecoveringStatus(statusSink, error) {
2767
+ statusSink?.({
2768
+ lastError: String(error),
2769
+ connected: false,
2770
+ lifecycle: "recovering"
2771
+ });
2772
+ }
2469
2773
  async function monitorMattermostProvider(opts = {}) {
2470
2774
  const core = getMattermostRuntime();
2471
2775
  const runtime = opts.runtime ?? {
@@ -2503,10 +2807,7 @@ async function monitorMattermostProvider(opts = {}) {
2503
2807
  shouldReconnect: ({ outcome }) => outcome === "rejected",
2504
2808
  onError: (err) => {
2505
2809
  runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
2506
- opts.statusSink?.({
2507
- lastError: String(err),
2508
- connected: false
2509
- });
2810
+ publishMattermostRecoveringStatus(opts.statusSink, err);
2510
2811
  },
2511
2812
  onReconnect: (delayMs) => {
2512
2813
  runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
@@ -2516,15 +2817,6 @@ async function monitorMattermostProvider(opts = {}) {
2516
2817
  const botUserId = botUser.id;
2517
2818
  const botUsername = normalizeOptionalString(botUser.username);
2518
2819
  runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
2519
- await registerMattermostMonitorSlashCommands({
2520
- client,
2521
- cfg,
2522
- runtime,
2523
- account,
2524
- baseUrl,
2525
- botUserId
2526
- });
2527
- const slashEnabled = getSlashCommandState(account.accountId) != null;
2528
2820
  setInteractionSecret(account.accountId, botToken);
2529
2821
  const interactionPath = resolveInteractionCallbackPath(account.accountId);
2530
2822
  const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
@@ -2548,7 +2840,7 @@ async function monitorMattermostProvider(opts = {}) {
2548
2840
  resolveChannelLimitMb: () => void 0,
2549
2841
  accountId: account.accountId
2550
2842
  }) ?? 8 * 1024 * 1024;
2551
- const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
2843
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy$1({
2552
2844
  providerConfigPresent: cfg.channels?.mattermost !== void 0,
2553
2845
  groupPolicy: account.config.groupPolicy,
2554
2846
  defaultGroupPolicy: resolveDefaultGroupPolicy(cfg)
@@ -2588,6 +2880,20 @@ async function monitorMattermostProvider(opts = {}) {
2588
2880
  allowedSourceIps: allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"],
2589
2881
  handleModelPickerInteraction: createMattermostModelPickerInteractionHandler(monitor)
2590
2882
  });
2883
+ try {
2884
+ await registerMattermostMonitorSlashCommands({
2885
+ client,
2886
+ cfg,
2887
+ runtime,
2888
+ account,
2889
+ baseUrl,
2890
+ botUserId
2891
+ });
2892
+ } catch (error) {
2893
+ unregisterInteractions();
2894
+ throw error;
2895
+ }
2896
+ const slashEnabled = getSlashCommandState(account.accountId) != null;
2591
2897
  const handlePost = createMattermostPostHandler(monitor);
2592
2898
  const handleReactionEvent = createMattermostReactionHandler(monitor);
2593
2899
  const debouncer = core.channel.debounce.createInboundDebouncer({
@@ -2606,27 +2912,32 @@ async function monitorMattermostProvider(opts = {}) {
2606
2912
  const text = normalizeOptionalString(entry.post.message) ?? "";
2607
2913
  return Boolean(text) && !core.channel.commands.isControlCommandMessage(text, cfg);
2608
2914
  },
2609
- onFlush: async (entries) => {
2915
+ onFlush: (entries, createFlush) => {
2610
2916
  const last = entries.at(-1);
2611
- if (!last) return;
2612
2917
  const { lifecycle, settle } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
2613
- try {
2614
- if (entries.length === 1) {
2615
- await handlePost(last.post, last.payload, lifecycle);
2616
- await settle();
2617
- return;
2918
+ return createFlush({
2919
+ lifecycle,
2920
+ dispatch: async (admissionLifecycle) => {
2921
+ if (!last) return;
2922
+ try {
2923
+ if (entries.length === 1) {
2924
+ await handlePost(last.post, last.payload, admissionLifecycle);
2925
+ await settle();
2926
+ return;
2927
+ }
2928
+ const mergedPost = {
2929
+ ...last.post,
2930
+ message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2931
+ file_ids: []
2932
+ };
2933
+ await handlePost(mergedPost, last.payload, admissionLifecycle, entries.map((entry) => entry.post.id));
2934
+ await settle();
2935
+ } catch (error) {
2936
+ await admissionLifecycle.onAbandoned();
2937
+ throw error;
2938
+ }
2618
2939
  }
2619
- const mergedPost = {
2620
- ...last.post,
2621
- message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2622
- file_ids: []
2623
- };
2624
- await handlePost(mergedPost, last.payload, lifecycle, entries.map((entry) => entry.post.id));
2625
- await settle();
2626
- } catch (error) {
2627
- await lifecycle?.onAbandoned();
2628
- throw error;
2629
- }
2940
+ });
2630
2941
  },
2631
2942
  onError: (err) => {
2632
2943
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
@@ -2681,10 +2992,7 @@ async function monitorMattermostProvider(opts = {}) {
2681
2992
  jitterRatio: .2,
2682
2993
  onError: (err) => {
2683
2994
  runtime.error?.(`mattermost connection failed: ${String(err)}`);
2684
- opts.statusSink?.({
2685
- lastError: String(err),
2686
- connected: false
2687
- });
2995
+ publishMattermostRecoveringStatus(opts.statusSink, err);
2688
2996
  },
2689
2997
  onReconnect: (delayMs) => {
2690
2998
  runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
@@ -2692,7 +3000,7 @@ async function monitorMattermostProvider(opts = {}) {
2692
3000
  });
2693
3001
  } finally {
2694
3002
  await ingress.stop();
2695
- unregisterInteractions?.();
3003
+ unregisterInteractions();
2696
3004
  }
2697
3005
  const slashShutdownCleanupPromise = slashShutdownCleanup;
2698
3006
  if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
@@ -2870,4 +3178,71 @@ async function deleteReaction(client, params) {
2870
3178
  await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, { method: "DELETE" });
2871
3179
  }
2872
3180
  //#endregion
2873
- export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };
3181
+ //#region extensions/mattermost/src/mattermost/read.ts
3182
+ function parseMattermostChannelTarget(rawTarget) {
3183
+ const normalized = normalizeMattermostMessagingTarget(rawTarget);
3184
+ if (normalized?.startsWith("channel:")) return normalized.slice(8).trim() || void 0;
3185
+ const trimmed = rawTarget.trim();
3186
+ return trimmed && !trimmed.includes(":") ? trimmed : void 0;
3187
+ }
3188
+ function isCurrentMattermostReadTarget(params) {
3189
+ const toolContext = params.context.toolContext;
3190
+ const requesterAccountId = params.context.requesterAccountId?.trim();
3191
+ if (normalizeLowercaseStringOrEmpty(toolContext?.currentChannelProvider) !== "mattermost" || !requesterAccountId || normalizeAccountId(requesterAccountId) !== normalizeAccountId(params.accountId)) return false;
3192
+ const nativeChannelId = toolContext?.currentChannelId;
3193
+ if (typeof nativeChannelId === "string" && nativeChannelId.trim()) return parseMattermostChannelTarget(nativeChannelId) === params.channelId;
3194
+ const messagingTarget = toolContext?.currentMessagingTarget;
3195
+ return typeof messagingTarget === "string" && Boolean(messagingTarget.trim()) && parseMattermostChannelTarget(messagingTarget) === params.channelId;
3196
+ }
3197
+ function isConfiguredMattermostReadTarget(params) {
3198
+ const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
3199
+ providerConfigPresent: params.cfg.channels?.mattermost !== void 0,
3200
+ groupPolicy: params.account.config.groupPolicy,
3201
+ defaultGroupPolicy: params.cfg.channels?.defaults?.groupPolicy
3202
+ });
3203
+ if (groupPolicy === "disabled") return false;
3204
+ if (groupPolicy === "open") return true;
3205
+ const groups = params.account.config.groups;
3206
+ return groups?.[params.channelId] !== void 0 || groups?.["*"] !== void 0;
3207
+ }
3208
+ async function readMattermostMessages(params) {
3209
+ const account = resolveMattermostAccount({
3210
+ cfg: params.cfg,
3211
+ accountId: params.accountId
3212
+ });
3213
+ if (!account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
3214
+ const baseUrl = account.baseUrl?.trim();
3215
+ const botToken = account.botToken?.trim();
3216
+ if (!baseUrl || !botToken) throw new Error("Mattermost botToken/baseUrl missing.");
3217
+ const client = createMattermostClient({
3218
+ baseUrl,
3219
+ botToken,
3220
+ fetchImpl: params.fetchImpl,
3221
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
3222
+ });
3223
+ const directOperator = params.context.conversationReadOrigin === "direct-operator";
3224
+ const currentConversation = isCurrentMattermostReadTarget({
3225
+ accountId: account.accountId,
3226
+ channelId: params.channelId,
3227
+ context: params.context
3228
+ });
3229
+ if (!directOperator && !currentConversation) {
3230
+ const requesterAccountId = params.context.requesterAccountId?.trim();
3231
+ const sameProvider = normalizeLowercaseStringOrEmpty(params.context.toolContext?.currentChannelProvider) === "mattermost";
3232
+ const sameAccount = requesterAccountId && normalizeAccountId(requesterAccountId) === normalizeAccountId(account.accountId);
3233
+ if (!sameProvider || !sameAccount) throw new Error("Mattermost delegated reads require the current Mattermost account.");
3234
+ const channel = await fetchMattermostChannel(client, params.channelId);
3235
+ if (channel.type !== "O" && channel.type !== "P" || !isConfiguredMattermostReadTarget({
3236
+ cfg: params.cfg,
3237
+ account,
3238
+ channelId: params.channelId
3239
+ })) throw new Error("Mattermost read target channel is not allowed.");
3240
+ }
3241
+ return await fetchMattermostChannelPosts(client, params.channelId, {
3242
+ limit: params.limit,
3243
+ before: params.before,
3244
+ after: params.after
3245
+ });
3246
+ }
3247
+ //#endregion
3248
+ export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, readMattermostMessages, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };