@openclaw/mattermost 2026.7.2-beta.5 → 2026.7.2-beta.7

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,10 +1,10 @@
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 { _ as sendMattermostTyping, a as createMattermostPost, d as fetchMattermostUser, h 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 updateMattermostPost } from "./client-CqqzTcno.js";
3
+ import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy$1, 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-rctDliGZ.js";
4
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-BQXY_48h.js";
5
+ import { a as resolveMattermostReplyToMode, i as resolveMattermostAccount, n as listMattermostAccountIds, t as inspectMattermostAccount } from "./accounts-NaMdx9yF.js";
6
+ import { a as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-DlrMaSIu.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-DM8qmFJR.js";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
10
10
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -13,11 +13,14 @@ import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveTimerTimeou
13
13
  import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
14
14
  import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
15
15
  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";
16
+ import { buildChannelInboundMediaPayload, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
17
+ import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createMessageReceiptFromOutboundResults, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
18
+ import { resolveAllowlistProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
18
19
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
19
20
  import { fanInChannelIngressLifecycles, resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
20
- import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
21
+ import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
22
+ import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
23
+ import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
21
24
  import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
22
25
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
23
26
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
@@ -27,11 +30,14 @@ import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
27
30
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
28
31
  import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
29
32
  import WebSocket from "ws";
33
+ import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
34
+ import { resolveChannelContextVisibilityMode, shouldIncludeSupplementalContext } from "openclaw/plugin-sdk/context-visibility-runtime";
35
+ import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
30
36
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
31
37
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
32
38
  //#region extensions/mattermost/src/mattermost/directory.ts
33
39
  function buildClient(params) {
34
- const account = resolveMattermostAccount({
40
+ const account = inspectMattermostAccount({
35
41
  cfg: params.cfg,
36
42
  accountId: params.accountId
37
43
  });
@@ -93,7 +99,7 @@ async function listMattermostDirectoryGroups(params) {
93
99
  }
94
100
  seenIds.add(ch.id);
95
101
  entries.push({
96
- kind: "group",
102
+ kind: resolveMattermostTrustedChatKind({ channelType: ch.type }) === "group" ? "group" : "channel",
97
103
  id: `channel:${ch.id}`,
98
104
  name: ch.name ?? void 0,
99
105
  handle: ch.display_name ?? void 0
@@ -485,21 +491,7 @@ function reasonToString(reason) {
485
491
  //#region extensions/mattermost/src/mattermost/monitor-ingress.ts
486
492
  const MATTERMOST_INGRESS_PAYLOAD_VERSION = 1;
487
493
  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
- }
494
+ const MattermostIngressPermanentError = createChannelIngressError("MattermostIngressPermanentError", { withReason: true });
503
495
  function parseRawObject(raw, subject) {
504
496
  let parsed;
505
497
  try {
@@ -583,13 +575,7 @@ function createMattermostIngressMonitor(options) {
583
575
  },
584
576
  pollIntervalMs: options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS,
585
577
  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
- },
578
+ retention: "standard",
593
579
  drain: {
594
580
  resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
595
581
  ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
@@ -640,7 +626,7 @@ function formatMattermostNoVisibleReplyLog(params) {
640
626
  //#endregion
641
627
  //#region extensions/mattermost/src/mattermost/monitor-context.ts
642
628
  function shouldUpdateMattermostDraftToolProgress(account) {
643
- return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
629
+ return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, true, account.streamingMode);
644
630
  }
645
631
  function shouldSuppressMattermostDefaultToolProgressMessages(account) {
646
632
  return account.streamingMode !== "off";
@@ -650,12 +636,25 @@ function buildMattermostModelPickerSelectMessageSid(params) {
650
636
  const model = normalizeLowercaseStringOrEmpty(params.model);
651
637
  return `interaction:${params.postId}:select:${provider}/${model}`;
652
638
  }
639
+ function buildMattermostButtonInteractionMessageSid(params) {
640
+ return `interaction:${params.postId}:${params.actionId}`;
641
+ }
653
642
  function resolveMattermostReplyRootId(params) {
654
643
  const threadRootId = normalizeOptionalString(params.threadRootId);
655
644
  if (params.kind === "direct" && !threadRootId) return;
656
645
  if (threadRootId) return threadRootId;
657
646
  return normalizeOptionalString(params.replyToId);
658
647
  }
648
+ function resolveMattermostInteractionReplyRootId(params) {
649
+ const interactionMessageSid = normalizeOptionalString(params.interactionMessageSid);
650
+ const replyToId = normalizeOptionalString(params.replyToId);
651
+ const providerReplyToId = replyToId === interactionMessageSid ? normalizeOptionalString(params.sourcePostId) : replyToId;
652
+ return resolveMattermostReplyRootId({
653
+ kind: params.kind,
654
+ threadRootId: params.threadRootId,
655
+ replyToId: providerReplyToId
656
+ });
657
+ }
659
658
  function canFinalizeMattermostPreviewInPlace(params) {
660
659
  return resolveMattermostReplyRootId({
661
660
  kind: params.kind,
@@ -859,10 +858,15 @@ function registerMattermostInteractions(params) {
859
858
  return eventPlan.thread.sessionKey;
860
859
  },
861
860
  dispatchButtonClick: async (button) => {
861
+ const sourcePostId = button.post.id || button.postId;
862
+ const interactionMessageSid = buildMattermostButtonInteractionMessageSid({
863
+ postId: button.postId,
864
+ actionId: button.actionId
865
+ });
862
866
  const eventPlan = await buildMattermostEventPlan(monitor, {
863
867
  channelId: button.channelId,
864
868
  senderId: button.userId,
865
- postId: button.post.id || button.postId,
869
+ postId: sourcePostId,
866
870
  threadRootId: button.post.root_id,
867
871
  dropLabel: "interaction dispatch"
868
872
  });
@@ -877,7 +881,7 @@ function registerMattermostInteractions(params) {
877
881
  ConversationLabel: `mattermost:${button.userName}`,
878
882
  GroupSubject: kind !== "direct" ? channelDisplay || button.channelId : void 0,
879
883
  SenderName: button.userName,
880
- MessageSid: `interaction:${button.postId}:${button.actionId}`,
884
+ MessageSid: interactionMessageSid,
881
885
  WasMentioned: true,
882
886
  CommandAuthorized: false
883
887
  });
@@ -893,24 +897,27 @@ function registerMattermostInteractions(params) {
893
897
  },
894
898
  ctxPayload,
895
899
  delivery: {
900
+ observeMessageSent: true,
896
901
  deliver: async (payload) => {
897
- const result = toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
902
+ const result = await deliverMattermostReplyPayload({
898
903
  core,
899
904
  cfg,
900
905
  payload,
901
906
  to,
902
907
  accountId: account.accountId,
903
908
  agentId: route.agentId,
904
- replyToId: resolveMattermostReplyRootId({
909
+ replyToId: resolveMattermostInteractionReplyRootId({
905
910
  kind,
906
911
  threadRootId: thread.effectiveReplyToId,
907
- replyToId: payload.replyToId
912
+ replyToId: payload.replyToId,
913
+ interactionMessageSid,
914
+ sourcePostId
908
915
  }),
909
916
  textLimit,
910
917
  tableMode,
911
918
  sendMessage: sendMessageMattermost,
912
919
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
913
- }));
920
+ });
914
921
  if (result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
915
922
  return result;
916
923
  },
@@ -969,28 +976,31 @@ function createMattermostModelPickerInteractionHandler(monitor) {
969
976
  },
970
977
  ctxPayload,
971
978
  delivery: {
979
+ observeMessageSent: true,
972
980
  deliver: async (payload) => {
973
981
  const trimmedPayload = {
974
982
  ...payload,
975
983
  text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
976
984
  };
977
- return toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
985
+ return await deliverMattermostReplyPayload({
978
986
  core,
979
987
  cfg,
980
988
  payload: trimmedPayload,
981
989
  to,
982
990
  accountId: account.accountId,
983
991
  agentId: route.agentId,
984
- replyToId: resolveMattermostReplyRootId({
992
+ replyToId: resolveMattermostInteractionReplyRootId({
985
993
  kind,
986
994
  threadRootId: thread.effectiveReplyToId,
987
- replyToId: trimmedPayload.replyToId
995
+ replyToId: trimmedPayload.replyToId,
996
+ interactionMessageSid: params.messageSid,
997
+ sourcePostId: params.sourcePostId
988
998
  }),
989
999
  textLimit,
990
1000
  tableMode: "off",
991
1001
  sendMessage: sendMessageMattermost,
992
1002
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
993
- }));
1003
+ });
994
1004
  },
995
1005
  onError: (err, info) => {
996
1006
  runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
@@ -1094,37 +1104,37 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1094
1104
  }
1095
1105
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
1096
1106
  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
- })();
1107
+ const messageSid = buildMattermostModelPickerSelectMessageSid({
1108
+ postId: params.payload.post_id,
1109
+ provider: pickerState.provider,
1110
+ model: pickerState.model
1111
+ });
1112
+ runDetachedWebhookWork(async () => {
1113
+ await runModelPickerCommand({
1114
+ commandText: `/model ${targetModelRef}`,
1115
+ commandAuthorized: auth.commandAuthorized,
1116
+ eventPlan,
1117
+ senderName: params.userName,
1118
+ messageSid,
1119
+ sourcePostId: params.post.id || params.payload.post_id
1120
+ });
1121
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1122
+ cfg,
1123
+ route: modelSessionRoute,
1124
+ data,
1125
+ readConsistency: "latest"
1126
+ });
1127
+ const view = renderMattermostModelsPickerView({
1128
+ ownerUserId: pickerState.ownerUserId,
1129
+ data,
1130
+ provider: pickerState.provider,
1131
+ page: pickerState.page,
1132
+ currentModel
1133
+ });
1134
+ await updatePickerPost(view.text, view.buttons);
1135
+ }).catch((err) => {
1136
+ runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
1137
+ });
1128
1138
  return {};
1129
1139
  };
1130
1140
  }
@@ -1175,8 +1185,12 @@ function stripOncharPrefix(text, prefixes) {
1175
1185
  }
1176
1186
  //#endregion
1177
1187
  //#region extensions/mattermost/src/mattermost/monitor-resources.ts
1178
- function buildMattermostInboundMediaPayload(media) {
1179
- return buildChannelInboundMediaPayload(toInboundMediaFacts(media));
1188
+ async function buildMattermostInboundMediaPayload(media) {
1189
+ const facts = await toInboundMediaFactsWithMetadata(media);
1190
+ return {
1191
+ ...buildChannelInboundMediaPayload(facts),
1192
+ media: facts
1193
+ };
1180
1194
  }
1181
1195
  function formatMattermostPendingMediaText(params) {
1182
1196
  return [params.body, formatMediaPlaceholderText(params.media)].filter(Boolean).join("\n").trim();
@@ -1327,6 +1341,13 @@ function normalizeMattermostDraftText(text, maxChars) {
1327
1341
  if (trimmed.length <= maxChars) return trimmed;
1328
1342
  return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
1329
1343
  }
1344
+ function consumeMattermostPublishedChunk(params) {
1345
+ const chunk = params.chunk.trim();
1346
+ if (!chunk) return params.offset;
1347
+ let offset = params.offset;
1348
+ while (offset < params.source.length && /\s/.test(params.source[offset] ?? "")) offset += 1;
1349
+ return params.source.startsWith(chunk, offset) ? offset + chunk.length : void 0;
1350
+ }
1330
1351
  function createMattermostDraftPreviewBoundaryController(params) {
1331
1352
  let hasStreamedContent = false;
1332
1353
  return {
@@ -1354,6 +1375,10 @@ function createMattermostDraftStream(params) {
1354
1375
  ready: Promise.resolve()
1355
1376
  };
1356
1377
  const sealedAssistantTexts = [];
1378
+ const publishedAssistantParts = /* @__PURE__ */ new Map();
1379
+ const trackPublishedAssistantPart = (part) => {
1380
+ publishedAssistantParts.set(part.messageId, part);
1381
+ };
1357
1382
  const sendOrEditStreamMessage = async (text) => {
1358
1383
  if (streamState.stopped && !streamState.final) return false;
1359
1384
  const target = currentGeneration;
@@ -1363,19 +1388,21 @@ function createMattermostDraftStream(params) {
1363
1388
  if (streamState.stopped && !streamState.final) return false;
1364
1389
  if (normalized === target.lastSentText) return true;
1365
1390
  try {
1366
- if (target.postId) await updateMattermostPost(params.client, target.postId, { message: normalized });
1391
+ if (target.postId) target.lastProviderText = (await updateMattermostPost(params.client, target.postId, { message: normalized })).message ?? normalized;
1367
1392
  else {
1368
- const postId = (await createMattermostPost(params.client, {
1393
+ const sent = await createMattermostPost(params.client, {
1369
1394
  channelId: params.channelId,
1370
1395
  message: normalized,
1371
1396
  rootId: params.rootId
1372
- })).id?.trim();
1397
+ });
1398
+ const postId = sent.id?.trim();
1373
1399
  if (!postId) {
1374
1400
  streamState.stopped = true;
1375
1401
  params.warn?.("mattermost stream preview stopped (missing post id from create)");
1376
1402
  return false;
1377
1403
  }
1378
1404
  target.postId = postId;
1405
+ target.lastProviderText = sent.message ?? normalized;
1379
1406
  }
1380
1407
  target.lastSentText = normalized;
1381
1408
  return true;
@@ -1408,6 +1435,8 @@ function createMattermostDraftStream(params) {
1408
1435
  const pendingText = loop.takePending();
1409
1436
  const inFlightAtBoundary = loop.waitForInFlight();
1410
1437
  const sealed = currentGeneration;
1438
+ const assistantText = sealed.latestAssistantText?.trim();
1439
+ let publishedAssistantOffset = 0;
1411
1440
  const boundary = (async () => {
1412
1441
  try {
1413
1442
  await sealed.ready;
@@ -1419,20 +1448,83 @@ function createMattermostDraftStream(params) {
1419
1448
  const firstChunk = chunks[0];
1420
1449
  if (!firstChunk) return;
1421
1450
  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
1451
+ if (assistantText && (sealed.lastProviderText || sealed.lastSentText)) {
1452
+ const publishedContent = sealed.lastProviderText ?? sealed.lastSentText;
1453
+ trackPublishedAssistantPart({
1454
+ messageId: sealed.postId,
1455
+ content: publishedContent
1456
+ });
1457
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1458
+ source: assistantText,
1459
+ offset: 0,
1460
+ chunk: publishedContent
1461
+ }) ?? 0;
1462
+ }
1463
+ let providerFirstChunk = sealed.lastProviderText ?? firstChunk;
1464
+ if (firstChunk !== sealed.lastSentText) providerFirstChunk = (await updateMattermostPost(params.client, sealed.postId, { message: firstChunk })).message ?? firstChunk;
1465
+ if (assistantText) {
1466
+ trackPublishedAssistantPart({
1467
+ messageId: sealed.postId,
1468
+ content: providerFirstChunk
1469
+ });
1470
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1471
+ source: assistantText,
1472
+ offset: 0,
1473
+ chunk: providerFirstChunk
1474
+ }) ?? 0;
1475
+ }
1476
+ } else {
1477
+ const firstPost = await createMattermostPost(params.client, {
1478
+ channelId: params.channelId,
1479
+ message: firstChunk,
1480
+ rootId: params.rootId
1481
+ });
1482
+ const firstPostId = firstPost.id?.trim();
1483
+ if (!firstPostId) throw new Error("missing post id from boundary create");
1484
+ if (assistantText) {
1485
+ const publishedContent = firstPost.message ?? firstChunk;
1486
+ trackPublishedAssistantPart({
1487
+ messageId: firstPostId,
1488
+ content: publishedContent
1489
+ });
1490
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1491
+ source: assistantText,
1492
+ offset: 0,
1493
+ chunk: publishedContent
1494
+ }) ?? 0;
1495
+ }
1496
+ }
1497
+ for (const chunk of chunks.slice(1)) {
1498
+ const post = await createMattermostPost(params.client, {
1499
+ channelId: params.channelId,
1500
+ message: chunk,
1501
+ rootId: params.rootId
1502
+ });
1503
+ const postId = post.id?.trim();
1504
+ if (!postId) throw new Error("missing post id from boundary create");
1505
+ if (assistantText) {
1506
+ const publishedContent = post.message ?? chunk;
1507
+ trackPublishedAssistantPart({
1508
+ messageId: postId,
1509
+ content: publishedContent
1510
+ });
1511
+ publishedAssistantOffset = consumeMattermostPublishedChunk({
1512
+ source: assistantText,
1513
+ offset: publishedAssistantOffset,
1514
+ chunk: publishedContent
1515
+ }) ?? publishedAssistantOffset;
1516
+ }
1517
+ }
1518
+ if (assistantText) sealedAssistantTexts.push({
1519
+ text: assistantText,
1520
+ requiresBlockBoundary: true
1432
1521
  });
1433
- const assistantText = sealed.latestAssistantText?.trim();
1434
- if (assistantText) sealedAssistantTexts.push(assistantText);
1435
1522
  } catch (err) {
1523
+ const publishedAssistantPrefix = assistantText?.slice(0, publishedAssistantOffset).trim();
1524
+ if (publishedAssistantPrefix) sealedAssistantTexts.push({
1525
+ text: publishedAssistantPrefix,
1526
+ requiresBlockBoundary: false
1527
+ });
1436
1528
  params.warn?.(`mattermost stream preview boundary flush failed: ${err instanceof Error ? err.message : String(err)}`);
1437
1529
  }
1438
1530
  })();
@@ -1477,34 +1569,43 @@ function createMattermostDraftStream(params) {
1477
1569
  await currentGeneration.ready;
1478
1570
  };
1479
1571
  const resolveFinalText = (text) => {
1572
+ const publishedParts = [...publishedAssistantParts.values()];
1480
1573
  if (sealedAssistantTexts.length === 0) return {
1481
1574
  kind: "full",
1482
- text
1575
+ text,
1576
+ publishedParts
1483
1577
  };
1484
1578
  let remainingText = text.trim();
1485
1579
  for (const sealedText of sealedAssistantTexts) {
1486
- const completed = sealedText.trim();
1580
+ const completed = sealedText.text.trim();
1487
1581
  if (!completed || !remainingText.startsWith(completed)) return {
1488
1582
  kind: "full",
1489
- text
1583
+ text,
1584
+ publishedParts
1490
1585
  };
1491
1586
  const suffix = remainingText.slice(completed.length);
1492
- if (suffix && !/^\r?\n/.test(suffix)) return {
1587
+ if (sealedText.requiresBlockBoundary && suffix && !/^\r?\n/.test(suffix)) return {
1493
1588
  kind: "full",
1494
- text
1589
+ text,
1590
+ publishedParts
1495
1591
  };
1496
- remainingText = suffix.replace(/^(?:\r?\n)+/, "");
1592
+ remainingText = suffix.replace(sealedText.requiresBlockBoundary ? /^(?:\r?\n)+/ : /^\s+/, "");
1497
1593
  }
1498
1594
  const currentText = currentGeneration.latestAssistantText?.trim() ?? "";
1499
1595
  const remaining = remainingText.trim();
1500
1596
  if (currentText && !remaining.startsWith(currentText)) return {
1501
1597
  kind: "full",
1502
- text
1598
+ text,
1599
+ publishedParts
1503
1600
  };
1504
1601
  return remaining ? {
1505
1602
  kind: "remaining",
1506
- text: remaining
1507
- } : { kind: "already-delivered" };
1603
+ text: remaining,
1604
+ publishedParts
1605
+ } : {
1606
+ kind: "already-delivered",
1607
+ publishedParts
1608
+ };
1508
1609
  };
1509
1610
  params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
1510
1611
  return {
@@ -1523,54 +1624,145 @@ function createMattermostDraftStream(params) {
1523
1624
  }
1524
1625
  //#endregion
1525
1626
  //#region extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
1627
+ function combineMattermostVisibleDeliveryResults(results) {
1628
+ const visibleResults = results.filter((result) => result?.visibleReplySent === true);
1629
+ if (visibleResults.length === 0) return;
1630
+ const receiptResults = [];
1631
+ for (const result of visibleResults) if (result.receipt) receiptResults.push({ receipt: result.receipt });
1632
+ else receiptResults.push(...(result.messageIds ?? []).map((messageId) => ({ messageId })));
1633
+ const receipt = createMessageReceiptFromOutboundResults({ results: receiptResults });
1634
+ return {
1635
+ outcome: visibleResults.some((result) => result.outcome === "media") ? "media" : "text",
1636
+ messageIds: listMessageReceiptPlatformIds(receipt),
1637
+ receipt,
1638
+ visibleReplySent: true,
1639
+ content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1640
+ };
1641
+ }
1526
1642
  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)})`);
1643
+ if (isReasoningReplyPayload(params.payload)) return {
1644
+ outcome: "reasoning_skipped",
1645
+ visibleReplySent: false,
1646
+ suppression: { reason: "no_visible_result" }
1647
+ };
1648
+ let normalDeliveryResult;
1649
+ let supplementalDeliveryResult;
1650
+ let previewDeliveryResult;
1651
+ let confirmedPreviewDelivery;
1652
+ let previewFinalDeliveryText;
1653
+ let previewFinalTextAlreadyDelivered = false;
1654
+ let useConfirmedPreviewAsWholeFinal = false;
1655
+ let pendingPreviewFinalContent;
1656
+ let finalizedPreviewPost;
1657
+ try {
1658
+ if ((await deliverWithFinalizableLivePreviewAdapter({
1659
+ kind: params.info.kind,
1660
+ payload: params.payload,
1661
+ adapter: defineFinalizableLivePreviewAdapter({
1662
+ ...params.previewState.finalizedViaPreviewPost ? {} : { draft: {
1663
+ flush: params.draftStream.flush,
1664
+ clear: params.draftStream.clear,
1665
+ discardPending: params.draftStream.discardPending,
1666
+ seal: params.draftStream.seal,
1667
+ id: params.draftStream.postId
1668
+ } },
1669
+ buildFinalEdit: (payload) => {
1670
+ const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
1671
+ const ttsSupplement = getReplyPayloadTtsSupplement(payload);
1672
+ const previewFinalResolution = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
1673
+ confirmedPreviewDelivery = previewFinalResolution?.confirmedDelivery;
1674
+ previewFinalDeliveryText = previewFinalResolution?.deliveryText;
1675
+ previewFinalTextAlreadyDelivered = previewFinalResolution?.alreadyDelivered === true && payload.isError !== true;
1676
+ useConfirmedPreviewAsWholeFinal = previewFinalTextAlreadyDelivered && !resolveSendableOutboundReplyParts(payload).hasMedia;
1677
+ const previewFinalText = previewFinalResolution?.editText;
1678
+ if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1679
+ kind: params.kind,
1680
+ previewRootId: params.effectiveReplyToId,
1681
+ threadRootId: params.effectiveReplyToId,
1682
+ replyToId: payload.replyToId
1683
+ })) return;
1684
+ pendingPreviewFinalContent = previewFinalText;
1685
+ return { message: previewFinalText };
1686
+ },
1687
+ editFinal: async (previewPostId, edit) => {
1688
+ finalizedPreviewPost = await updateMattermostPost(params.client, previewPostId, edit);
1689
+ },
1690
+ resolveFinalizedId: (previewPostId) => finalizedPreviewPost?.id ?? previewPostId,
1691
+ onPreviewFinalized: (_previewPostId, receipt) => {
1692
+ params.previewState.finalizedViaPreviewPost = true;
1693
+ previewDeliveryResult = {
1694
+ outcome: "text",
1695
+ messageIds: listMessageReceiptPlatformIds(receipt),
1696
+ receipt,
1697
+ visibleReplySent: true,
1698
+ content: finalizedPreviewPost?.message ?? pendingPreviewFinalContent ?? ""
1699
+ };
1700
+ params.recordThreadParticipation?.();
1701
+ },
1702
+ buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
1703
+ deliverSupplemental: async (payload) => {
1704
+ supplementalDeliveryResult = await params.deliverPayload(payload);
1705
+ return supplementalDeliveryResult.visibleReplySent;
1706
+ },
1707
+ logPreviewEditFailure: (err) => {
1708
+ params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
1709
+ }
1710
+ }),
1711
+ deliverNormally: async (payload) => {
1712
+ if (useConfirmedPreviewAsWholeFinal && confirmedPreviewDelivery?.visibleReplySent === true) return true;
1713
+ const supplement = getReplyPayloadTtsSupplement(payload);
1714
+ const resolvedDeliveryText = previewFinalDeliveryText ?? (previewFinalTextAlreadyDelivered ? "" : void 0);
1715
+ const payloadText = payload.text?.trim();
1716
+ const deliveryPayload = payload.isError !== true && supplement && (previewFinalTextAlreadyDelivered || !payloadText && supplement.visibleTextAlreadyDelivered === true) ? buildTtsSupplementMediaPayload(payload) : payload.isError !== true && supplement && !payloadText ? {
1717
+ ...payload,
1718
+ text: resolvedDeliveryText?.trim() ? resolvedDeliveryText : supplement.spokenText
1719
+ } : payload.isError !== true && typeof resolvedDeliveryText === "string" ? {
1720
+ ...payload,
1721
+ text: resolvedDeliveryText
1722
+ } : payload;
1723
+ normalDeliveryResult = await params.deliverPayload(deliveryPayload);
1724
+ return normalDeliveryResult.visibleReplySent;
1564
1725
  }
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);
1726
+ })).kind !== "preview-finalized" || !previewDeliveryResult?.receipt) return combineMattermostVisibleDeliveryResults([confirmedPreviewDelivery, normalDeliveryResult]) ?? {
1727
+ outcome: "empty",
1728
+ visibleReplySent: false,
1729
+ suppression: { reason: "no_visible_result" }
1730
+ };
1731
+ return combineMattermostVisibleDeliveryResults([
1732
+ confirmedPreviewDelivery,
1733
+ previewDeliveryResult,
1734
+ supplementalDeliveryResult
1735
+ ]) ?? previewDeliveryResult;
1736
+ } catch (error) {
1737
+ const completedVisibleResults = [];
1738
+ const completedReceiptResults = [];
1739
+ for (const result of [
1740
+ confirmedPreviewDelivery,
1741
+ previewDeliveryResult,
1742
+ normalDeliveryResult,
1743
+ supplementalDeliveryResult
1744
+ ]) {
1745
+ if (result?.visibleReplySent !== true) continue;
1746
+ completedVisibleResults.push(result);
1747
+ if (result.receipt) completedReceiptResults.push({ receipt: result.receipt });
1748
+ else completedReceiptResults.push(...(result.messageIds ?? []).map((messageId) => ({ messageId })));
1572
1749
  }
1573
- });
1750
+ if (completedVisibleResults.length === 0) throw error;
1751
+ const failedPartial = isChannelPartialDeliveryError(error) ? error.deliveryResult : void 0;
1752
+ const receipt = createMessageReceiptFromOutboundResults({ results: [...completedReceiptResults, ...failedPartial?.receipt ? [{ receipt: failedPartial.receipt }] : (failedPartial?.messageIds ?? []).map((messageId) => ({ messageId }))] });
1753
+ throw createChannelPartialDeliveryError(error, {
1754
+ messageIds: listMessageReceiptPlatformIds(receipt),
1755
+ receipt,
1756
+ visibleReplySent: true,
1757
+ content: joinMattermostVisibleContent([
1758
+ confirmedPreviewDelivery?.content,
1759
+ previewDeliveryResult?.content,
1760
+ normalDeliveryResult?.content,
1761
+ supplementalDeliveryResult?.content,
1762
+ failedPartial?.content
1763
+ ])
1764
+ });
1765
+ }
1574
1766
  }
1575
1767
  //#endregion
1576
1768
  //#region extensions/mattermost/src/mattermost/thread-participation.ts
@@ -1623,7 +1815,8 @@ function createDisabledMattermostDraftStream() {
1623
1815
  settleBoundaries: noopAsync,
1624
1816
  resolveFinalText: (text) => ({
1625
1817
  kind: "full",
1626
- text
1818
+ text,
1819
+ publishedParts: []
1627
1820
  })
1628
1821
  };
1629
1822
  }
@@ -1641,9 +1834,10 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1641
1834
  accountId: account.accountId,
1642
1835
  typing: baseReplyPipeline.typing
1643
1836
  });
1644
- const draftPreviewEnabled = account.streamingMode !== "off";
1645
- const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
1646
- const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
1837
+ const hookRunner = getGlobalHookRunner();
1838
+ const draftPreviewEnabled = !((hookRunner?.hasHooks("reply_payload_sending") ?? false) || (hookRunner?.hasHooks("message_sending") ?? false)) && account.streamingMode !== "off";
1839
+ const draftToolProgressEnabled = draftPreviewEnabled && shouldUpdateMattermostDraftToolProgress(account);
1840
+ const suppressDefaultToolProgressMessages = draftPreviewEnabled && shouldSuppressMattermostDefaultToolProgressMessages(account);
1647
1841
  const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
1648
1842
  client,
1649
1843
  channelId,
@@ -1689,17 +1883,51 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1689
1883
  };
1690
1884
  const previewState = { finalizedViaPreviewPost: false };
1691
1885
  const resolvePreviewFinalText = (text) => {
1692
- if (typeof text !== "string") return;
1693
- const resolution = draftStream.resolveFinalText(text);
1886
+ const resolution = draftStream.resolveFinalText(typeof text === "string" ? text : "");
1887
+ const confirmedDelivery = resolution.publishedParts.length > 0 ? (() => {
1888
+ const receipt = createMessageReceiptFromOutboundResults({
1889
+ results: resolution.publishedParts.map((part) => ({
1890
+ channel: "mattermost",
1891
+ messageId: part.messageId,
1892
+ channelId
1893
+ })),
1894
+ kind: "preview",
1895
+ ...effectiveReplyToId ? { replyToId: effectiveReplyToId } : {}
1896
+ });
1897
+ return {
1898
+ outcome: "text",
1899
+ messageIds: listMessageReceiptPlatformIds(receipt),
1900
+ receipt,
1901
+ visibleReplySent: true,
1902
+ content: joinMattermostVisibleContent(resolution.publishedParts.map((part) => part.content))
1903
+ };
1904
+ })() : void 0;
1694
1905
  const deliveryText = resolution.kind === "already-delivered" ? "" : resolution.text;
1695
1906
  const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
1696
1907
  const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
1697
1908
  if (!chunks.length && formatted) chunks.push(formatted);
1698
- if (chunks.length !== 1) return;
1909
+ if (chunks.length !== 1) return {
1910
+ deliveryText,
1911
+ confirmedDelivery,
1912
+ alreadyDelivered: resolution.kind === "already-delivered"
1913
+ };
1699
1914
  const trimmed = chunks[0]?.trim();
1700
- if (!trimmed) return;
1701
- if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
1702
- return trimmed;
1915
+ if (!trimmed) return {
1916
+ deliveryText,
1917
+ confirmedDelivery,
1918
+ alreadyDelivered: resolution.kind === "already-delivered"
1919
+ };
1920
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return {
1921
+ deliveryText,
1922
+ confirmedDelivery,
1923
+ alreadyDelivered: false
1924
+ };
1925
+ return {
1926
+ editText: trimmed,
1927
+ deliveryText,
1928
+ confirmedDelivery,
1929
+ alreadyDelivered: false
1930
+ };
1703
1931
  };
1704
1932
  const updateDraftFromPartial = (text) => {
1705
1933
  const cleaned = text?.trim();
@@ -1725,16 +1953,21 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1725
1953
  typingCallbacks
1726
1954
  };
1727
1955
  const delivery = {
1956
+ observeMessageSent: true,
1728
1957
  deliver: async (payloadEntry, info) => {
1729
1958
  if (info.kind === "final") {
1730
1959
  await enterBlockPreviewActivity("text");
1731
1960
  await draftStream.settleBoundaries();
1732
1961
  progressDraft.markFinalReplyStarted();
1733
1962
  }
1963
+ let threadParticipationRecorded = false;
1734
1964
  const markThreadParticipation = () => {
1735
- if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
1965
+ if (!threadParticipationRecorded && kind !== "direct" && effectiveReplyToId) {
1966
+ threadParticipationRecorded = true;
1967
+ recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
1968
+ }
1736
1969
  };
1737
- await deliverMattermostReplyWithDraftPreview({
1970
+ const result = await deliverMattermostReplyWithDraftPreview({
1738
1971
  payload: payloadEntry,
1739
1972
  info,
1740
1973
  kind,
@@ -1751,7 +1984,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1751
1984
  ...payloadToDeliver,
1752
1985
  text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
1753
1986
  } : payloadToDeliver;
1754
- const outcome = await deliverMattermostReplyPayload({
1987
+ const deliveryResult = await deliverMattermostReplyPayload({
1755
1988
  core,
1756
1989
  cfg,
1757
1990
  payload: resolvedPayload,
@@ -1767,20 +2000,32 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1767
2000
  tableMode,
1768
2001
  sendMessage: sendMessageMattermost,
1769
2002
  onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2003
+ }).catch((error) => {
2004
+ if (isChannelPartialDeliveryError(error)) markThreadParticipation();
2005
+ throw error;
1770
2006
  });
1771
- if (outcome === "text" || outcome === "media") markThreadParticipation();
1772
- else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
2007
+ if (deliveryResult.outcome === "text" || deliveryResult.outcome === "media") markThreadParticipation();
2008
+ else if (deliveryResult.outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
1773
2009
  const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
1774
- outcome,
2010
+ outcome: deliveryResult.outcome,
1775
2011
  payload: resolvedPayload,
1776
2012
  to,
1777
2013
  accountId: account.accountId,
1778
2014
  agentId: route.agentId
1779
2015
  });
1780
2016
  if (deliveryLog) runtime.log?.(deliveryLog);
2017
+ return deliveryResult;
2018
+ }
2019
+ }).catch((error) => {
2020
+ if (isChannelPartialDeliveryError(error)) {
2021
+ markThreadParticipation();
2022
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
1781
2023
  }
2024
+ throw error;
1782
2025
  });
2026
+ if (result.visibleReplySent) markThreadParticipation();
1783
2027
  if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2028
+ return result;
1784
2029
  },
1785
2030
  onError: (err, info) => {
1786
2031
  runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
@@ -1966,6 +2211,35 @@ function createMattermostPostHandler(monitor) {
1966
2211
  const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
1967
2212
  const rawPostText = typeof post.message === "string" ? post.message : "";
1968
2213
  const rawText = normalizeOptionalString(rawPostText) ?? "";
2214
+ const { effectiveReplyToId, sessionKey } = thread;
2215
+ const { envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
2216
+ cfg,
2217
+ agentId: route.agentId,
2218
+ sessionKey
2219
+ });
2220
+ const historyKey = resolveMattermostPendingHistoryKey({
2221
+ kind,
2222
+ sessionKey
2223
+ });
2224
+ const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2225
+ const nativeMedia = fileIds.map(() => ({}));
2226
+ const pendingBody = formatMattermostPendingMediaText({
2227
+ body: rawText,
2228
+ media: nativeMedia
2229
+ });
2230
+ const recordPendingHistory = () => {
2231
+ const trimmed = pendingBody.trim();
2232
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
2233
+ limit: historyLimit,
2234
+ historyKey: historyKey ?? "",
2235
+ entry: historyKey && trimmed ? {
2236
+ sender: senderName,
2237
+ body: trimmed,
2238
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2239
+ messageId: post.id
2240
+ } : null
2241
+ });
2242
+ };
1969
2243
  const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1970
2244
  cfg,
1971
2245
  surface: "mattermost"
@@ -2029,6 +2303,15 @@ function createMattermostPostHandler(monitor) {
2029
2303
  return;
2030
2304
  }
2031
2305
  if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
2306
+ if (shouldIncludeSupplementalContext({
2307
+ mode: resolveChannelContextVisibilityMode({
2308
+ cfg,
2309
+ channel: "mattermost",
2310
+ accountId: account.accountId
2311
+ }),
2312
+ kind: "history",
2313
+ senderAllowed: false
2314
+ })) recordPendingHistory();
2032
2315
  monitor.logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
2033
2316
  return;
2034
2317
  }
@@ -2044,32 +2327,8 @@ function createMattermostPostHandler(monitor) {
2044
2327
  });
2045
2328
  return;
2046
2329
  }
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
2330
  const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2055
2331
  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
2332
  const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2074
2333
  const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2075
2334
  const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
@@ -2151,7 +2410,9 @@ function createMattermostPostHandler(monitor) {
2151
2410
  sender: {
2152
2411
  name: senderName,
2153
2412
  id: senderId
2154
- }
2413
+ },
2414
+ previousTimestamp,
2415
+ envelope: envelopeOptions
2155
2416
  });
2156
2417
  if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2157
2418
  historyKey,
@@ -2163,7 +2424,8 @@ function createMattermostPostHandler(monitor) {
2163
2424
  timestamp: entry.timestamp,
2164
2425
  body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2165
2426
  chatType: kind,
2166
- senderLabel: entry.sender
2427
+ senderLabel: entry.sender,
2428
+ envelope: envelopeOptions
2167
2429
  })
2168
2430
  });
2169
2431
  const commandBody = rawText.trim();
@@ -2189,7 +2451,7 @@ function createMattermostPostHandler(monitor) {
2189
2451
  WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2190
2452
  CommandAuthorized: commandAuthorized,
2191
2453
  CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2192
- ...buildMattermostInboundMediaPayload(mediaList)
2454
+ ...await buildMattermostInboundMediaPayload(mediaList)
2193
2455
  });
2194
2456
  const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2195
2457
  dmScope: cfg.session?.dmScope,
@@ -2548,7 +2810,7 @@ async function monitorMattermostProvider(opts = {}) {
2548
2810
  resolveChannelLimitMb: () => void 0,
2549
2811
  accountId: account.accountId
2550
2812
  }) ?? 8 * 1024 * 1024;
2551
- const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
2813
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy$1({
2552
2814
  providerConfigPresent: cfg.channels?.mattermost !== void 0,
2553
2815
  groupPolicy: account.config.groupPolicy,
2554
2816
  defaultGroupPolicy: resolveDefaultGroupPolicy(cfg)
@@ -2606,27 +2868,32 @@ async function monitorMattermostProvider(opts = {}) {
2606
2868
  const text = normalizeOptionalString(entry.post.message) ?? "";
2607
2869
  return Boolean(text) && !core.channel.commands.isControlCommandMessage(text, cfg);
2608
2870
  },
2609
- onFlush: async (entries) => {
2871
+ onFlush: (entries, createFlush) => {
2610
2872
  const last = entries.at(-1);
2611
- if (!last) return;
2612
2873
  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;
2874
+ return createFlush({
2875
+ lifecycle,
2876
+ dispatch: async (admissionLifecycle) => {
2877
+ if (!last) return;
2878
+ try {
2879
+ if (entries.length === 1) {
2880
+ await handlePost(last.post, last.payload, admissionLifecycle);
2881
+ await settle();
2882
+ return;
2883
+ }
2884
+ const mergedPost = {
2885
+ ...last.post,
2886
+ message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2887
+ file_ids: []
2888
+ };
2889
+ await handlePost(mergedPost, last.payload, admissionLifecycle, entries.map((entry) => entry.post.id));
2890
+ await settle();
2891
+ } catch (error) {
2892
+ await admissionLifecycle.onAbandoned();
2893
+ throw error;
2894
+ }
2618
2895
  }
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
- }
2896
+ });
2630
2897
  },
2631
2898
  onError: (err) => {
2632
2899
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
@@ -2870,4 +3137,71 @@ async function deleteReaction(client, params) {
2870
3137
  await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, { method: "DELETE" });
2871
3138
  }
2872
3139
  //#endregion
2873
- export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };
3140
+ //#region extensions/mattermost/src/mattermost/read.ts
3141
+ function parseMattermostChannelTarget(rawTarget) {
3142
+ const normalized = normalizeMattermostMessagingTarget(rawTarget);
3143
+ if (normalized?.startsWith("channel:")) return normalized.slice(8).trim() || void 0;
3144
+ const trimmed = rawTarget.trim();
3145
+ return trimmed && !trimmed.includes(":") ? trimmed : void 0;
3146
+ }
3147
+ function isCurrentMattermostReadTarget(params) {
3148
+ const toolContext = params.context.toolContext;
3149
+ const requesterAccountId = params.context.requesterAccountId?.trim();
3150
+ if (normalizeLowercaseStringOrEmpty(toolContext?.currentChannelProvider) !== "mattermost" || !requesterAccountId || normalizeAccountId(requesterAccountId) !== normalizeAccountId(params.accountId)) return false;
3151
+ const nativeChannelId = toolContext?.currentChannelId;
3152
+ if (typeof nativeChannelId === "string" && nativeChannelId.trim()) return parseMattermostChannelTarget(nativeChannelId) === params.channelId;
3153
+ const messagingTarget = toolContext?.currentMessagingTarget;
3154
+ return typeof messagingTarget === "string" && Boolean(messagingTarget.trim()) && parseMattermostChannelTarget(messagingTarget) === params.channelId;
3155
+ }
3156
+ function isConfiguredMattermostReadTarget(params) {
3157
+ const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
3158
+ providerConfigPresent: params.cfg.channels?.mattermost !== void 0,
3159
+ groupPolicy: params.account.config.groupPolicy,
3160
+ defaultGroupPolicy: params.cfg.channels?.defaults?.groupPolicy
3161
+ });
3162
+ if (groupPolicy === "disabled") return false;
3163
+ if (groupPolicy === "open") return true;
3164
+ const groups = params.account.config.groups;
3165
+ return groups?.[params.channelId] !== void 0 || groups?.["*"] !== void 0;
3166
+ }
3167
+ async function readMattermostMessages(params) {
3168
+ const account = resolveMattermostAccount({
3169
+ cfg: params.cfg,
3170
+ accountId: params.accountId
3171
+ });
3172
+ if (!account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
3173
+ const baseUrl = account.baseUrl?.trim();
3174
+ const botToken = account.botToken?.trim();
3175
+ if (!baseUrl || !botToken) throw new Error("Mattermost botToken/baseUrl missing.");
3176
+ const client = createMattermostClient({
3177
+ baseUrl,
3178
+ botToken,
3179
+ fetchImpl: params.fetchImpl,
3180
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
3181
+ });
3182
+ const directOperator = params.context.conversationReadOrigin === "direct-operator";
3183
+ const currentConversation = isCurrentMattermostReadTarget({
3184
+ accountId: account.accountId,
3185
+ channelId: params.channelId,
3186
+ context: params.context
3187
+ });
3188
+ if (!directOperator && !currentConversation) {
3189
+ const requesterAccountId = params.context.requesterAccountId?.trim();
3190
+ const sameProvider = normalizeLowercaseStringOrEmpty(params.context.toolContext?.currentChannelProvider) === "mattermost";
3191
+ const sameAccount = requesterAccountId && normalizeAccountId(requesterAccountId) === normalizeAccountId(account.accountId);
3192
+ if (!sameProvider || !sameAccount) throw new Error("Mattermost delegated reads require the current Mattermost account.");
3193
+ const channel = await fetchMattermostChannel(client, params.channelId);
3194
+ if (channel.type !== "O" && channel.type !== "P" || !isConfiguredMattermostReadTarget({
3195
+ cfg: params.cfg,
3196
+ account,
3197
+ channelId: params.channelId
3198
+ })) throw new Error("Mattermost read target channel is not allowed.");
3199
+ }
3200
+ return await fetchMattermostChannelPosts(client, params.channelId, {
3201
+ limit: params.limit,
3202
+ before: params.before,
3203
+ after: params.after
3204
+ });
3205
+ }
3206
+ //#endregion
3207
+ export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, readMattermostMessages, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };