@openclaw/mattermost 2026.9.6 → 2026.9.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.
- package/assets/icon.png +0 -0
- package/dist/.setup/{channel-plugin-api-CCmaCFdK.mjs → channel-plugin-api-Bc8Qc1-t.mjs} +2 -2
- package/dist/.setup/{channel-plugin-api-CzBhdovL.mjs → channel-plugin-api-DXqHarCt.mjs} +2 -2
- package/dist/.setup/{channel-plugin-runtime-yAOg5GcM.mjs → channel-plugin-runtime-B0CAMiHe.mjs} +122 -160
- package/dist/.setup/channel.runtime-E2B5dNrh.mjs +383 -0
- package/dist/.setup/{client-BSSVve1x.mjs → client-CVeeTqCO.mjs} +18 -39
- package/dist/.setup/doctor-contract-BI6SB2cd.mjs +175 -0
- package/dist/.setup/{interactions-rBQWCbK8.mjs → interactions-DMSZYnEx.mjs} +170 -80
- package/dist/.setup/{channel.runtime-CihvzY84.mjs → monitor-BZyzPkkb.mjs} +172 -628
- package/dist/.setup/{monitor-auth-CCpN0z_f.mjs → monitor-auth-aZ0b1gqx.mjs} +9 -14
- package/dist/.setup/{normalize-DM54w7ud.mjs → normalize-BCjtmxtp.mjs} +8 -17
- package/dist/.setup/rolldown-runtime-BBjsoOtd.mjs +27 -0
- package/dist/.setup/send-ClgX-usq.mjs +438 -0
- package/dist/.setup/{slash-state-DfnmzXMr.mjs → slash-state-Dni1XNc1.mjs} +144 -781
- package/dist/api.js +2 -2
- package/dist/channel-plugin-api.js +2 -2
- package/dist/channel-plugin-runtime.js +1 -1
- package/dist/doctor-contract-api.js +1 -1
- package/dist/policy-api.js +1 -1
- package/dist/runtime-api.js +2 -23
- package/dist/setup-entry.js +1 -1
- package/dist/slash-route-api.js +1 -1
- package/openclaw.plugin.json +20 -0
- package/package.json +4 -4
- package/dist/.setup/doctor-contract-mvORF4f6.mjs +0 -18
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { _ as readMattermostError, h as normalizeMattermostBaseUrl, l as fetchMattermostChannelPosts, r as createMattermostClient, s as fetchMattermostChannel, u as fetchMattermostMe } from "./client-CVeeTqCO.mjs";
|
|
2
|
+
import { o as resolveMattermostTrustedChatKind } from "./monitor-auth-aZ0b1gqx.mjs";
|
|
3
|
+
import { c as listMattermostAccountIds, n as normalizeMattermostMessagingTarget, o as inspectMattermostAccount, u as resolveMattermostAccount } from "./normalize-BCjtmxtp.mjs";
|
|
4
|
+
import { n as resolveMattermostOpaqueTarget, t as sendMessageMattermost } from "./send-ClgX-usq.mjs";
|
|
5
|
+
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
6
|
+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
7
|
+
import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
8
|
+
import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
|
|
9
|
+
import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
10
|
+
import { resolveAllowlistProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
|
|
11
|
+
import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
|
|
12
|
+
import { runChannelProbe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
13
|
+
//#region extensions/mattermost/src/mattermost/directory.ts
|
|
14
|
+
function buildClient(params) {
|
|
15
|
+
const account = inspectMattermostAccount({
|
|
16
|
+
cfg: params.cfg,
|
|
17
|
+
accountId: params.accountId
|
|
18
|
+
});
|
|
19
|
+
if (!account.enabled || !account.botToken || !account.baseUrl) return null;
|
|
20
|
+
return createMattermostClient({
|
|
21
|
+
baseUrl: account.baseUrl,
|
|
22
|
+
botToken: account.botToken,
|
|
23
|
+
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** Build the requested account client, or aggregate accounts for an explicitly unscoped lookup. */
|
|
27
|
+
function buildClients(params) {
|
|
28
|
+
const requestedAccountId = params.accountId?.trim();
|
|
29
|
+
const accountIds = requestedAccountId ? [requestedAccountId] : listMattermostAccountIds(params.cfg);
|
|
30
|
+
const seen = /* @__PURE__ */ new Set();
|
|
31
|
+
const clients = [];
|
|
32
|
+
for (const id of accountIds) {
|
|
33
|
+
const client = buildClient({
|
|
34
|
+
cfg: params.cfg,
|
|
35
|
+
accountId: id
|
|
36
|
+
});
|
|
37
|
+
if (client && !seen.has(client.token)) {
|
|
38
|
+
seen.add(client.token);
|
|
39
|
+
clients.push(client);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return clients;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* List channels (public + private) visible to any configured bot account.
|
|
46
|
+
*
|
|
47
|
+
* NOTE: Uses per_page=200 which covers most instances. Mattermost does not
|
|
48
|
+
* return a "has more" indicator, so very large instances (200+ channels per bot)
|
|
49
|
+
* may see incomplete results. Pagination can be added if needed.
|
|
50
|
+
*/
|
|
51
|
+
async function listMattermostDirectoryGroups(params) {
|
|
52
|
+
const clients = buildClients(params);
|
|
53
|
+
if (!clients.length) return [];
|
|
54
|
+
const q = normalizeLowercaseStringOrEmpty(params.query);
|
|
55
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
56
|
+
const entries = [];
|
|
57
|
+
for (const client of clients) try {
|
|
58
|
+
const me = await fetchMattermostMe(client);
|
|
59
|
+
const channels = await client.request(`/users/${me.id}/channels?per_page=200`);
|
|
60
|
+
for (const ch of channels) {
|
|
61
|
+
if (ch.type !== "O" && ch.type !== "P") continue;
|
|
62
|
+
if (seenIds.has(ch.id)) continue;
|
|
63
|
+
if (q) {
|
|
64
|
+
const name = normalizeLowercaseStringOrEmpty(ch.name);
|
|
65
|
+
const display = normalizeLowercaseStringOrEmpty(ch.display_name);
|
|
66
|
+
if (!name.includes(q) && !display.includes(q)) continue;
|
|
67
|
+
}
|
|
68
|
+
seenIds.add(ch.id);
|
|
69
|
+
entries.push({
|
|
70
|
+
kind: resolveMattermostTrustedChatKind({ channelType: ch.type }) === "group" ? "group" : "channel",
|
|
71
|
+
id: `channel:${ch.id}`,
|
|
72
|
+
name: ch.name ?? void 0,
|
|
73
|
+
handle: ch.display_name ?? void 0
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
} catch (err) {
|
|
77
|
+
console.debug?.("[mattermost-directory] listGroups: skipping account:", err?.message);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* List team members as peer directory entries.
|
|
84
|
+
*
|
|
85
|
+
* Uses only the first available client since all bots in a team see the same
|
|
86
|
+
* user list (unlike channels where membership varies). Uses the first team
|
|
87
|
+
* returned — multi-team setups will only see members from that team.
|
|
88
|
+
*
|
|
89
|
+
* Uses paginated member listing with per_page=200, the Mattermost API maximum.
|
|
90
|
+
*/
|
|
91
|
+
async function listMattermostDirectoryPeers(params) {
|
|
92
|
+
const client = buildClients(params)[0];
|
|
93
|
+
if (!client) return [];
|
|
94
|
+
try {
|
|
95
|
+
const me = await fetchMattermostMe(client);
|
|
96
|
+
const team = (await client.request("/users/me/teams"))[0];
|
|
97
|
+
if (!team) return [];
|
|
98
|
+
const teamId = team.id;
|
|
99
|
+
const q = normalizeLowercaseStringOrEmpty(params.query);
|
|
100
|
+
let users;
|
|
101
|
+
if (q) users = await client.request("/users/search", {
|
|
102
|
+
method: "POST",
|
|
103
|
+
body: JSON.stringify({
|
|
104
|
+
term: q,
|
|
105
|
+
team_id: teamId
|
|
106
|
+
})
|
|
107
|
+
});
|
|
108
|
+
else {
|
|
109
|
+
const pageSize = 200;
|
|
110
|
+
const userIds = [];
|
|
111
|
+
for (let page = 0;; page += 1) {
|
|
112
|
+
const pageMembers = await client.request(`/teams/${teamId}/members?page=${page}&per_page=${pageSize}`);
|
|
113
|
+
for (const member of pageMembers) if (member.user_id !== me.id) userIds.push(member.user_id);
|
|
114
|
+
if (pageMembers.length < pageSize) break;
|
|
115
|
+
}
|
|
116
|
+
if (!userIds.length) return [];
|
|
117
|
+
users = [];
|
|
118
|
+
for (let index = 0; index < userIds.length; index += pageSize) {
|
|
119
|
+
const userIdBatch = userIds.slice(index, index + pageSize);
|
|
120
|
+
users.push(...await client.request("/users/ids", {
|
|
121
|
+
method: "POST",
|
|
122
|
+
body: JSON.stringify(userIdBatch)
|
|
123
|
+
}));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const entries = users.filter((u) => u.id !== me.id).map((u) => ({
|
|
127
|
+
kind: "user",
|
|
128
|
+
id: `user:${u.id}`,
|
|
129
|
+
name: u.username ?? void 0,
|
|
130
|
+
handle: [u.first_name, u.last_name].filter(Boolean).join(" ").trim() || u.nickname || void 0
|
|
131
|
+
}));
|
|
132
|
+
return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
|
|
133
|
+
} catch (err) {
|
|
134
|
+
console.debug?.("[mattermost-directory] listPeers failed:", err?.message);
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region extensions/mattermost/src/mattermost/probe.ts
|
|
140
|
+
async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false, deps) {
|
|
141
|
+
const normalized = normalizeMattermostBaseUrl(baseUrl);
|
|
142
|
+
if (!normalized) return {
|
|
143
|
+
ok: false,
|
|
144
|
+
error: "baseUrl missing"
|
|
145
|
+
};
|
|
146
|
+
const url = `${normalized}/api/v4/users/me`;
|
|
147
|
+
const headers = { Authorization: `Bearer ${botToken}` };
|
|
148
|
+
return await runChannelProbe(void 0, async ({ elapsedMs }) => {
|
|
149
|
+
const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : void 0;
|
|
150
|
+
const { response: res, release } = await fetchWithSsrFGuard({
|
|
151
|
+
url,
|
|
152
|
+
init: { headers },
|
|
153
|
+
auditContext: "mattermost-probe",
|
|
154
|
+
policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork),
|
|
155
|
+
...resolvedTimeoutMs !== void 0 ? { timeoutMs: resolvedTimeoutMs } : {},
|
|
156
|
+
...deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
|
|
157
|
+
...deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}
|
|
158
|
+
});
|
|
159
|
+
const requestElapsedMs = elapsedMs();
|
|
160
|
+
try {
|
|
161
|
+
if (!res.ok) {
|
|
162
|
+
const detail = await readMattermostError(res, headers);
|
|
163
|
+
return {
|
|
164
|
+
ok: false,
|
|
165
|
+
status: res.status,
|
|
166
|
+
error: detail || res.statusText,
|
|
167
|
+
elapsedMs: requestElapsedMs
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const bot = await readProviderJsonResponse(res, "Mattermost probe /users/me");
|
|
171
|
+
return {
|
|
172
|
+
ok: true,
|
|
173
|
+
status: res.status,
|
|
174
|
+
elapsedMs: requestElapsedMs,
|
|
175
|
+
bot
|
|
176
|
+
};
|
|
177
|
+
} finally {
|
|
178
|
+
await release();
|
|
179
|
+
}
|
|
180
|
+
}, (error) => ({
|
|
181
|
+
ok: false,
|
|
182
|
+
status: null,
|
|
183
|
+
error: formatErrorMessage(error)
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region extensions/mattermost/src/mattermost/reactions.ts
|
|
188
|
+
const BOT_USER_CACHE_TTL_MS = 6e5;
|
|
189
|
+
const botUserIdCache = /* @__PURE__ */ new Map();
|
|
190
|
+
async function resolveBotUserId(client, cacheKey) {
|
|
191
|
+
const rawNow = Date.now();
|
|
192
|
+
const now = asDateTimestampMs(rawNow);
|
|
193
|
+
const cached = botUserIdCache.get(cacheKey);
|
|
194
|
+
if (cached) {
|
|
195
|
+
if (now !== void 0 && cached.expiresAt > now) return cached.userId;
|
|
196
|
+
botUserIdCache.delete(cacheKey);
|
|
197
|
+
}
|
|
198
|
+
const userId = (await fetchMattermostMe(client))?.id?.trim();
|
|
199
|
+
if (!userId) return null;
|
|
200
|
+
const expiresAt = resolveExpiresAtMsFromDurationMs(BOT_USER_CACHE_TTL_MS, { nowMs: rawNow });
|
|
201
|
+
if (expiresAt !== void 0) botUserIdCache.set(cacheKey, {
|
|
202
|
+
userId,
|
|
203
|
+
expiresAt
|
|
204
|
+
});
|
|
205
|
+
return userId;
|
|
206
|
+
}
|
|
207
|
+
async function addMattermostReaction(params) {
|
|
208
|
+
return runMattermostReaction(params, {
|
|
209
|
+
action: "add",
|
|
210
|
+
mutation: createReaction
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
async function removeMattermostReaction(params) {
|
|
214
|
+
return runMattermostReaction(params, {
|
|
215
|
+
action: "remove",
|
|
216
|
+
mutation: deleteReaction
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
function parseAuthorizedReactionTarget(rawTarget) {
|
|
220
|
+
const normalized = rawTarget ? normalizeMattermostMessagingTarget(rawTarget) : void 0;
|
|
221
|
+
if (!normalized) return null;
|
|
222
|
+
if (normalized.startsWith("channel:")) {
|
|
223
|
+
const id = normalized.slice(8).trim();
|
|
224
|
+
return id ? {
|
|
225
|
+
kind: "channel",
|
|
226
|
+
id
|
|
227
|
+
} : null;
|
|
228
|
+
}
|
|
229
|
+
if (normalized.startsWith("user:")) {
|
|
230
|
+
const id = normalized.slice(5).trim();
|
|
231
|
+
return id ? {
|
|
232
|
+
kind: "user",
|
|
233
|
+
id
|
|
234
|
+
} : null;
|
|
235
|
+
}
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
async function authorizeMattermostReactionResource(params) {
|
|
239
|
+
const target = parseAuthorizedReactionTarget(params.authorizedTarget);
|
|
240
|
+
if (!target) throw new Error("Mattermost delegated reactions require a canonical authorized conversation target.");
|
|
241
|
+
const postChannelId = (await params.client.request(`/posts/${encodeURIComponent(params.postId)}`)).channel_id?.trim();
|
|
242
|
+
if (!postChannelId) throw new Error("Mattermost reaction post is missing its conversation binding.");
|
|
243
|
+
if (target.kind === "channel") {
|
|
244
|
+
if (postChannelId !== target.id) throw new Error("Mattermost reaction post belongs to a different conversation.");
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const botUserId = await resolveBotUserId(params.client, params.cacheKey);
|
|
248
|
+
if (!botUserId) throw new Error("Mattermost reactions failed: could not resolve bot user id.");
|
|
249
|
+
const channel = await fetchMattermostChannel(params.client, postChannelId);
|
|
250
|
+
const participants = channel.name?.split("__").map((entry) => entry.trim()).filter(Boolean).toSorted() ?? [];
|
|
251
|
+
const authorizedParticipants = [botUserId, target.id].toSorted();
|
|
252
|
+
if (channel.type !== "D" || participants.length !== 2 || participants[0] !== authorizedParticipants[0] || participants[1] !== authorizedParticipants[1]) throw new Error("Mattermost reaction post belongs to a different direct conversation.");
|
|
253
|
+
return botUserId;
|
|
254
|
+
}
|
|
255
|
+
async function runMattermostReaction(params, options) {
|
|
256
|
+
const resolved = resolveMattermostAccount({
|
|
257
|
+
cfg: params.cfg,
|
|
258
|
+
accountId: params.accountId
|
|
259
|
+
});
|
|
260
|
+
const baseUrl = resolved.baseUrl?.trim();
|
|
261
|
+
const botToken = resolved.botToken?.trim();
|
|
262
|
+
if (!baseUrl || !botToken) return {
|
|
263
|
+
ok: false,
|
|
264
|
+
error: "Mattermost botToken/baseUrl missing."
|
|
265
|
+
};
|
|
266
|
+
const client = createMattermostClient({
|
|
267
|
+
baseUrl,
|
|
268
|
+
botToken,
|
|
269
|
+
fetchImpl: params.fetchImpl,
|
|
270
|
+
allowPrivateNetwork: isPrivateNetworkOptInEnabled(resolved.config)
|
|
271
|
+
});
|
|
272
|
+
const cacheKey = `${baseUrl}:${botToken}`;
|
|
273
|
+
try {
|
|
274
|
+
const userId = (params.conversationReadOrigin === "direct-operator" ? void 0 : await authorizeMattermostReactionResource({
|
|
275
|
+
client,
|
|
276
|
+
cacheKey,
|
|
277
|
+
postId: params.postId,
|
|
278
|
+
authorizedTarget: params.authorizedTarget
|
|
279
|
+
})) ?? await resolveBotUserId(client, cacheKey);
|
|
280
|
+
if (!userId) return {
|
|
281
|
+
ok: false,
|
|
282
|
+
error: "Mattermost reactions failed: could not resolve bot user id."
|
|
283
|
+
};
|
|
284
|
+
await options.mutation(client, {
|
|
285
|
+
userId,
|
|
286
|
+
postId: params.postId,
|
|
287
|
+
emojiName: params.emojiName
|
|
288
|
+
});
|
|
289
|
+
} catch (err) {
|
|
290
|
+
return {
|
|
291
|
+
ok: false,
|
|
292
|
+
error: `Mattermost ${options.action} reaction failed: ${String(err)}`
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
return { ok: true };
|
|
296
|
+
}
|
|
297
|
+
async function createReaction(client, params) {
|
|
298
|
+
await client.request("/reactions", {
|
|
299
|
+
method: "POST",
|
|
300
|
+
body: JSON.stringify({
|
|
301
|
+
user_id: params.userId,
|
|
302
|
+
post_id: params.postId,
|
|
303
|
+
emoji_name: params.emojiName
|
|
304
|
+
}),
|
|
305
|
+
discardResponse: true
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
async function deleteReaction(client, params) {
|
|
309
|
+
const emoji = encodeURIComponent(params.emojiName);
|
|
310
|
+
await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, {
|
|
311
|
+
method: "DELETE",
|
|
312
|
+
discardResponse: true
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
//#endregion
|
|
316
|
+
//#region extensions/mattermost/src/mattermost/read.ts
|
|
317
|
+
function parseMattermostChannelTarget(rawTarget) {
|
|
318
|
+
const normalized = normalizeMattermostMessagingTarget(rawTarget);
|
|
319
|
+
if (normalized?.startsWith("channel:")) return normalized.slice(8).trim() || void 0;
|
|
320
|
+
const trimmed = rawTarget.trim();
|
|
321
|
+
return trimmed && !trimmed.includes(":") ? trimmed : void 0;
|
|
322
|
+
}
|
|
323
|
+
function isCurrentMattermostReadTarget(params) {
|
|
324
|
+
const toolContext = params.context.toolContext;
|
|
325
|
+
const requesterAccountId = params.context.requesterAccountId?.trim();
|
|
326
|
+
if (normalizeLowercaseStringOrEmpty(toolContext?.currentChannelProvider) !== "mattermost" || !requesterAccountId || normalizeAccountId(requesterAccountId) !== normalizeAccountId(params.accountId)) return false;
|
|
327
|
+
const nativeChannelId = toolContext?.currentChannelId;
|
|
328
|
+
if (typeof nativeChannelId === "string" && nativeChannelId.trim()) return parseMattermostChannelTarget(nativeChannelId) === params.channelId;
|
|
329
|
+
const messagingTarget = toolContext?.currentMessagingTarget;
|
|
330
|
+
return typeof messagingTarget === "string" && Boolean(messagingTarget.trim()) && parseMattermostChannelTarget(messagingTarget) === params.channelId;
|
|
331
|
+
}
|
|
332
|
+
function isConfiguredMattermostReadTarget(params) {
|
|
333
|
+
const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
|
|
334
|
+
providerConfigPresent: params.cfg.channels?.mattermost !== void 0,
|
|
335
|
+
groupPolicy: params.account.config.groupPolicy,
|
|
336
|
+
defaultGroupPolicy: params.cfg.channels?.defaults?.groupPolicy
|
|
337
|
+
});
|
|
338
|
+
if (groupPolicy === "disabled") return false;
|
|
339
|
+
if (groupPolicy === "open") return true;
|
|
340
|
+
const groups = params.account.config.groups;
|
|
341
|
+
return groups?.[params.channelId] !== void 0 || groups?.["*"] !== void 0;
|
|
342
|
+
}
|
|
343
|
+
async function readMattermostMessages(params) {
|
|
344
|
+
const account = resolveMattermostAccount({
|
|
345
|
+
cfg: params.cfg,
|
|
346
|
+
accountId: params.accountId
|
|
347
|
+
});
|
|
348
|
+
if (!account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
|
|
349
|
+
const baseUrl = account.baseUrl?.trim();
|
|
350
|
+
const botToken = account.botToken?.trim();
|
|
351
|
+
if (!baseUrl || !botToken) throw new Error("Mattermost botToken/baseUrl missing.");
|
|
352
|
+
const client = createMattermostClient({
|
|
353
|
+
baseUrl,
|
|
354
|
+
botToken,
|
|
355
|
+
fetchImpl: params.fetchImpl,
|
|
356
|
+
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
|
|
357
|
+
});
|
|
358
|
+
const directOperator = params.context.conversationReadOrigin === "direct-operator";
|
|
359
|
+
const currentConversation = isCurrentMattermostReadTarget({
|
|
360
|
+
accountId: account.accountId,
|
|
361
|
+
channelId: params.channelId,
|
|
362
|
+
context: params.context
|
|
363
|
+
});
|
|
364
|
+
if (!directOperator && !currentConversation) {
|
|
365
|
+
const requesterAccountId = params.context.requesterAccountId?.trim();
|
|
366
|
+
const sameProvider = normalizeLowercaseStringOrEmpty(params.context.toolContext?.currentChannelProvider) === "mattermost";
|
|
367
|
+
const sameAccount = requesterAccountId && normalizeAccountId(requesterAccountId) === normalizeAccountId(account.accountId);
|
|
368
|
+
if (!sameProvider || !sameAccount) throw new Error("Mattermost delegated reads require the current Mattermost account.");
|
|
369
|
+
const channel = await fetchMattermostChannel(client, params.channelId);
|
|
370
|
+
if (channel.type !== "O" && channel.type !== "P" || !isConfiguredMattermostReadTarget({
|
|
371
|
+
cfg: params.cfg,
|
|
372
|
+
account,
|
|
373
|
+
channelId: params.channelId
|
|
374
|
+
})) throw new Error("Mattermost read target channel is not allowed.");
|
|
375
|
+
}
|
|
376
|
+
return await fetchMattermostChannelPosts(client, params.channelId, {
|
|
377
|
+
limit: params.limit,
|
|
378
|
+
before: params.before,
|
|
379
|
+
after: params.after
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
//#endregion
|
|
383
|
+
export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, probeMattermost, readMattermostMessages, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
1
|
+
import { asOptionalObjectRecord, normalizeLowercaseStringOrEmpty, normalizeOptionalString, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
2
2
|
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
|
|
3
3
|
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
|
|
4
|
-
import { PlatformMessageNotDispatchedError, collectErrorGraphCandidates } from "openclaw/plugin-sdk/error-runtime";
|
|
4
|
+
import { PlatformMessageNotDispatchedError, collectErrorGraphCandidates, readErrorName } from "openclaw/plugin-sdk/error-runtime";
|
|
5
5
|
import { buildTimeoutAbortSignal } from "openclaw/plugin-sdk/extension-shared";
|
|
6
6
|
import { captureChannelReadAuthority, responseWithRelease } from "openclaw/plugin-sdk/fetch-runtime";
|
|
7
7
|
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
@@ -23,6 +23,7 @@ const MattermostPostSchema = z.object({
|
|
|
23
23
|
type: z.string().nullable().optional(),
|
|
24
24
|
root_id: z.string().nullable().optional(),
|
|
25
25
|
create_at: z.number().nullable().optional(),
|
|
26
|
+
delete_at: z.number().nullable().optional(),
|
|
26
27
|
props: z.record(z.string(), z.unknown()).nullable().optional()
|
|
27
28
|
}).passthrough();
|
|
28
29
|
const MattermostPostListSchema = z.object({
|
|
@@ -146,12 +147,13 @@ function createMattermostClient(params) {
|
|
|
146
147
|
} : void 0) ?? guardedFetchImpl;
|
|
147
148
|
const request = async (path, init) => {
|
|
148
149
|
const url = buildMattermostApiUrl(baseUrl, path);
|
|
149
|
-
const
|
|
150
|
+
const { discardResponse, ...requestInit } = init ?? {};
|
|
151
|
+
const headers = new Headers(requestInit.headers);
|
|
150
152
|
headers.set("Authorization", `Bearer ${token}`);
|
|
151
|
-
if (typeof
|
|
153
|
+
if (typeof requestInit.body === "string" && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
152
154
|
const isMessagePost = path === "/posts" && init?.method?.toUpperCase() === "POST";
|
|
153
155
|
const res = await fetchImpl(url, {
|
|
154
|
-
...
|
|
156
|
+
...requestInit,
|
|
155
157
|
headers,
|
|
156
158
|
isMessagePost
|
|
157
159
|
});
|
|
@@ -160,7 +162,7 @@ function createMattermostClient(params) {
|
|
|
160
162
|
throw new Error(`Mattermost API ${res.status} ${res.statusText}: ${detail || "unknown error"}`);
|
|
161
163
|
}
|
|
162
164
|
if (res.status === 204) return;
|
|
163
|
-
if (
|
|
165
|
+
if (discardResponse) {
|
|
164
166
|
try {
|
|
165
167
|
await res.body?.cancel();
|
|
166
168
|
} catch {}
|
|
@@ -224,7 +226,8 @@ async function sendMattermostTyping(client, params) {
|
|
|
224
226
|
if (parentId) payload.parent_id = parentId;
|
|
225
227
|
await client.request("/users/me/typing", {
|
|
226
228
|
method: "POST",
|
|
227
|
-
body: JSON.stringify(payload)
|
|
229
|
+
body: JSON.stringify(payload),
|
|
230
|
+
discardResponse: true
|
|
228
231
|
});
|
|
229
232
|
}
|
|
230
233
|
async function createMattermostDirectChannel(client, userIds, signal, timeoutMs) {
|
|
@@ -307,42 +310,15 @@ function isRetryableError(error) {
|
|
|
307
310
|
current.reason,
|
|
308
311
|
...Array.isArray(current.errors) ? current.errors : []
|
|
309
312
|
]);
|
|
310
|
-
const messages = candidates.map((candidate) => normalizeLowercaseStringOrEmpty(
|
|
313
|
+
const messages = candidates.map((candidate) => normalizeLowercaseStringOrEmpty(readStringField(asOptionalObjectRecord(candidate), "message"))).filter((message) => Boolean(message));
|
|
311
314
|
if (messages.some((message) => /mattermost api 5\d{2}\b/.test(message))) return true;
|
|
312
315
|
if (messages.some((message) => /mattermost api 429\b/.test(message) || message.includes("too many requests"))) return true;
|
|
313
|
-
|
|
314
|
-
const clientErrorMatch = message.match(/mattermost api (4\d{2})\b/);
|
|
315
|
-
if (!clientErrorMatch) continue;
|
|
316
|
-
const statusCodeText = clientErrorMatch[1];
|
|
317
|
-
if (!statusCodeText) continue;
|
|
318
|
-
const statusCode = Number.parseInt(statusCodeText, 10);
|
|
319
|
-
if (statusCode >= 400 && statusCode < 500) return false;
|
|
320
|
-
}
|
|
316
|
+
if (messages.some((message) => /mattermost api 4\d{2}\b/.test(message))) return false;
|
|
321
317
|
if (messages.some((message) => /mattermost api \d{3}\b/.test(message))) return false;
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const code = readErrorCode(candidate);
|
|
325
|
-
if (code) codes.push(code);
|
|
326
|
-
}
|
|
327
|
-
if (codes.some((code) => RETRYABLE_NETWORK_ERROR_CODES.has(code))) return true;
|
|
328
|
-
const names = [];
|
|
329
|
-
for (const candidate of candidates) {
|
|
330
|
-
const name = readErrorName(candidate);
|
|
331
|
-
if (name) names.push(name);
|
|
332
|
-
}
|
|
333
|
-
if (names.some((name) => RETRYABLE_NETWORK_ERROR_NAMES.has(name))) return true;
|
|
318
|
+
if (candidates.some((candidate) => RETRYABLE_NETWORK_ERROR_CODES.has(readErrorCode(candidate) ?? ""))) return true;
|
|
319
|
+
if (candidates.some((candidate) => RETRYABLE_NETWORK_ERROR_NAMES.has(readErrorName(candidate)))) return true;
|
|
334
320
|
return messages.some((message) => RETRYABLE_NETWORK_MESSAGE_SNIPPETS.some((pattern) => message.includes(pattern)));
|
|
335
321
|
}
|
|
336
|
-
function readErrorMessage(error) {
|
|
337
|
-
if (!error || typeof error !== "object") return;
|
|
338
|
-
const message = error.message;
|
|
339
|
-
return typeof message === "string" && message.trim() ? message : void 0;
|
|
340
|
-
}
|
|
341
|
-
function readErrorName(error) {
|
|
342
|
-
if (!error || typeof error !== "object") return;
|
|
343
|
-
const name = error.name;
|
|
344
|
-
return typeof name === "string" && name.trim() ? name : void 0;
|
|
345
|
-
}
|
|
346
322
|
function readErrorCode(error) {
|
|
347
323
|
if (!error || typeof error !== "object") return;
|
|
348
324
|
const { code, errno } = error;
|
|
@@ -390,7 +366,10 @@ async function updateMattermostPost(client, postId, params) {
|
|
|
390
366
|
});
|
|
391
367
|
}
|
|
392
368
|
async function deleteMattermostPost(client, postId) {
|
|
393
|
-
await client.request(`/posts/${postId}`, {
|
|
369
|
+
await client.request(`/posts/${postId}`, {
|
|
370
|
+
method: "DELETE",
|
|
371
|
+
discardResponse: true
|
|
372
|
+
});
|
|
394
373
|
}
|
|
395
374
|
async function uploadMattermostFile(client, params) {
|
|
396
375
|
const form = new FormData();
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { n as __reExport, t as __exportAll } from "./rolldown-runtime-BBjsoOtd.mjs";
|
|
2
|
+
//#region packages/normalization-core/src/record-coerce.ts
|
|
3
|
+
/** Type guard for non-array object records at browser-safe boundaries. */
|
|
4
|
+
function isRecord(value) {
|
|
5
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
/** Returns a non-array record or null. */
|
|
8
|
+
function asNullableRecord(value) {
|
|
9
|
+
return isRecord(value) ? value : null;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/config/channel-config-normalization.ts
|
|
13
|
+
/** Applies one channel-specific doctor migration to every object-shaped account. */
|
|
14
|
+
function normalizeChannelAccounts(params) {
|
|
15
|
+
const rawAccounts = asNullableRecord(params.entry.accounts);
|
|
16
|
+
if (!rawAccounts) return {
|
|
17
|
+
entry: params.entry,
|
|
18
|
+
changed: false
|
|
19
|
+
};
|
|
20
|
+
let changed = false;
|
|
21
|
+
const accounts = { ...rawAccounts };
|
|
22
|
+
for (const [accountId, value] of Object.entries(rawAccounts)) {
|
|
23
|
+
const account = asNullableRecord(value);
|
|
24
|
+
if (!account) continue;
|
|
25
|
+
const normalized = params.normalizeAccount({
|
|
26
|
+
account,
|
|
27
|
+
accountId,
|
|
28
|
+
pathPrefix: `${params.pathPrefix}.accounts.${accountId}`,
|
|
29
|
+
changes: params.changes
|
|
30
|
+
});
|
|
31
|
+
if (normalized.changed) {
|
|
32
|
+
accounts[accountId] = normalized.entry;
|
|
33
|
+
changed = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return changed ? {
|
|
37
|
+
entry: {
|
|
38
|
+
...params.entry,
|
|
39
|
+
accounts
|
|
40
|
+
},
|
|
41
|
+
changed: true
|
|
42
|
+
} : {
|
|
43
|
+
entry: params.entry,
|
|
44
|
+
changed: false
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Applies the same channel-specific doctor migration at root and account scope. */
|
|
48
|
+
function normalizeChannelConfigEntries(params) {
|
|
49
|
+
const changes = params.changes ?? [];
|
|
50
|
+
const channels = params.cfg.channels;
|
|
51
|
+
const entry = asNullableRecord(channels?.[params.channelId]);
|
|
52
|
+
if (!entry) return {
|
|
53
|
+
config: params.cfg,
|
|
54
|
+
changes
|
|
55
|
+
};
|
|
56
|
+
const channelPath = `channels.${params.channelId}`;
|
|
57
|
+
const root = params.normalizeEntry({
|
|
58
|
+
entry,
|
|
59
|
+
pathPrefix: channelPath,
|
|
60
|
+
changes
|
|
61
|
+
});
|
|
62
|
+
const accounts = normalizeChannelAccounts({
|
|
63
|
+
entry: root.entry,
|
|
64
|
+
pathPrefix: channelPath,
|
|
65
|
+
changes,
|
|
66
|
+
normalizeAccount: (accountParams) => params.normalizeEntry({
|
|
67
|
+
entry: accountParams.account,
|
|
68
|
+
accountId: accountParams.accountId,
|
|
69
|
+
pathPrefix: accountParams.pathPrefix,
|
|
70
|
+
changes: accountParams.changes
|
|
71
|
+
})
|
|
72
|
+
});
|
|
73
|
+
if (!root.changed && !accounts.changed) return {
|
|
74
|
+
config: params.cfg,
|
|
75
|
+
changes
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
config: {
|
|
79
|
+
...params.cfg,
|
|
80
|
+
channels: {
|
|
81
|
+
...channels,
|
|
82
|
+
[params.channelId]: accounts.entry
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
changes
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/plugin-sdk/legacy-webhook-listener-migration.ts
|
|
90
|
+
/** Preserve explicitly configured webhook listeners while moving ingress onto Gateway routes. */
|
|
91
|
+
function createLegacyWebhookListenerDoctorContract(params) {
|
|
92
|
+
const portKey = params.portKey ?? "webhookPort";
|
|
93
|
+
const hostKey = params.hostKey === void 0 ? "webhookHost" : params.hostKey;
|
|
94
|
+
const source = (entry) => params.webhookKey ? asNullableRecord(entry[params.webhookKey]) : entry;
|
|
95
|
+
const hasLegacy = (value) => {
|
|
96
|
+
const entry = asNullableRecord(value);
|
|
97
|
+
const listener = entry && source(entry);
|
|
98
|
+
return Boolean(listener && (Object.hasOwn(listener, portKey) || hostKey && Object.hasOwn(listener, hostKey)));
|
|
99
|
+
};
|
|
100
|
+
const prefix = `channels.${params.channelKey}`;
|
|
101
|
+
return {
|
|
102
|
+
legacyConfigRules: [{
|
|
103
|
+
path: ["channels", params.channelKey],
|
|
104
|
+
message: `${prefix} webhook listeners moved to Gateway routes. Run "openclaw doctor --fix" to preserve explicitly configured listener settings as legacyWebhook.`,
|
|
105
|
+
match: (value) => {
|
|
106
|
+
const accounts = asNullableRecord(asNullableRecord(value)?.accounts);
|
|
107
|
+
return hasLegacy(value) || Object.values(accounts ?? {}).some(hasLegacy);
|
|
108
|
+
}
|
|
109
|
+
}],
|
|
110
|
+
normalizeCompatibilityConfig: ({ cfg }) => {
|
|
111
|
+
const root = asNullableRecord(asNullableRecord(cfg.channels)?.[params.channelKey]);
|
|
112
|
+
const inherited = root && source(root);
|
|
113
|
+
const canonicalRoot = asNullableRecord(root?.legacyWebhook);
|
|
114
|
+
return normalizeChannelConfigEntries({
|
|
115
|
+
cfg,
|
|
116
|
+
channelId: params.channelKey,
|
|
117
|
+
normalizeEntry: ({ entry, accountId, pathPrefix, changes }) => {
|
|
118
|
+
const listener = source(entry);
|
|
119
|
+
if (!listener || !hasLegacy(entry)) return {
|
|
120
|
+
entry,
|
|
121
|
+
changed: false
|
|
122
|
+
};
|
|
123
|
+
const next = { ...entry };
|
|
124
|
+
const port = Object.hasOwn(listener, portKey) ? listener[portKey] : (accountId ? canonicalRoot?.port ?? inherited?.[portKey] : void 0) ?? params.defaultPort;
|
|
125
|
+
const inheritedHost = accountId ? canonicalRoot ? canonicalRoot.host : (hostKey ? inherited?.[hostKey] : void 0) ?? params.defaultHost : params.defaultHost;
|
|
126
|
+
const host = hostKey ? listener[hostKey] ?? inheritedHost : inheritedHost;
|
|
127
|
+
const legacyPath = [pathPrefix, params.webhookKey].filter(Boolean).join(".");
|
|
128
|
+
if (Object.hasOwn(entry, "legacyWebhook")) changes.push(`Removed ${legacyPath} legacy listener keys; ${pathPrefix}.legacyWebhook is already configured.`);
|
|
129
|
+
else if (accountId && root?.legacyWebhook === false) changes.push(`Removed ${legacyPath} legacy listener keys; ${prefix}.legacyWebhook: false keeps this account's inherited listener disabled.`);
|
|
130
|
+
else {
|
|
131
|
+
next.legacyWebhook = {
|
|
132
|
+
port,
|
|
133
|
+
...host !== void 0 ? { host } : {}
|
|
134
|
+
};
|
|
135
|
+
changes.push(`Moved ${legacyPath} listener settings to ${pathPrefix}.legacyWebhook. Point the external callback or reverse proxy at the Gateway port and webhook path, verify delivery, then set legacyWebhook: false to disable legacy forwarding.`);
|
|
136
|
+
}
|
|
137
|
+
const updated = params.webhookKey ? { ...listener } : next;
|
|
138
|
+
delete updated[portKey];
|
|
139
|
+
if (hostKey) delete updated[hostKey];
|
|
140
|
+
if (params.webhookKey) {
|
|
141
|
+
if (Object.keys(updated).length) next[params.webhookKey] = updated;
|
|
142
|
+
else delete next[params.webhookKey];
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
entry: next,
|
|
146
|
+
changed: true
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region \0openclaw:bundled-sdk:openclaw/plugin-sdk/runtime-doctor-migrations
|
|
155
|
+
var runtime_doctor_migrations_exports = /* @__PURE__ */ __exportAll({ createLegacyWebhookListenerDoctorContract: () => createLegacyWebhookListenerDoctorContract });
|
|
156
|
+
import * as import_openclaw_plugin_sdk_runtime_doctor_migrations from "openclaw/plugin-sdk/runtime-doctor-migrations";
|
|
157
|
+
__reExport(runtime_doctor_migrations_exports, import_openclaw_plugin_sdk_runtime_doctor_migrations);
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region extensions/mattermost/src/doctor-contract.ts
|
|
160
|
+
const networkContract = (0, runtime_doctor_migrations_exports.createLegacyPrivateNetworkDoctorContract)({ channelKey: "mattermost" });
|
|
161
|
+
const streamingAliasMigration = (0, runtime_doctor_migrations_exports.defineChannelAliasMigration)({
|
|
162
|
+
channelId: "mattermost",
|
|
163
|
+
streaming: { defaultMode: "partial" },
|
|
164
|
+
accountStreamingReplacesRoot: true
|
|
165
|
+
});
|
|
166
|
+
const legacyConfigRules = [...networkContract.legacyConfigRules, ...streamingAliasMigration.legacyConfigRules];
|
|
167
|
+
function normalizeCompatibilityConfig({ cfg }) {
|
|
168
|
+
const network = networkContract.normalizeCompatibilityConfig({ cfg });
|
|
169
|
+
return streamingAliasMigration.normalizeChannelConfig({
|
|
170
|
+
cfg: network.config,
|
|
171
|
+
changes: network.changes
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
//#endregion
|
|
175
|
+
export { normalizeCompatibilityConfig as n, legacyConfigRules as t };
|