@openclaw/mattermost 2026.7.2-beta.7 → 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,4 +1,4 @@
1
- import { m as normalizeMattermostBaseUrl } from "./client-CqqzTcno.js";
1
+ import { m as normalizeMattermostBaseUrl } from "./client-B_hd-kwM.js";
2
2
  import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
3
3
  import { resolveChannelPreviewStreamMode, resolveChannelStreamingBlockCoalesce, resolveChannelStreamingBlockEnabled, resolveChannelStreamingChunkMode } from "openclaw/plugin-sdk/channel-outbound";
4
4
  import { createAccountListHelpers, hasConfiguredAccountValue } from "openclaw/plugin-sdk/account-helpers";
package/dist/api.js CHANGED
@@ -1,3 +1,3 @@
1
- import { r as isMattermostSenderAllowed } from "./monitor-auth-rctDliGZ.js";
2
- import { t as buildButtonAttachments } from "./interactions-BQXY_48h.js";
1
+ import { r as isMattermostSenderAllowed } from "./monitor-auth-CVd_4FPD.js";
2
+ import { t as buildButtonAttachments } from "./interactions-Du_EJMeN.js";
3
3
  export { buildButtonAttachments, isMattermostSenderAllowed };
@@ -1,5 +1,5 @@
1
- import { c as isMattermostConfigured, i as mattermostSetupContract, l as mattermostConfigAdapter, n as mattermostSetupWizard, o as MattermostChannelConfigSchema, r as mattermostSetupAdapter, s as describeMattermostAccount, t as mattermostPlugin, u as mattermostMeta } from "./channel-plugin-runtime-DlrMaSIu.js";
2
- import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-CL1PxV3z.js";
1
+ import { a as MattermostChannelConfigSchema, c as mattermostConfigAdapter, l as mattermostMeta, n as mattermostSetupWizard, o as describeMattermostAccount, r as mattermostSetupContract, s as isMattermostConfigured, t as mattermostPlugin } from "./channel-plugin-runtime-Dxt8Zv1j.js";
2
+ import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-B93t91oq.js";
3
3
  //#region extensions/mattermost/src/channel.setup.ts
4
4
  const mattermostSetupPlugin = {
5
5
  id: "mattermost",
@@ -31,7 +31,6 @@ const mattermostSetupPlugin = {
31
31
  describeAccount: describeMattermostAccount
32
32
  },
33
33
  gateway: { resolveGatewayAuthBypassPaths: resolveMattermostGatewayAuthBypassPaths },
34
- setup: mattermostSetupAdapter,
35
34
  setupContract: mattermostSetupContract,
36
35
  setupWizard: mattermostSetupWizard
37
36
  };
@@ -1,8 +1,9 @@
1
- import { m as normalizeMattermostBaseUrl } from "./client-CqqzTcno.js";
2
- import { a as resolveMattermostReplyToMode, i as resolveMattermostAccount, n as listMattermostAccountIds, o as buildSecretInputSchema, r as resolveDefaultMattermostAccountId, s as hasConfiguredSecretInput, t as inspectMattermostAccount } from "./accounts-NaMdx9yF.js";
3
- import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-CL1PxV3z.js";
4
- import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-BaUvVh8e.js";
5
- import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-B4R5Bmhv.js";
1
+ import { m as normalizeMattermostBaseUrl } from "./client-B_hd-kwM.js";
2
+ import { a as resolveMattermostReplyToMode, i as resolveMattermostAccount, n as listMattermostAccountIds, o as buildSecretInputSchema, r as resolveDefaultMattermostAccountId, s as hasConfiguredSecretInput, t as inspectMattermostAccount } from "./accounts-DspH-NMT.js";
3
+ import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-B93t91oq.js";
4
+ import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-mvORF4f6.js";
5
+ import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-qg3NXRlS.js";
6
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, buildChannelOutboundSessionRoute, buildThreadAwareOutboundSessionRoute, stripChannelTargetPrefix, stripTargetKindPrefix } from "openclaw/plugin-sdk/core";
6
7
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
7
8
  import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
8
9
  import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
@@ -10,7 +11,6 @@ import { z } from "zod";
10
11
  import { formatNormalizedAllowFromEntries } from "openclaw/plugin-sdk/allow-from";
11
12
  import { createLoggedPairingApprovalNotifier } from "openclaw/plugin-sdk/channel-pairing";
12
13
  import { createAccountStatusSink, createChannelMessageAdapterFromOutbound } from "openclaw/plugin-sdk/channel-outbound";
13
- import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, buildChannelOutboundSessionRoute, buildThreadAwareOutboundSessionRoute, stripChannelTargetPrefix, stripTargetKindPrefix } from "openclaw/plugin-sdk/core";
14
14
  import { jsonResult, readPositiveIntegerParam, readStringParam, withNormalizedTimestamp } from "openclaw/plugin-sdk/channel-actions";
15
15
  import { adaptScopedAccountAccessor, createScopedChannelConfigAdapter } from "openclaw/plugin-sdk/channel-config-helpers";
16
16
  import { createChannelConfigUiHints, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
@@ -256,7 +256,7 @@ const MattermostChannelConfigSchema = buildChannelConfigSchema(buildMultiAccount
256
256
  "block.enabled": "Enable chunked block-style Mattermost preview delivery when channels.mattermost.streaming.mode=\"block\".",
257
257
  "block.coalesce": "Merge streamed Mattermost block replies before final delivery.",
258
258
  "preview.toolProgress": "Show tool/progress activity in the live draft preview post (default: true). Set false to hide interim tool updates while the draft preview stays active.",
259
- "preview.commandText": "Command/exec detail in preview tool-progress lines: \"raw\" preserves released behavior; \"status\" shows only the tool label."
259
+ "preview.commandText": "Command/exec detail in preview tool-progress lines: \"status\" is the safe default; \"raw\" opts into command text."
260
260
  },
261
261
  progress: {}
262
262
  })
@@ -397,47 +397,6 @@ function applyMattermostSetupConfigPatch(params) {
397
397
  patch: params.patch
398
398
  });
399
399
  }
400
- const mattermostSetupAdapter = {
401
- resolveAccountId: ({ accountId }) => normalizeAccountId(accountId),
402
- applyAccountName: ({ cfg, accountId, name }) => applyAccountNameToChannelSection({
403
- cfg,
404
- channelKey: channel$1,
405
- accountId,
406
- name
407
- }),
408
- validateInput: createSetupInputPresenceValidator({
409
- defaultAccountOnlyEnvError: "Mattermost env vars can only be used for the default account.",
410
- whenNotUseEnv: [{
411
- someOf: ["botToken", "token"],
412
- message: "Mattermost requires --bot-token and --http-url (or --use-env)."
413
- }, {
414
- someOf: ["httpUrl"],
415
- message: "Mattermost requires --bot-token and --http-url (or --use-env)."
416
- }],
417
- validate: ({ input }) => {
418
- const setupInput = input;
419
- const token = setupInput.botToken ?? setupInput.token;
420
- const baseUrl = normalizeMattermostBaseUrl(setupInput.httpUrl);
421
- if (!setupInput.useEnv && (!token || !baseUrl)) return "Mattermost requires --bot-token and --http-url (or --use-env).";
422
- if (setupInput.httpUrl && !baseUrl) return "Mattermost --http-url must include a valid base URL.";
423
- return null;
424
- }
425
- }),
426
- applyAccountConfig: ({ cfg, accountId, input }) => {
427
- const setupInput = input;
428
- const token = setupInput.botToken ?? setupInput.token;
429
- const baseUrl = normalizeMattermostBaseUrl(setupInput.httpUrl);
430
- return applyMattermostSetupConfigPatch({
431
- cfg,
432
- accountId,
433
- name: setupInput.name,
434
- patch: setupInput.useEnv ? {} : {
435
- ...token ? { botToken: token } : {},
436
- ...baseUrl ? { baseUrl } : {}
437
- }
438
- });
439
- }
440
- };
441
400
  const mattermostSetupContract = defineChannelSetupContract({
442
401
  fields: {
443
402
  token: {
@@ -468,10 +427,51 @@ const mattermostSetupContract = defineChannelSetupContract({
468
427
  cli: {
469
428
  flags: "--use-env",
470
429
  description: "Use Mattermost environment credentials"
471
- }
430
+ },
431
+ envVars: ["MATTERMOST_BOT_TOKEN", "MATTERMOST_URL"]
472
432
  }
473
433
  },
474
- legacyAdapter: mattermostSetupAdapter
434
+ legacyAdapter: {
435
+ resolveAccountId: ({ accountId }) => normalizeAccountId(accountId),
436
+ applyAccountName: ({ cfg, accountId, name }) => applyAccountNameToChannelSection({
437
+ cfg,
438
+ channelKey: channel$1,
439
+ accountId,
440
+ name
441
+ }),
442
+ validateInput: createSetupInputPresenceValidator({
443
+ defaultAccountOnlyEnvError: "Mattermost env vars can only be used for the default account.",
444
+ whenNotUseEnv: [{
445
+ someOf: ["botToken", "token"],
446
+ message: "Mattermost requires --bot-token and --http-url (or --use-env)."
447
+ }, {
448
+ someOf: ["httpUrl"],
449
+ message: "Mattermost requires --bot-token and --http-url (or --use-env)."
450
+ }],
451
+ validate: ({ input }) => {
452
+ const setupInput = input;
453
+ const token = setupInput.botToken ?? setupInput.token;
454
+ const baseUrl = normalizeMattermostBaseUrl(setupInput.httpUrl);
455
+ if (!setupInput.useEnv && (!token || !baseUrl)) return "Mattermost requires --bot-token and --http-url (or --use-env).";
456
+ if (setupInput.httpUrl && !baseUrl) return "Mattermost --http-url must include a valid base URL.";
457
+ return null;
458
+ }
459
+ }),
460
+ applyAccountConfig: ({ cfg, accountId, input }) => {
461
+ const setupInput = input;
462
+ const token = setupInput.botToken ?? setupInput.token;
463
+ const baseUrl = normalizeMattermostBaseUrl(setupInput.httpUrl);
464
+ return applyMattermostSetupConfigPatch({
465
+ cfg,
466
+ accountId,
467
+ name: setupInput.name,
468
+ patch: setupInput.useEnv ? {} : {
469
+ ...token ? { botToken: token } : {},
470
+ ...baseUrl ? { baseUrl } : {}
471
+ }
472
+ });
473
+ }
474
+ }
475
475
  });
476
476
  //#endregion
477
477
  //#region extensions/mattermost/src/setup-surface.ts
@@ -559,7 +559,7 @@ const mattermostSetupWizard = {
559
559
  };
560
560
  //#endregion
561
561
  //#region extensions/mattermost/src/channel.ts
562
- const loadMattermostChannelRuntime = createLazyRuntimeModule(() => import("./channel.runtime-DndW9G7T.js"));
562
+ const loadMattermostChannelRuntime = createLazyRuntimeModule(() => import("./channel.runtime-FKnzxYBR.js"));
563
563
  function buildMattermostPresentationButtons(presentation) {
564
564
  return presentation.blocks.filter((block) => block.type === "buttons").map((block) => block.buttons.flatMap((button) => {
565
565
  if (button.action) return [];
@@ -1073,7 +1073,6 @@ const mattermostPlugin = createChatChannelPlugin({
1073
1073
  base: {
1074
1074
  id: "mattermost",
1075
1075
  meta: { ...mattermostMeta },
1076
- setup: mattermostSetupAdapter,
1077
1076
  setupContract: mattermostSetupContract,
1078
1077
  setupWizard: mattermostSetupWizard,
1079
1078
  capabilities: {
@@ -1128,6 +1127,11 @@ const mattermostPlugin = createChatChannelPlugin({
1128
1127
  targetIdComparison: "case-sensitive",
1129
1128
  defaultMarkdownTableMode: "off",
1130
1129
  normalizeTarget: normalizeMattermostMessagingTarget,
1130
+ inferTargetChatType: ({ to }) => {
1131
+ const target = normalizeMattermostMessagingTarget(to);
1132
+ if (!target) return;
1133
+ return target.startsWith("user:") || target.startsWith("@") ? "direct" : "channel";
1134
+ },
1131
1135
  resolveDeliveryTarget: ({ conversationId, parentConversationId }) => {
1132
1136
  const parent = parentConversationId?.trim();
1133
1137
  const child = conversationId.trim();
@@ -1254,4 +1258,4 @@ const mattermostPlugin = createChatChannelPlugin({
1254
1258
  outbound: mattermostOutbound
1255
1259
  });
1256
1260
  //#endregion
1257
- export { normalizeMattermostMessagingTarget as a, isMattermostConfigured$1 as c, mattermostSetupContract as i, mattermostConfigAdapter as l, mattermostSetupWizard as n, MattermostChannelConfigSchema as o, mattermostSetupAdapter as r, describeMattermostAccount as s, mattermostPlugin as t, mattermostMeta as u };
1261
+ export { MattermostChannelConfigSchema as a, mattermostConfigAdapter as c, normalizeMattermostMessagingTarget as i, mattermostMeta as l, mattermostSetupWizard as n, describeMattermostAccount as o, mattermostSetupContract as r, isMattermostConfigured$1 as s, mattermostPlugin as t };
@@ -1,2 +1,2 @@
1
- import { t as mattermostPlugin } from "./channel-plugin-runtime-DlrMaSIu.js";
1
+ import { t as mattermostPlugin } from "./channel-plugin-runtime-Dxt8Zv1j.js";
2
2
  export { mattermostPlugin };
@@ -1,19 +1,21 @@
1
1
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.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";
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, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
17
19
  import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createMessageReceiptFromOutboundResults, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
18
20
  import { resolveAllowlistProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
19
21
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
@@ -26,8 +28,7 @@ import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
26
28
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
27
29
  import { runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
28
30
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
29
- import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
30
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
31
+ import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
31
32
  import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
32
33
  import WebSocket from "ws";
33
34
  import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
@@ -35,6 +36,7 @@ import { resolveChannelContextVisibilityMode, shouldIncludeSupplementalContext }
35
36
  import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
36
37
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
37
38
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
39
+ import { createPluginStateErrorReporter } from "openclaw/plugin-sdk/plugin-state-runtime";
38
40
  //#region extensions/mattermost/src/mattermost/directory.ts
39
41
  function buildClient(params) {
40
42
  const account = inspectMattermostAccount({
@@ -214,6 +216,8 @@ const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
214
216
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
215
217
  const MattermostEventPayloadSchema = z.object({
216
218
  event: z.string().optional(),
219
+ status: z.string().optional(),
220
+ seq_reply: z.number().optional(),
217
221
  data: z.object({
218
222
  post: z.unknown().optional(),
219
223
  reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
@@ -277,6 +281,7 @@ function createMattermostConnectOnce(opts) {
277
281
  let protocolPingTimer;
278
282
  let protocolPongTimer;
279
283
  let initialUpdateAt;
284
+ let authenticationSeq;
280
285
  const clearTimers = () => {
281
286
  if (healthCheckTimer !== void 0) {
282
287
  clearTimeout(healthCheckTimer);
@@ -376,11 +381,11 @@ function createMattermostConnectOnce(opts) {
376
381
  });
377
382
  opts.statusSink?.({
378
383
  connected: true,
379
- lastConnectedAt: Date.now(),
380
- lastError: null
384
+ lifecycle: "starting"
381
385
  });
386
+ authenticationSeq = opts.nextSeq();
382
387
  const authPayload = JSON.stringify({
383
- seq: opts.nextSeq(),
388
+ seq: authenticationSeq,
384
389
  action: "authentication_challenge",
385
390
  data: { token: opts.botToken }
386
391
  });
@@ -418,6 +423,10 @@ function createMattermostConnectOnce(opts) {
418
423
  const raw = rawDataToString(data);
419
424
  const payload = parseMattermostEventPayload(raw);
420
425
  if (!payload) return;
426
+ if (payload.status === "OK" && payload.seq_reply === authenticationSeq) {
427
+ opts.statusSink?.(channelReadyPatch());
428
+ return;
429
+ }
421
430
  if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
422
431
  if (!opts.onReaction) return;
423
432
  try {
@@ -449,6 +458,7 @@ function createMattermostConnectOnce(opts) {
449
458
  const message = reasonToString(reason);
450
459
  opts.statusSink?.({
451
460
  connected: false,
461
+ lifecycle: "recovering",
452
462
  lastDisconnect: {
453
463
  at: Date.now(),
454
464
  status: code,
@@ -471,7 +481,11 @@ function createMattermostConnectOnce(opts) {
471
481
  meta: { subsystem: "mattermost-websocket" }
472
482
  });
473
483
  opts.runtime.error?.(`mattermost websocket error: ${String(err)}`);
474
- opts.statusSink?.({ lastError: String(err) });
484
+ opts.statusSink?.({
485
+ connected: false,
486
+ lifecycle: "recovering",
487
+ lastError: String(err)
488
+ });
475
489
  try {
476
490
  ws.close();
477
491
  } catch {}
@@ -939,7 +953,9 @@ function registerMattermostInteractions(params) {
939
953
  pluginId: "mattermost",
940
954
  source: "mattermost-interactions",
941
955
  accountId: account.accountId,
942
- log: (message) => runtime.log?.(message)
956
+ log: (message) => runtime.log?.(message),
957
+ replaceExisting: true,
958
+ throwOnFailure: true
943
959
  });
944
960
  }
945
961
  //#endregion
@@ -1369,6 +1385,10 @@ function createMattermostDraftStream(params) {
1369
1385
  stopped: false,
1370
1386
  final: false
1371
1387
  };
1388
+ let terminalAcceptedDeliveryError;
1389
+ const assertNoAcceptedDeliveryFailure = () => {
1390
+ if (terminalAcceptedDeliveryError !== void 0) throw terminalAcceptedDeliveryError;
1391
+ };
1372
1392
  let currentGeneration = {
1373
1393
  lastSentText: "",
1374
1394
  latestSourceText: "",
@@ -1395,20 +1415,17 @@ function createMattermostDraftStream(params) {
1395
1415
  message: normalized,
1396
1416
  rootId: params.rootId
1397
1417
  });
1398
- const postId = sent.id?.trim();
1399
- if (!postId) {
1400
- streamState.stopped = true;
1401
- params.warn?.("mattermost stream preview stopped (missing post id from create)");
1402
- return false;
1403
- }
1404
- target.postId = postId;
1418
+ target.postId = sent.id;
1405
1419
  target.lastProviderText = sent.message ?? normalized;
1406
1420
  }
1407
1421
  target.lastSentText = normalized;
1408
1422
  return true;
1409
1423
  } catch (err) {
1410
1424
  streamState.stopped = true;
1425
+ const acceptedDeliveryError = isChannelPartialDeliveryError(err) ? toErrorObject(err, "Mattermost accepted delivery failed") : void 0;
1426
+ if (acceptedDeliveryError) terminalAcceptedDeliveryError = acceptedDeliveryError;
1411
1427
  params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
1428
+ if (acceptedDeliveryError) throw acceptedDeliveryError;
1412
1429
  return false;
1413
1430
  }
1414
1431
  };
@@ -1431,6 +1448,7 @@ function createMattermostDraftStream(params) {
1431
1448
  warnPrefix: "mattermost stream preview cleanup failed"
1432
1449
  });
1433
1450
  const forceNewMessage = () => {
1451
+ if (terminalAcceptedDeliveryError !== void 0) return Promise.reject(terminalAcceptedDeliveryError);
1434
1452
  if (streamState.stopped || streamState.final) return Promise.resolve();
1435
1453
  const pendingText = loop.takePending();
1436
1454
  const inFlightAtBoundary = loop.waitForInFlight();
@@ -1440,8 +1458,13 @@ function createMattermostDraftStream(params) {
1440
1458
  const boundary = (async () => {
1441
1459
  try {
1442
1460
  await sealed.ready;
1461
+ assertNoAcceptedDeliveryFailure();
1443
1462
  await inFlightAtBoundary;
1444
- if (streamState.stopped && !streamState.final) return;
1463
+ assertNoAcceptedDeliveryFailure();
1464
+ if (streamState.stopped && !streamState.final) {
1465
+ assertNoAcceptedDeliveryFailure();
1466
+ return;
1467
+ }
1445
1468
  const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
1446
1469
  const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
1447
1470
  const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
@@ -1479,12 +1502,10 @@ function createMattermostDraftStream(params) {
1479
1502
  message: firstChunk,
1480
1503
  rootId: params.rootId
1481
1504
  });
1482
- const firstPostId = firstPost.id?.trim();
1483
- if (!firstPostId) throw new Error("missing post id from boundary create");
1484
1505
  if (assistantText) {
1485
1506
  const publishedContent = firstPost.message ?? firstChunk;
1486
1507
  trackPublishedAssistantPart({
1487
- messageId: firstPostId,
1508
+ messageId: firstPost.id,
1488
1509
  content: publishedContent
1489
1510
  });
1490
1511
  publishedAssistantOffset = consumeMattermostPublishedChunk({
@@ -1500,12 +1521,10 @@ function createMattermostDraftStream(params) {
1500
1521
  message: chunk,
1501
1522
  rootId: params.rootId
1502
1523
  });
1503
- const postId = post.id?.trim();
1504
- if (!postId) throw new Error("missing post id from boundary create");
1505
1524
  if (assistantText) {
1506
1525
  const publishedContent = post.message ?? chunk;
1507
1526
  trackPublishedAssistantPart({
1508
- messageId: postId,
1527
+ messageId: post.id,
1509
1528
  content: publishedContent
1510
1529
  });
1511
1530
  publishedAssistantOffset = consumeMattermostPublishedChunk({
@@ -1520,12 +1539,18 @@ function createMattermostDraftStream(params) {
1520
1539
  requiresBlockBoundary: true
1521
1540
  });
1522
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
+ }
1523
1547
  const publishedAssistantPrefix = assistantText?.slice(0, publishedAssistantOffset).trim();
1524
1548
  if (publishedAssistantPrefix) sealedAssistantTexts.push({
1525
1549
  text: publishedAssistantPrefix,
1526
1550
  requiresBlockBoundary: false
1527
1551
  });
1528
1552
  params.warn?.(`mattermost stream preview boundary flush failed: ${err instanceof Error ? err.message : String(err)}`);
1553
+ if (acceptedDeliveryError) throw acceptedDeliveryError;
1529
1554
  }
1530
1555
  })();
1531
1556
  currentGeneration = {
@@ -1537,23 +1562,33 @@ function createMattermostDraftStream(params) {
1537
1562
  return boundary;
1538
1563
  };
1539
1564
  const flush = async () => {
1565
+ assertNoAcceptedDeliveryFailure();
1540
1566
  await loop.flush();
1541
1567
  await currentGeneration.ready;
1568
+ assertNoAcceptedDeliveryFailure();
1542
1569
  };
1543
1570
  const discardPending = async () => {
1571
+ assertNoAcceptedDeliveryFailure();
1544
1572
  await stopForClear();
1545
1573
  await currentGeneration.ready;
1574
+ assertNoAcceptedDeliveryFailure();
1546
1575
  };
1547
1576
  const clear = async () => {
1577
+ assertNoAcceptedDeliveryFailure();
1548
1578
  await clearWithStop(discardPending);
1579
+ assertNoAcceptedDeliveryFailure();
1549
1580
  };
1550
1581
  const seal = async () => {
1582
+ assertNoAcceptedDeliveryFailure();
1551
1583
  await sealLifecycle();
1552
1584
  await currentGeneration.ready;
1585
+ assertNoAcceptedDeliveryFailure();
1553
1586
  };
1554
1587
  const stop = async () => {
1588
+ assertNoAcceptedDeliveryFailure();
1555
1589
  await stopLifecycle();
1556
1590
  await currentGeneration.ready;
1591
+ assertNoAcceptedDeliveryFailure();
1557
1592
  };
1558
1593
  const update = (text) => {
1559
1594
  currentGeneration.latestSourceText = text;
@@ -1566,7 +1601,9 @@ function createMattermostDraftStream(params) {
1566
1601
  updateLifecycle(text);
1567
1602
  };
1568
1603
  const settleBoundaries = async () => {
1604
+ assertNoAcceptedDeliveryFailure();
1569
1605
  await currentGeneration.ready;
1606
+ assertNoAcceptedDeliveryFailure();
1570
1607
  };
1571
1608
  const resolveFinalText = (text) => {
1572
1609
  const publishedParts = [...publishedAssistantParts.values()];
@@ -1690,6 +1727,7 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1690
1727
  resolveFinalizedId: (previewPostId) => finalizedPreviewPost?.id ?? previewPostId,
1691
1728
  onPreviewFinalized: (_previewPostId, receipt) => {
1692
1729
  params.previewState.finalizedViaPreviewPost = true;
1730
+ previewFinalTextAlreadyDelivered = true;
1693
1731
  previewDeliveryResult = {
1694
1732
  outcome: "text",
1695
1733
  messageIds: listMessageReceiptPlatformIds(receipt),
@@ -1731,7 +1769,8 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1731
1769
  return combineMattermostVisibleDeliveryResults([
1732
1770
  confirmedPreviewDelivery,
1733
1771
  previewDeliveryResult,
1734
- supplementalDeliveryResult
1772
+ supplementalDeliveryResult,
1773
+ normalDeliveryResult
1735
1774
  ]) ?? previewDeliveryResult;
1736
1775
  } catch (error) {
1737
1776
  const completedVisibleResults = [];
@@ -1774,14 +1813,8 @@ const threadParticipation = createPersistentDedupeCache({
1774
1813
  namespace: "mattermost.thread-participation",
1775
1814
  maxEntries: 1e3,
1776
1815
  openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1777
- logError: (error) => {
1778
- try {
1779
- getOptionalMattermostRuntime()?.logging.getChildLogger({
1780
- plugin: "mattermost",
1781
- feature: "thread-participation-state"
1782
- }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
1783
- } catch {}
1784
- }
1816
+ logError: createPluginStateErrorReporter(getOptionalMattermostRuntime, "mattermost", "thread-participation-state", "Mattermost persistent thread participation state failed"),
1817
+ readTimestamp: ({ repliedAt }) => repliedAt
1785
1818
  }
1786
1819
  });
1787
1820
  function makeKey(accountId, channelId, threadRootId) {
@@ -2093,35 +2126,35 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2093
2126
  disableBlockStreaming: draftPreviewEnabled ? true : replyOptions.disableBlockStreaming,
2094
2127
  ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2095
2128
  onModelSelected,
2096
- onPartialReply: (payloadResult) => account.streamingMode === "progress" ? void 0 : updateDraftFromPartial(payloadResult.text),
2129
+ onPartialReply: (payloadResult) => account.streamingMode === "progress" ? false : updateDraftFromPartial(payloadResult.text),
2097
2130
  onAssistantMessageStart: () => {
2098
2131
  lastPartialText = "";
2099
2132
  progressDraft.resetReasoningProgress();
2100
2133
  if (account.streamingMode === "block") {
2101
2134
  blockPreviewAssistantMessagePending = true;
2102
- return;
2135
+ return false;
2103
2136
  }
2104
2137
  if (account.streamingMode !== "progress") progressDraft.reset();
2138
+ return false;
2105
2139
  },
2106
2140
  onReasoningEnd: () => {
2107
2141
  lastPartialText = "";
2108
2142
  progressDraft.resetReasoningProgress();
2109
2143
  if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
2144
+ return false;
2110
2145
  },
2111
2146
  onReasoningStream: async (payloadResult) => {
2112
- if (account.streamingMode === "progress") {
2113
- await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2114
- return;
2115
- }
2147
+ if (account.streamingMode === "progress") return await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2116
2148
  if (!lastPartialText) {
2117
2149
  const boundarySettled = enterBlockPreviewActivity("reasoning");
2118
2150
  draftStream.update("Thinking…");
2119
2151
  previewBoundaryController.noteUpdate();
2120
2152
  await boundarySettled;
2121
2153
  }
2154
+ return false;
2122
2155
  },
2123
2156
  onToolStart: async (payloadValue) => {
2124
- if (!draftToolProgressEnabled) return;
2157
+ if (!draftToolProgressEnabled) return false;
2125
2158
  const boundarySettled = enterBlockPreviewActivity("tool");
2126
2159
  const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2127
2160
  event: "tool",
@@ -2132,10 +2165,11 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2132
2165
  args: payloadValue.args
2133
2166
  }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2134
2167
  previewBoundaryController.noteUpdate();
2135
- await Promise.all([boundarySettled, progressSettled]);
2168
+ const [, visible] = await Promise.all([boundarySettled, progressSettled]);
2169
+ return visible;
2136
2170
  },
2137
2171
  onItemEvent: async (payloadLocal) => {
2138
- if (!draftToolProgressEnabled) return;
2172
+ if (!draftToolProgressEnabled) return false;
2139
2173
  const boundarySettled = enterBlockPreviewActivity("tool");
2140
2174
  const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2141
2175
  event: "item",
@@ -2150,7 +2184,8 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2150
2184
  meta: payloadLocal.meta
2151
2185
  }), { startImmediately: true });
2152
2186
  previewBoundaryController.noteUpdate();
2153
- await Promise.all([boundarySettled, progressSettled]);
2187
+ const [, visible] = await Promise.all([boundarySettled, progressSettled]);
2188
+ return visible;
2154
2189
  }
2155
2190
  }
2156
2191
  })
@@ -2607,7 +2642,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2607
2642
  const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
2608
2643
  const slashCallbackUrl = resolveCallbackUrl({
2609
2644
  config: slashConfig,
2610
- gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
2645
+ gatewayPort: resolveGatewayPort(params.cfg),
2611
2646
  gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
2612
2647
  });
2613
2648
  warnOnSuspiciousCallbackUrl({
@@ -2728,6 +2763,13 @@ function sleepAbortable(ms, signal) {
2728
2763
  }
2729
2764
  //#endregion
2730
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
+ }
2731
2773
  async function monitorMattermostProvider(opts = {}) {
2732
2774
  const core = getMattermostRuntime();
2733
2775
  const runtime = opts.runtime ?? {
@@ -2765,10 +2807,7 @@ async function monitorMattermostProvider(opts = {}) {
2765
2807
  shouldReconnect: ({ outcome }) => outcome === "rejected",
2766
2808
  onError: (err) => {
2767
2809
  runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
2768
- opts.statusSink?.({
2769
- lastError: String(err),
2770
- connected: false
2771
- });
2810
+ publishMattermostRecoveringStatus(opts.statusSink, err);
2772
2811
  },
2773
2812
  onReconnect: (delayMs) => {
2774
2813
  runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
@@ -2778,15 +2817,6 @@ async function monitorMattermostProvider(opts = {}) {
2778
2817
  const botUserId = botUser.id;
2779
2818
  const botUsername = normalizeOptionalString(botUser.username);
2780
2819
  runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
2781
- await registerMattermostMonitorSlashCommands({
2782
- client,
2783
- cfg,
2784
- runtime,
2785
- account,
2786
- baseUrl,
2787
- botUserId
2788
- });
2789
- const slashEnabled = getSlashCommandState(account.accountId) != null;
2790
2820
  setInteractionSecret(account.accountId, botToken);
2791
2821
  const interactionPath = resolveInteractionCallbackPath(account.accountId);
2792
2822
  const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
@@ -2850,6 +2880,20 @@ async function monitorMattermostProvider(opts = {}) {
2850
2880
  allowedSourceIps: allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"],
2851
2881
  handleModelPickerInteraction: createMattermostModelPickerInteractionHandler(monitor)
2852
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;
2853
2897
  const handlePost = createMattermostPostHandler(monitor);
2854
2898
  const handleReactionEvent = createMattermostReactionHandler(monitor);
2855
2899
  const debouncer = core.channel.debounce.createInboundDebouncer({
@@ -2948,10 +2992,7 @@ async function monitorMattermostProvider(opts = {}) {
2948
2992
  jitterRatio: .2,
2949
2993
  onError: (err) => {
2950
2994
  runtime.error?.(`mattermost connection failed: ${String(err)}`);
2951
- opts.statusSink?.({
2952
- lastError: String(err),
2953
- connected: false
2954
- });
2995
+ publishMattermostRecoveringStatus(opts.statusSink, err);
2955
2996
  },
2956
2997
  onReconnect: (delayMs) => {
2957
2998
  runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
@@ -2959,7 +3000,7 @@ async function monitorMattermostProvider(opts = {}) {
2959
3000
  });
2960
3001
  } finally {
2961
3002
  await ingress.stop();
2962
- unregisterInteractions?.();
3003
+ unregisterInteractions();
2963
3004
  }
2964
3005
  const slashShutdownCleanupPromise = slashShutdownCleanup;
2965
3006
  if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
@@ -1,5 +1,8 @@
1
1
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2
+ import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
3
+ import { collectErrorGraphCandidates } from "openclaw/plugin-sdk/error-runtime";
2
4
  import { buildTimeoutAbortSignal } from "openclaw/plugin-sdk/extension-shared";
5
+ import { responseWithRelease } from "openclaw/plugin-sdk/fetch-runtime";
3
6
  import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
4
7
  import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
5
8
  import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
@@ -10,12 +13,6 @@ import { z } from "zod";
10
13
  const MATTERMOST_ERROR_BODY_LIMIT_BYTES = 8 * 1024;
11
14
  const MATTERMOST_REQUEST_TIMEOUT_MS = 3e4;
12
15
  const MATTERMOST_TEXT_RESPONSE_LIMIT_BYTES = 64 * 1024;
13
- const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
14
- 101,
15
- 204,
16
- 205,
17
- 304
18
- ]);
19
16
  const MattermostPostSchema = z.object({
20
17
  id: z.string(),
21
18
  user_id: z.string().nullable().optional(),
@@ -33,6 +30,14 @@ const MattermostPostListSchema = z.object({
33
30
  next_post_id: z.string().nullable().optional(),
34
31
  prev_post_id: z.string().nullable().optional()
35
32
  }).passthrough();
33
+ function parseMattermostApiStatus(error) {
34
+ if (!error || typeof error !== "object") return;
35
+ const message = "message" in error && typeof error.message === "string" ? error.message : "";
36
+ const match = /Mattermost API (\d{3})\b/.exec(message);
37
+ if (!match) return;
38
+ const status = Number(match[1]);
39
+ return Number.isFinite(status) ? status : void 0;
40
+ }
36
41
  function normalizeMattermostBaseUrl(raw) {
37
42
  const trimmed = raw?.trim();
38
43
  if (!trimmed) return;
@@ -69,48 +74,6 @@ async function readMattermostError(res) {
69
74
  }
70
75
  return text;
71
76
  }
72
- function responseWithRelease(response, release) {
73
- let released = false;
74
- const releaseOnce = async () => {
75
- if (released) return;
76
- released = true;
77
- await release();
78
- };
79
- if (!response.body || NULL_BODY_STATUSES.has(response.status)) {
80
- releaseOnce();
81
- return new Response(null, {
82
- status: response.status,
83
- statusText: response.statusText,
84
- headers: response.headers
85
- });
86
- }
87
- const reader = response.body.getReader();
88
- const body = new ReadableStream({
89
- async pull(controller) {
90
- try {
91
- const { done, value } = await reader.read();
92
- if (done) {
93
- await releaseOnce();
94
- controller.close();
95
- return;
96
- }
97
- if (value) controller.enqueue(value);
98
- } catch (error) {
99
- await releaseOnce();
100
- throw error;
101
- }
102
- },
103
- async cancel(reason) {
104
- await reader.cancel(reason).catch(() => void 0);
105
- await releaseOnce();
106
- }
107
- });
108
- return new Response(body, {
109
- status: response.status,
110
- statusText: response.statusText,
111
- headers: response.headers
112
- });
113
- }
114
77
  function createMattermostClient(params) {
115
78
  const baseUrl = normalizeMattermostBaseUrl(params.baseUrl);
116
79
  if (!baseUrl) throw new Error("Mattermost baseUrl is required");
@@ -166,8 +129,16 @@ function createMattermostClient(params) {
166
129
  throw new Error(`Mattermost API ${res.status} ${res.statusText}: ${detail || "unknown error"}`);
167
130
  }
168
131
  if (res.status === 204) return;
169
- if ((res.headers.get("content-type") ?? "").includes("application/json")) return await readProviderJsonResponse(res, `Mattermost API ${path}`);
170
- return await readMattermostSuccessText(res, path);
132
+ try {
133
+ if ((res.headers.get("content-type") ?? "").includes("application/json")) return await readProviderJsonResponse(res, `Mattermost API ${path}`);
134
+ return await readMattermostSuccessText(res, path);
135
+ } catch (error) {
136
+ if (path === "/posts" && init?.method?.toUpperCase() === "POST") throw createChannelPartialDeliveryError(error, {
137
+ messageIds: [],
138
+ visibleReplySent: true
139
+ });
140
+ throw error;
141
+ }
171
142
  };
172
143
  return {
173
144
  baseUrl,
@@ -305,7 +276,11 @@ async function createMattermostDirectChannelWithRetry(client, userIds, options =
305
276
  });
306
277
  }
307
278
  function isRetryableError(error) {
308
- const candidates = collectErrorCandidates(error);
279
+ const candidates = collectErrorGraphCandidates(error, (current) => [
280
+ current.cause,
281
+ current.reason,
282
+ ...Array.isArray(current.errors) ? current.errors : []
283
+ ]);
309
284
  const messages = candidates.map((candidate) => normalizeLowercaseStringOrEmpty(readErrorMessage(candidate))).filter((message) => Boolean(message));
310
285
  if (messages.some((message) => /mattermost api 5\d{2}\b/.test(message))) return true;
311
286
  if (messages.some((message) => /mattermost api 429\b/.test(message) || message.includes("too many requests"))) return true;
@@ -332,24 +307,6 @@ function isRetryableError(error) {
332
307
  if (names.some((name) => RETRYABLE_NETWORK_ERROR_NAMES.has(name))) return true;
333
308
  return messages.some((message) => RETRYABLE_NETWORK_MESSAGE_SNIPPETS.some((pattern) => message.includes(pattern)));
334
309
  }
335
- function collectErrorCandidates(error) {
336
- const queue = [error];
337
- let queueIndex = 0;
338
- const seen = /* @__PURE__ */ new Set();
339
- const candidates = [];
340
- while (queueIndex < queue.length) {
341
- const current = queue[queueIndex];
342
- queueIndex += 1;
343
- if (!current || seen.has(current)) continue;
344
- seen.add(current);
345
- candidates.push(current);
346
- if (typeof current !== "object") continue;
347
- const nested = current;
348
- queue.push(nested.cause, nested.reason);
349
- if (Array.isArray(nested.errors)) queue.push(...nested.errors);
350
- }
351
- return candidates;
352
- }
353
310
  function readErrorMessage(error) {
354
311
  if (!error || typeof error !== "object") return;
355
312
  const message = error.message;
@@ -375,10 +332,19 @@ async function createMattermostPost(client, params) {
375
332
  if (params.rootId) payload.root_id = params.rootId;
376
333
  if (params.fileIds?.length) payload.file_ids = params.fileIds;
377
334
  if (params.props) payload.props = params.props;
378
- return await client.request("/posts", {
335
+ const post = await client.request("/posts", {
379
336
  method: "POST",
380
337
  body: JSON.stringify(payload)
381
338
  });
339
+ const postId = post && typeof post === "object" ? normalizeOptionalString(post.id) : void 0;
340
+ if (!postId) throw createChannelPartialDeliveryError(/* @__PURE__ */ new Error("Mattermost post creation response did not include a post id"), {
341
+ messageIds: [],
342
+ visibleReplySent: true
343
+ });
344
+ return postId === post.id ? post : {
345
+ ...post,
346
+ id: postId
347
+ };
382
348
  }
383
349
  async function fetchMattermostUserTeams(client, userId) {
384
350
  return await client.request(`/users/${userId}/teams`);
@@ -416,4 +382,4 @@ async function uploadMattermostFile(client, params) {
416
382
  return info;
417
383
  }
418
384
  //#endregion
419
- export { sendMattermostTyping as _, createMattermostPost as a, fetchMattermostChannelByName as c, fetchMattermostUser as d, fetchMattermostUserByUsername as f, resolveMattermostReplyDeliveryBarrierTimeoutMs as g, readMattermostError as h, createMattermostDirectChannelWithRetry as i, fetchMattermostChannelPosts as l, normalizeMattermostBaseUrl as m, buildMattermostApiUrl as n, deleteMattermostPost as o, fetchMattermostUserTeams as p, createMattermostClient as r, fetchMattermostChannel as s, MattermostPostSchema as t, fetchMattermostMe as u, updateMattermostPost as v, uploadMattermostFile as y };
385
+ export { resolveMattermostReplyDeliveryBarrierTimeoutMs as _, createMattermostPost as a, uploadMattermostFile as b, fetchMattermostChannelByName as c, fetchMattermostUser as d, fetchMattermostUserByUsername as f, readMattermostError as g, parseMattermostApiStatus as h, createMattermostDirectChannelWithRetry as i, fetchMattermostChannelPosts as l, normalizeMattermostBaseUrl as m, buildMattermostApiUrl as n, deleteMattermostPost as o, fetchMattermostUserTeams as p, createMattermostClient as r, fetchMattermostChannel as s, MattermostPostSchema as t, fetchMattermostMe as u, sendMattermostTyping as v, updateMattermostPost as y };
@@ -1,2 +1,2 @@
1
- import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-BaUvVh8e.js";
1
+ import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-mvORF4f6.js";
2
2
  export { legacyConfigRules, normalizeCompatibilityConfig };
@@ -1,5 +1,4 @@
1
- import { createLegacyPrivateNetworkDoctorContract } from "openclaw/plugin-sdk/ssrf-runtime";
2
- import { defineChannelAliasMigration } from "openclaw/plugin-sdk/runtime-doctor";
1
+ import { createLegacyPrivateNetworkDoctorContract, defineChannelAliasMigration } from "openclaw/plugin-sdk/runtime-doctor-migrations";
3
2
  //#region extensions/mattermost/src/doctor-contract.ts
4
3
  const networkContract = createLegacyPrivateNetworkDoctorContract({ channelKey: "mattermost" });
5
4
  const streamingAliasMigration = defineChannelAliasMigration({
@@ -1,2 +1,2 @@
1
- import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-CL1PxV3z.js";
1
+ import { t as resolveMattermostGatewayAuthBypassPaths } from "./gateway-auth-bypass-B93t91oq.js";
2
2
  export { resolveMattermostGatewayAuthBypassPaths as resolveGatewayAuthBypassPaths };
@@ -1,22 +1,20 @@
1
+ import { asOptionalRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
1
2
  //#region extensions/mattermost/src/gateway-auth-bypass.ts
2
3
  const DEFAULT_SLASH_CALLBACK_PATH = "/api/channels/mattermost/command";
3
- function readTrimmedString(value) {
4
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
5
- }
6
4
  function normalizeCallbackPath(value) {
7
- const trimmed = readTrimmedString(value);
5
+ const trimmed = normalizeOptionalString(value);
8
6
  if (!trimmed) return DEFAULT_SLASH_CALLBACK_PATH;
9
7
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
10
8
  }
11
9
  function readMattermostCommands(value) {
12
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10
+ return asOptionalRecord(value);
13
11
  }
14
12
  function isMattermostBypassPath(path) {
15
13
  return path === DEFAULT_SLASH_CALLBACK_PATH || path.startsWith("/api/channels/mattermost/");
16
14
  }
17
15
  function collectMattermostSlashCallbackPaths(raw) {
18
16
  const paths = /* @__PURE__ */ new Set([normalizeCallbackPath(raw?.callbackPath)]);
19
- const callbackUrl = readTrimmedString(raw?.callbackUrl);
17
+ const callbackUrl = normalizeOptionalString(raw?.callbackUrl);
20
18
  if (callbackUrl) try {
21
19
  const pathname = new URL(callbackUrl).pathname;
22
20
  if (pathname) paths.add(pathname);
@@ -1,7 +1,8 @@
1
1
  import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { v as updateMattermostPost } from "./client-CqqzTcno.js";
3
- import { b as readRequestBodyWithLimit, m as isTrustedProxyAddress, w as resolveClientIp } from "./monitor-auth-rctDliGZ.js";
2
+ import { y as updateMattermostPost } from "./client-B_hd-kwM.js";
3
+ import { C as resolveClientIp, m as isTrustedProxyAddress, y as readRequestBodyWithLimit } from "./monitor-auth-CVd_4FPD.js";
4
4
  import { createHmac } from "node:crypto";
5
+ import { resolveGatewayPort } from "openclaw/plugin-sdk/core";
5
6
  import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
6
7
  import { normalizeOptionalString, normalizeStringifiedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
7
8
  //#region extensions/mattermost/src/mattermost/interactions.ts
@@ -47,7 +48,7 @@ function computeInteractionCallbackUrl(accountId, cfg) {
47
48
  const path = resolveInteractionCallbackPath(accountId);
48
49
  const callbackBaseUrl = normalizeOptionalString(cfg?.interactions?.callbackBaseUrl) ?? normalizeOptionalString(cfg?.channels?.mattermost?.interactions?.callbackBaseUrl);
49
50
  if (callbackBaseUrl) return `${normalizeCallbackBaseUrl(callbackBaseUrl)}${path}`;
50
- const port = typeof cfg?.gateway?.port === "number" ? cfg.gateway.port : 18789;
51
+ const port = resolveGatewayPort(cfg);
51
52
  let host = cfg?.gateway?.customBindHost && !isWildcardBindHost(cfg.gateway.customBindHost) ? cfg.gateway.customBindHost.trim() : "localhost";
52
53
  if (host.includes(":") && !(host.startsWith("[") && host.endsWith("]"))) host = `[${host}]`;
53
54
  return `http://${host}:${port}${path}`;
@@ -1,7 +1,7 @@
1
+ import { isTrustedProxyAddress, resolveClientIp } from "openclaw/plugin-sdk/core";
1
2
  import { normalizeLowercaseStringOrEmpty, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
2
- import { parseTcpPort } from "openclaw/plugin-sdk/number-runtime";
3
- import { resolveAllowlistMatchSimple } from "openclaw/plugin-sdk/allow-from";
4
3
  import { logInboundDrop } from "openclaw/plugin-sdk/channel-inbound";
4
+ import { resolveAllowlistMatchSimple } from "openclaw/plugin-sdk/allow-from";
5
5
  import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
6
6
  import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
7
7
  import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
@@ -14,7 +14,6 @@ import { loadOutboundMediaFromUrl } from "openclaw/plugin-sdk/outbound-media";
14
14
  import { DEFAULT_GROUP_HISTORY_LIMIT, createChannelHistoryWindow } from "openclaw/plugin-sdk/reply-history";
15
15
  import { registerPluginHttpRoute } from "openclaw/plugin-sdk/webhook-targets";
16
16
  import { isRequestBodyLimitError, readRequestBodyWithLimit } from "openclaw/plugin-sdk/webhook-ingress";
17
- import { isTrustedProxyAddress, resolveClientIp } from "openclaw/plugin-sdk/core";
18
17
  import { parseAccessGroupAllowFromEntry } from "openclaw/plugin-sdk/access-groups";
19
18
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
20
19
  //#region extensions/mattermost/src/mattermost/monitor-auth.ts
@@ -182,4 +181,4 @@ async function authorizeMattermostCommandInvocation(params) {
182
181
  };
183
182
  }
184
183
  //#endregion
185
- export { resolveChannelMediaMaxBytes as C, warnMissingProviderGroupPolicyFallbackOnce as E, resolveAllowlistProviderRuntimeGroupPolicy$1 as S, resolveDefaultGroupPolicy as T, logInboundDrop as _, normalizeMattermostAllowList as a, readRequestBodyWithLimit as b, DEFAULT_GROUP_HISTORY_LIMIT as c, createChannelMessageReplyPipeline as d, createChannelPairingController as f, loadOutboundMediaFromUrl as g, listSkillCommandsForAgents as h, normalizeMattermostAllowEntry as i, buildModelsProviderData as l, isTrustedProxyAddress as m, formatMattermostDirectMessageDropLog as n, resolveMattermostMonitorInboundAccess as o, isRequestBodyLimitError as p, isMattermostSenderAllowed as r, resolveMattermostTrustedChatKind as s, authorizeMattermostCommandInvocation as t, createChannelHistoryWindow as u, logTypingFailure as v, resolveClientIp as w, registerPluginHttpRoute as x, parseTcpPort as y };
184
+ export { resolveClientIp as C, resolveChannelMediaMaxBytes as S, warnMissingProviderGroupPolicyFallbackOnce as T, logInboundDrop as _, normalizeMattermostAllowList as a, registerPluginHttpRoute as b, DEFAULT_GROUP_HISTORY_LIMIT as c, createChannelMessageReplyPipeline as d, createChannelPairingController as f, loadOutboundMediaFromUrl as g, listSkillCommandsForAgents as h, normalizeMattermostAllowEntry as i, buildModelsProviderData as l, isTrustedProxyAddress as m, formatMattermostDirectMessageDropLog as n, resolveMattermostMonitorInboundAccess as o, isRequestBodyLimitError as p, isMattermostSenderAllowed as r, resolveMattermostTrustedChatKind as s, authorizeMattermostCommandInvocation as t, createChannelHistoryWindow as u, logTypingFailure as v, resolveDefaultGroupPolicy as w, resolveAllowlistProviderRuntimeGroupPolicy$1 as x, readRequestBodyWithLimit as y };
@@ -1,2 +1,2 @@
1
- import { r as isMattermostSenderAllowed } from "./monitor-auth-rctDliGZ.js";
1
+ import { r as isMattermostSenderAllowed } from "./monitor-auth-CVd_4FPD.js";
2
2
  export { isMattermostSenderAllowed };
@@ -1,6 +1,7 @@
1
1
  import { r as setMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { resolveAllowlistMatchSimple } from "openclaw/plugin-sdk/allow-from";
2
+ import { DEFAULT_ACCOUNT_ID, buildChannelConfigSchema, createDedupeCache, isTrustedProxyAddress, parseStrictPositiveInteger, resolveClientIp } from "openclaw/plugin-sdk/core";
3
3
  import { formatInboundFromLabel, logInboundDrop } from "openclaw/plugin-sdk/channel-inbound";
4
+ import { resolveAllowlistMatchSimple } from "openclaw/plugin-sdk/allow-from";
4
5
  import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
5
6
  import { createAccountStatusSink, createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
6
7
  import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
@@ -13,7 +14,6 @@ import { loadOutboundMediaFromUrl } from "openclaw/plugin-sdk/outbound-media";
13
14
  import { DEFAULT_GROUP_HISTORY_LIMIT, buildPendingHistoryContextFromMap, clearHistoryEntriesIfEnabled, createChannelHistoryWindow, recordPendingHistoryEntryIfEnabled } from "openclaw/plugin-sdk/reply-history";
14
15
  import { registerPluginHttpRoute } from "openclaw/plugin-sdk/webhook-targets";
15
16
  import { isRequestBodyLimitError, rawDataToString, readRequestBodyWithLimit } from "openclaw/plugin-sdk/webhook-ingress";
16
- import { DEFAULT_ACCOUNT_ID, buildChannelConfigSchema, createDedupeCache, isTrustedProxyAddress, parseStrictPositiveInteger, resolveClientIp } from "openclaw/plugin-sdk/core";
17
17
  import { chunkTextForOutbound } from "openclaw/plugin-sdk/text-chunking";
18
18
  import { applyAccountNameToChannelSection, applySetupAccountConfigPatch, migrateBaseNameToDefaultAccount } from "openclaw/plugin-sdk/setup";
19
19
  import { buildComputedAccountStatusSnapshot } from "openclaw/plugin-sdk/channel-status";
@@ -1,2 +1,2 @@
1
- import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries, t as channelSecrets } from "./secret-contract-B4R5Bmhv.js";
1
+ import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries, t as channelSecrets } from "./secret-contract-qg3NXRlS.js";
2
2
  export { channelSecrets, collectRuntimeConfigAssignments, secretTargetRegistryEntries };
@@ -0,0 +1,12 @@
1
+ import { createSimpleChannelSecretContract } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
2
+ //#region extensions/mattermost/src/secret-contract.ts
3
+ const channelSecrets = createSimpleChannelSecretContract({
4
+ channelKey: "mattermost",
5
+ label: "Mattermost",
6
+ accountFields: ["botToken"],
7
+ channelFields: ["botToken"],
8
+ mode: "account-inheritance"
9
+ });
10
+ const { secretTargetRegistryEntries, collectRuntimeConfigAssignments } = channelSecrets;
11
+ //#endregion
12
+ export { collectRuntimeConfigAssignments as n, secretTargetRegistryEntries as r, channelSecrets as t };
@@ -1,2 +1,2 @@
1
- import { i as registerSlashCommandRoute } from "./slash-state-DM8qmFJR.js";
1
+ import { i as registerSlashCommandRoute } from "./slash-state-DUowGLl4.js";
2
2
  export { registerSlashCommandRoute };
@@ -1,14 +1,14 @@
1
1
  import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { _ as sendMattermostTyping, a as createMattermostPost, c as fetchMattermostChannelByName, d as fetchMattermostUser, f as fetchMattermostUserByUsername, g as resolveMattermostReplyDeliveryBarrierTimeoutMs, i as createMattermostDirectChannelWithRetry, m as normalizeMattermostBaseUrl, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, u as fetchMattermostMe, y as uploadMattermostFile } from "./client-CqqzTcno.js";
3
- import { a as normalizeMattermostAllowList, b as readRequestBodyWithLimit, g as loadOutboundMediaFromUrl, l as buildModelsProviderData, p as isRequestBodyLimitError, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, v as logTypingFailure } from "./monitor-auth-rctDliGZ.js";
4
- import { c as setInteractionSecret, n as buildButtonProps, o as resolveInteractionCallbackUrl } from "./interactions-BQXY_48h.js";
5
- import { i as resolveMattermostAccount } from "./accounts-NaMdx9yF.js";
2
+ import { _ as resolveMattermostReplyDeliveryBarrierTimeoutMs, a as createMattermostPost, b as uploadMattermostFile, c as fetchMattermostChannelByName, d as fetchMattermostUser, f as fetchMattermostUserByUsername, h as parseMattermostApiStatus, i as createMattermostDirectChannelWithRetry, m as normalizeMattermostBaseUrl, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, u as fetchMattermostMe, v as sendMattermostTyping } from "./client-B_hd-kwM.js";
3
+ import { a as normalizeMattermostAllowList, g as loadOutboundMediaFromUrl, l as buildModelsProviderData, p as isRequestBodyLimitError, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, v as logTypingFailure, y as readRequestBodyWithLimit } from "./monitor-auth-CVd_4FPD.js";
4
+ import { c as setInteractionSecret, n as buildButtonProps, o as resolveInteractionCallbackUrl } from "./interactions-Du_EJMeN.js";
5
+ import { i as resolveMattermostAccount } from "./accounts-DspH-NMT.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
8
- import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringifiedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
8
+ import { asFiniteNumber, normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringifiedOptionalString, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
9
+ import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
9
10
  import { asDateTimestampMs, parseStrictInteger, resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
10
11
  import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
11
- import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
12
12
  import { createMessageReceiptFromOutboundResults, listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
13
13
  import { resolveStoredModelOverride } from "openclaw/plugin-sdk/command-auth-native";
14
14
  import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
@@ -22,6 +22,7 @@ import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
22
22
  import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
23
23
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
24
24
  import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
25
+ import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
25
26
  import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
26
27
  const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
27
28
  function truncateMattermostCommandDescription(description) {
@@ -387,13 +388,11 @@ function splitModelRef(modelRef) {
387
388
  };
388
389
  }
389
390
  function readContextString(context, key, fallback = "") {
390
- const value = context[key];
391
- return typeof value === "string" ? value : fallback;
391
+ return readStringField(context, key) ?? fallback;
392
392
  }
393
393
  function readContextNumber(context, key) {
394
394
  const value = context[key];
395
- if (typeof value === "number" && Number.isFinite(value)) return value;
396
- if (typeof value === "string") return parseStrictInteger(value);
395
+ return asFiniteNumber(value) ?? parseStrictInteger(value);
397
396
  }
398
397
  function normalizePage(value) {
399
398
  if (!Number.isFinite(value)) return 1;
@@ -837,14 +836,6 @@ function isExplicitMattermostTarget(raw) {
837
836
  if (!trimmed) return false;
838
837
  return /^(channel|user|mattermost):/i.test(trimmed) || trimmed.startsWith("@") || trimmed.startsWith("#");
839
838
  }
840
- function parseMattermostApiStatus(err) {
841
- if (!err || typeof err !== "object") return;
842
- const msg = "message" in err && typeof err.message === "string" ? err.message : "";
843
- const match = /Mattermost API (\d{3})\b/.exec(msg);
844
- if (!match) return;
845
- const code = Number(match[1]);
846
- return Number.isFinite(code) ? code : void 0;
847
- }
848
839
  async function resolveMattermostOpaqueTarget(params) {
849
840
  const input = params.input.trim();
850
841
  if (!input || isExplicitMattermostTarget(input) || !isMattermostId(input)) return null;
@@ -924,15 +915,14 @@ function cacheOutboundEntry(cache, key, value, maxEntries) {
924
915
  }
925
916
  const getCore = () => getMattermostRuntime();
926
917
  function createMattermostSendReceipt(params) {
927
- const messageIds = params.messageId.trim() && params.messageId !== "unknown" ? [params.messageId] : [];
928
918
  return createMessageReceiptFromOutboundResults({
929
919
  kind: params.kind,
930
920
  ...params.replyToId ? { replyToId: params.replyToId } : {},
931
- results: messageIds.map((messageId) => ({
921
+ results: [{
932
922
  channel: "mattermost",
933
- messageId,
923
+ messageId: params.messageId,
934
924
  channelId: params.channelId
935
- }))
925
+ }]
936
926
  });
937
927
  }
938
928
  function resolveMattermostReceiptKind(params) {
@@ -1002,7 +992,9 @@ async function resolveChannelIdByName(params) {
1002
992
  cacheOutboundEntry(channelByNameCache, key, channel.id, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
1003
993
  return channel.id;
1004
994
  }
1005
- } catch {}
995
+ } catch (error) {
996
+ if (parseMattermostApiStatus(error) !== 404) throw error;
997
+ }
1006
998
  throw new Error(`Mattermost channel "#${name}" not found in any team the bot belongs to`);
1007
999
  }
1008
1000
  function mergeDmRetryOptions(base, override) {
@@ -1140,7 +1132,7 @@ async function sendMessageMattermost(to, text, opts) {
1140
1132
  fileIds = [(await uploadMattermostFile(client, {
1141
1133
  channelId,
1142
1134
  buffer: media.buffer,
1143
- fileName: media.fileName ?? "upload",
1135
+ fileName: media.fileName ?? `upload${extensionForMime(media.contentType) ?? ""}`,
1144
1136
  contentType: media.contentType ?? void 0
1145
1137
  })).id];
1146
1138
  } catch (err) {
@@ -1168,7 +1160,7 @@ async function sendMessageMattermost(to, text, opts) {
1168
1160
  fileIds,
1169
1161
  props
1170
1162
  });
1171
- const messageId = post.id ?? "unknown";
1163
+ const messageId = post.id;
1172
1164
  const receipt = createMattermostSendReceipt({
1173
1165
  messageId,
1174
1166
  channelId,
@@ -1,5 +1,8 @@
1
1
  {
2
2
  "id": "mattermost",
3
+ "doctorContract": {
4
+ "configRepair": true
5
+ },
3
6
  "icon": "https://cdn.simpleicons.org/mattermost",
4
7
  "activation": {
5
8
  "onStartup": false
@@ -81,6 +84,29 @@
81
84
  ],
82
85
  "additionalProperties": false
83
86
  },
87
+ {
88
+ "type": "object",
89
+ "properties": {
90
+ "source": {
91
+ "type": "string",
92
+ "const": "store"
93
+ },
94
+ "provider": {
95
+ "type": "string",
96
+ "pattern": "^[a-z][a-z0-9_-]{0,63}$"
97
+ },
98
+ "id": {
99
+ "type": "string",
100
+ "pattern": "^[A-Z][A-Z0-9_]{0,127}$"
101
+ }
102
+ },
103
+ "required": [
104
+ "source",
105
+ "provider",
106
+ "id"
107
+ ],
108
+ "additionalProperties": false
109
+ },
84
110
  {
85
111
  "type": "object",
86
112
  "properties": {
@@ -552,6 +578,29 @@
552
578
  ],
553
579
  "additionalProperties": false
554
580
  },
581
+ {
582
+ "type": "object",
583
+ "properties": {
584
+ "source": {
585
+ "type": "string",
586
+ "const": "store"
587
+ },
588
+ "provider": {
589
+ "type": "string",
590
+ "pattern": "^[a-z][a-z0-9_-]{0,63}$"
591
+ },
592
+ "id": {
593
+ "type": "string",
594
+ "pattern": "^[A-Z][A-Z0-9_]{0,127}$"
595
+ }
596
+ },
597
+ "required": [
598
+ "source",
599
+ "provider",
600
+ "id"
601
+ ],
602
+ "additionalProperties": false
603
+ },
555
604
  {
556
605
  "type": "object",
557
606
  "properties": {
@@ -1019,7 +1068,7 @@
1019
1068
  },
1020
1069
  "streaming.preview.commandText": {
1021
1070
  "label": "Mattermost Draft Command Text",
1022
- "help": "Command/exec detail in preview tool-progress lines: \"raw\" preserves released behavior; \"status\" shows only the tool label."
1071
+ "help": "Command/exec detail in preview tool-progress lines: \"status\" is the safe default; \"raw\" opts into command text."
1023
1072
  },
1024
1073
  "streaming.progress.label": {
1025
1074
  "label": "Mattermost Progress Label",
@@ -1043,7 +1092,7 @@
1043
1092
  },
1044
1093
  "streaming.progress.commandText": {
1045
1094
  "label": "Mattermost Progress Command Text",
1046
- "help": "Command/exec detail in progress draft lines: \"raw\" preserves released behavior; \"status\" shows only the tool label."
1095
+ "help": "Command/exec detail in progress draft lines: \"status\" is the safe default; \"raw\" opts into command text."
1047
1096
  }
1048
1097
  }
1049
1098
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/mattermost",
3
- "version": "2026.7.2-beta.7",
3
+ "version": "2026.8.1-beta.2",
4
4
  "description": "OpenClaw Mattermost channel plugin",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,7 @@
12
12
  "zod": "4.4.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "openclaw": ">=2026.7.2-beta.7"
15
+ "openclaw": ">=2026.8.1-beta.2"
16
16
  },
17
17
  "peerDependenciesMeta": {
18
18
  "openclaw": {
@@ -74,7 +74,11 @@
74
74
  "cli": {
75
75
  "flags": "--use-env",
76
76
  "description": "Use Mattermost environment credentials"
77
- }
77
+ },
78
+ "envVars": [
79
+ "MATTERMOST_BOT_TOKEN",
80
+ "MATTERMOST_URL"
81
+ ]
78
82
  }
79
83
  ]
80
84
  }
@@ -87,10 +91,10 @@
87
91
  "allowInvalidConfigRecovery": true
88
92
  },
89
93
  "compat": {
90
- "pluginApi": ">=2026.7.2-beta.7"
94
+ "pluginApi": ">=2026.8.1-beta.2"
91
95
  },
92
96
  "build": {
93
- "openclawVersion": "2026.7.2-beta.7",
97
+ "openclawVersion": "2026.8.1-beta.2",
94
98
  "bundledDist": false
95
99
  },
96
100
  "release": {
@@ -1,28 +0,0 @@
1
- import { collectSimpleChannelFieldAssignments, createChannelSecretTargetRegistryEntries, getChannelSurface } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
2
- //#region extensions/mattermost/src/secret-contract.ts
3
- const secretTargetRegistryEntries = createChannelSecretTargetRegistryEntries({
4
- channelKey: "mattermost",
5
- account: ["botToken"],
6
- channel: ["botToken"]
7
- });
8
- function collectRuntimeConfigAssignments(params) {
9
- const resolved = getChannelSurface(params.config, "mattermost");
10
- if (!resolved) return;
11
- const { channel: mattermost, surface } = resolved;
12
- collectSimpleChannelFieldAssignments({
13
- channelKey: "mattermost",
14
- field: "botToken",
15
- channel: mattermost,
16
- surface,
17
- defaults: params.defaults,
18
- context: params.context,
19
- topInactiveReason: "no enabled account inherits this top-level Mattermost botToken.",
20
- accountInactiveReason: "Mattermost account is disabled."
21
- });
22
- }
23
- const channelSecrets = {
24
- secretTargetRegistryEntries,
25
- collectRuntimeConfigAssignments
26
- };
27
- //#endregion
28
- export { collectRuntimeConfigAssignments as n, secretTargetRegistryEntries as r, channelSecrets as t };