@openclaw/mattermost 2026.7.2-beta.4 → 2026.7.2-beta.5
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/dist/{accounts-B-GrNVwP.js → accounts-BR6Nl5Qf.js} +8 -20
- package/dist/api.js +2 -2
- package/dist/channel-plugin-api.js +1 -1
- package/dist/{channel-plugin-runtime-CgRXlOvV.js → channel-plugin-runtime-DLBTUlbh.js} +2 -2
- package/dist/channel-plugin-runtime.js +1 -1
- package/dist/{channel.runtime-VRis1MN2.js → channel.runtime-CR1V5M8l.js} +1659 -1806
- package/dist/{interactions-DODXaHdE.js → interactions-B4gg-KRm.js} +1 -1
- package/dist/{monitor-auth-4zjr5tXP.js → monitor-auth-BOh6zLW9.js} +1 -1
- package/dist/policy-api.js +1 -1
- package/dist/runtime-api.js +1 -2
- package/dist/slash-route-api.js +1 -1
- package/dist/{slash-state-CFEaCLnp.js → slash-state-VCRdqj5F.js} +45 -59
- package/package.json +4 -5
- package/npm-shrinkwrap.json +0 -54
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
|
|
2
2
|
import { _ as updateMattermostPost, a as createMattermostPost, f as fetchMattermostUserTeams, g as sendMattermostTyping, l as fetchMattermostMe, m as readMattermostError, n as buildMattermostApiUrl, o as deleteMattermostPost, p as normalizeMattermostBaseUrl, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostUser } from "./client-w0lkxuKh.js";
|
|
3
|
-
import { C as
|
|
4
|
-
import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-
|
|
5
|
-
import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-
|
|
6
|
-
import { a as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-
|
|
7
|
-
import { _ as
|
|
3
|
+
import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy, T as resolveDefaultGroupPolicy, _ as logInboundDrop, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, x as registerPluginHttpRoute, y as parseTcpPort } from "./monitor-auth-BOh6zLW9.js";
|
|
4
|
+
import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-B4gg-KRm.js";
|
|
5
|
+
import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-BR6Nl5Qf.js";
|
|
6
|
+
import { a as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-DLBTUlbh.js";
|
|
7
|
+
import { _ as isSlashCommandsEnabled, a as sendMessageMattermost, b as resolveSlashCommandConfig, c as deliverMattermostReplyPayload, d as parseMattermostModelPickerContext, f as renderMattermostModelsPickerView, g as cleanupSlashCommands, h as DEFAULT_COMMAND_SPECS, l as toMattermostChannelDeliveryResult, m as resolveMattermostModelPickerCurrentModel, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as renderMattermostProviderPickerView, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as buildMattermostAllowedModelRefs, v as registerSlashCommands, y as resolveCallbackUrl } from "./slash-state-VCRdqj5F.js";
|
|
8
8
|
import { randomUUID } from "node:crypto";
|
|
9
9
|
import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
|
|
10
10
|
import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
@@ -16,18 +16,18 @@ import { z } from "zod";
|
|
|
16
16
|
import { buildChannelInboundMediaPayload, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, resolveInboundMentionDecision, toInboundMediaFacts } from "openclaw/plugin-sdk/channel-inbound";
|
|
17
17
|
import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
|
|
18
18
|
import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
|
|
19
|
-
import { resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
19
|
+
import { fanInChannelIngressLifecycles, resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
20
20
|
import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
|
|
21
21
|
import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
|
|
22
22
|
import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
|
|
23
23
|
import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
|
|
24
|
-
import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
24
|
+
import { runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
25
25
|
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
26
26
|
import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
|
|
27
|
-
import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
|
|
28
27
|
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
29
28
|
import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
|
|
30
29
|
import WebSocket from "ws";
|
|
30
|
+
import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
|
|
31
31
|
import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
|
|
32
32
|
//#region extensions/mattermost/src/mattermost/directory.ts
|
|
33
33
|
function buildClient(params) {
|
|
@@ -166,234 +166,6 @@ async function listMattermostDirectoryPeers(params) {
|
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
//#endregion
|
|
169
|
-
//#region extensions/mattermost/src/mattermost/draft-stream.ts
|
|
170
|
-
const MATTERMOST_STREAM_MAX_CHARS = 4e3;
|
|
171
|
-
const DEFAULT_THROTTLE_MS = 1e3;
|
|
172
|
-
function normalizeMattermostDraftText(text, maxChars) {
|
|
173
|
-
const trimmed = text.trim();
|
|
174
|
-
if (!trimmed) return "";
|
|
175
|
-
if (trimmed.length <= maxChars) return trimmed;
|
|
176
|
-
return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
|
|
177
|
-
}
|
|
178
|
-
function createMattermostDraftPreviewBoundaryController(params) {
|
|
179
|
-
let hasStreamedContent = false;
|
|
180
|
-
return {
|
|
181
|
-
noteUpdate() {
|
|
182
|
-
hasStreamedContent = true;
|
|
183
|
-
},
|
|
184
|
-
async noteBoundary() {
|
|
185
|
-
if (!params.enabled) return;
|
|
186
|
-
if (!hasStreamedContent) return;
|
|
187
|
-
hasStreamedContent = false;
|
|
188
|
-
await params.forceNewMessage();
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
function createMattermostDraftStream(params) {
|
|
193
|
-
const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
|
|
194
|
-
const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
|
|
195
|
-
const streamState = {
|
|
196
|
-
stopped: false,
|
|
197
|
-
final: false
|
|
198
|
-
};
|
|
199
|
-
let currentGeneration = {
|
|
200
|
-
lastSentText: "",
|
|
201
|
-
latestSourceText: "",
|
|
202
|
-
ready: Promise.resolve()
|
|
203
|
-
};
|
|
204
|
-
const sealedAssistantTexts = [];
|
|
205
|
-
const sendOrEditStreamMessage = async (text) => {
|
|
206
|
-
if (streamState.stopped && !streamState.final) return false;
|
|
207
|
-
const target = currentGeneration;
|
|
208
|
-
const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
|
|
209
|
-
if (!normalized) return false;
|
|
210
|
-
await target.ready;
|
|
211
|
-
if (streamState.stopped && !streamState.final) return false;
|
|
212
|
-
if (normalized === target.lastSentText) return true;
|
|
213
|
-
try {
|
|
214
|
-
if (target.postId) await updateMattermostPost(params.client, target.postId, { message: normalized });
|
|
215
|
-
else {
|
|
216
|
-
const postId = (await createMattermostPost(params.client, {
|
|
217
|
-
channelId: params.channelId,
|
|
218
|
-
message: normalized,
|
|
219
|
-
rootId: params.rootId
|
|
220
|
-
})).id?.trim();
|
|
221
|
-
if (!postId) {
|
|
222
|
-
streamState.stopped = true;
|
|
223
|
-
params.warn?.("mattermost stream preview stopped (missing post id from create)");
|
|
224
|
-
return false;
|
|
225
|
-
}
|
|
226
|
-
target.postId = postId;
|
|
227
|
-
}
|
|
228
|
-
target.lastSentText = normalized;
|
|
229
|
-
return true;
|
|
230
|
-
} catch (err) {
|
|
231
|
-
streamState.stopped = true;
|
|
232
|
-
params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
233
|
-
return false;
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
const clearMessageId = () => {
|
|
237
|
-
currentGeneration.postId = void 0;
|
|
238
|
-
};
|
|
239
|
-
const isValidMessageId = (value) => typeof value === "string" && value.length > 0;
|
|
240
|
-
const deleteMessage = async (postId) => {
|
|
241
|
-
await deleteMattermostPost(params.client, postId);
|
|
242
|
-
};
|
|
243
|
-
const { loop, update: updateLifecycle, stop: stopLifecycle, stopForClear, clearWithStop, seal: sealLifecycle } = createFinalizableDraftLifecycle({
|
|
244
|
-
throttleMs,
|
|
245
|
-
state: streamState,
|
|
246
|
-
sendOrEditStreamMessage,
|
|
247
|
-
readMessageId: () => currentGeneration.postId,
|
|
248
|
-
clearMessageId,
|
|
249
|
-
isValidMessageId,
|
|
250
|
-
deleteMessage,
|
|
251
|
-
warn: params.warn,
|
|
252
|
-
warnPrefix: "mattermost stream preview cleanup failed"
|
|
253
|
-
});
|
|
254
|
-
const forceNewMessage = () => {
|
|
255
|
-
if (streamState.stopped || streamState.final) return Promise.resolve();
|
|
256
|
-
const pendingText = loop.takePending();
|
|
257
|
-
const inFlightAtBoundary = loop.waitForInFlight();
|
|
258
|
-
const sealed = currentGeneration;
|
|
259
|
-
const boundary = (async () => {
|
|
260
|
-
try {
|
|
261
|
-
await sealed.ready;
|
|
262
|
-
await inFlightAtBoundary;
|
|
263
|
-
if (streamState.stopped && !streamState.final) return;
|
|
264
|
-
const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
|
|
265
|
-
const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
|
|
266
|
-
const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
|
|
267
|
-
const firstChunk = chunks[0];
|
|
268
|
-
if (!firstChunk) return;
|
|
269
|
-
if (sealed.postId) {
|
|
270
|
-
if (firstChunk !== sealed.lastSentText) await updateMattermostPost(params.client, sealed.postId, { message: firstChunk });
|
|
271
|
-
} else await createMattermostPost(params.client, {
|
|
272
|
-
channelId: params.channelId,
|
|
273
|
-
message: firstChunk,
|
|
274
|
-
rootId: params.rootId
|
|
275
|
-
});
|
|
276
|
-
for (const chunk of chunks.slice(1)) await createMattermostPost(params.client, {
|
|
277
|
-
channelId: params.channelId,
|
|
278
|
-
message: chunk,
|
|
279
|
-
rootId: params.rootId
|
|
280
|
-
});
|
|
281
|
-
const assistantText = sealed.latestAssistantText?.trim();
|
|
282
|
-
if (assistantText) sealedAssistantTexts.push(assistantText);
|
|
283
|
-
} catch (err) {
|
|
284
|
-
params.warn?.(`mattermost stream preview boundary flush failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
285
|
-
}
|
|
286
|
-
})();
|
|
287
|
-
currentGeneration = {
|
|
288
|
-
lastSentText: "",
|
|
289
|
-
latestSourceText: "",
|
|
290
|
-
ready: boundary
|
|
291
|
-
};
|
|
292
|
-
loop.resetThrottleWindow();
|
|
293
|
-
return boundary;
|
|
294
|
-
};
|
|
295
|
-
const flush = async () => {
|
|
296
|
-
await loop.flush();
|
|
297
|
-
await currentGeneration.ready;
|
|
298
|
-
};
|
|
299
|
-
const discardPending = async () => {
|
|
300
|
-
await stopForClear();
|
|
301
|
-
await currentGeneration.ready;
|
|
302
|
-
};
|
|
303
|
-
const clear = async () => {
|
|
304
|
-
await clearWithStop(discardPending);
|
|
305
|
-
};
|
|
306
|
-
const seal = async () => {
|
|
307
|
-
await sealLifecycle();
|
|
308
|
-
await currentGeneration.ready;
|
|
309
|
-
};
|
|
310
|
-
const stop = async () => {
|
|
311
|
-
await stopLifecycle();
|
|
312
|
-
await currentGeneration.ready;
|
|
313
|
-
};
|
|
314
|
-
const update = (text) => {
|
|
315
|
-
currentGeneration.latestSourceText = text;
|
|
316
|
-
currentGeneration.latestAssistantText = void 0;
|
|
317
|
-
updateLifecycle(text);
|
|
318
|
-
};
|
|
319
|
-
const updateAssistantText = (text) => {
|
|
320
|
-
currentGeneration.latestSourceText = text;
|
|
321
|
-
currentGeneration.latestAssistantText = text;
|
|
322
|
-
updateLifecycle(text);
|
|
323
|
-
};
|
|
324
|
-
const settleBoundaries = async () => {
|
|
325
|
-
await currentGeneration.ready;
|
|
326
|
-
};
|
|
327
|
-
const resolveFinalText = (text) => {
|
|
328
|
-
if (sealedAssistantTexts.length === 0) return {
|
|
329
|
-
kind: "full",
|
|
330
|
-
text
|
|
331
|
-
};
|
|
332
|
-
let remainingText = text.trim();
|
|
333
|
-
for (const sealedText of sealedAssistantTexts) {
|
|
334
|
-
const completed = sealedText.trim();
|
|
335
|
-
if (!completed || !remainingText.startsWith(completed)) return {
|
|
336
|
-
kind: "full",
|
|
337
|
-
text
|
|
338
|
-
};
|
|
339
|
-
const suffix = remainingText.slice(completed.length);
|
|
340
|
-
if (suffix && !/^\r?\n/.test(suffix)) return {
|
|
341
|
-
kind: "full",
|
|
342
|
-
text
|
|
343
|
-
};
|
|
344
|
-
remainingText = suffix.replace(/^(?:\r?\n)+/, "");
|
|
345
|
-
}
|
|
346
|
-
const currentText = currentGeneration.latestAssistantText?.trim() ?? "";
|
|
347
|
-
const remaining = remainingText.trim();
|
|
348
|
-
if (currentText && !remaining.startsWith(currentText)) return {
|
|
349
|
-
kind: "full",
|
|
350
|
-
text
|
|
351
|
-
};
|
|
352
|
-
return remaining ? {
|
|
353
|
-
kind: "remaining",
|
|
354
|
-
text: remaining
|
|
355
|
-
} : { kind: "already-delivered" };
|
|
356
|
-
};
|
|
357
|
-
params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
|
|
358
|
-
return {
|
|
359
|
-
update,
|
|
360
|
-
updateAssistantText,
|
|
361
|
-
flush,
|
|
362
|
-
postId: () => currentGeneration.postId,
|
|
363
|
-
clear,
|
|
364
|
-
discardPending,
|
|
365
|
-
seal,
|
|
366
|
-
stop,
|
|
367
|
-
forceNewMessage,
|
|
368
|
-
settleBoundaries,
|
|
369
|
-
resolveFinalText
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
//#endregion
|
|
373
|
-
//#region extensions/mattermost/src/mattermost/monitor-activation.ts
|
|
374
|
-
function resolveMattermostInboundMentionDecision(params) {
|
|
375
|
-
const implicitMentions = resolveChannelImplicitMentions({
|
|
376
|
-
cfg: params.cfg,
|
|
377
|
-
channel: "mattermost",
|
|
378
|
-
accountId: params.accountId
|
|
379
|
-
});
|
|
380
|
-
return resolveInboundMentionDecision({
|
|
381
|
-
facts: {
|
|
382
|
-
canDetectMention: params.canDetectMention,
|
|
383
|
-
wasMentioned: params.wasMentioned,
|
|
384
|
-
implicitMentionKinds: params.implicitMentionKinds
|
|
385
|
-
},
|
|
386
|
-
policy: {
|
|
387
|
-
isGroup: params.kind !== "direct",
|
|
388
|
-
requireMention: params.requireMention,
|
|
389
|
-
implicitMentions,
|
|
390
|
-
allowTextCommands: params.allowTextCommands,
|
|
391
|
-
hasControlCommand: params.hasControlCommand,
|
|
392
|
-
commandAuthorized: params.commandAuthorized
|
|
393
|
-
}
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
//#endregion
|
|
397
169
|
//#region extensions/mattermost/src/mattermost/monitor-helpers.ts
|
|
398
170
|
const formatInboundFromLabel$1 = formatInboundFromLabel;
|
|
399
171
|
function resolveThreadSessionKeys$1(params) {
|
|
@@ -431,159 +203,6 @@ function shouldDropEmptyMattermostBody(params) {
|
|
|
431
203
|
return !botUsername || normalizeLowercaseStringOrEmpty(bareMention ?? "") !== `@${botUsername}`;
|
|
432
204
|
}
|
|
433
205
|
//#endregion
|
|
434
|
-
//#region extensions/mattermost/src/mattermost/no-visible-reply-diagnostic.ts
|
|
435
|
-
/**
|
|
436
|
-
* Detects the #80501 symptom: `deliverMattermostReplyPayload` accepted a
|
|
437
|
-
* substantive (non-reasoning) payload, called the underlying
|
|
438
|
-
* `deliverTextOrMediaReply`, and the outcome was `"empty"` — meaning the
|
|
439
|
-
* payload had no text and no media to send, so no Mattermost API call
|
|
440
|
-
* happened. The agent's run completes successfully, but no visible
|
|
441
|
-
* channel/thread reply ever surfaces to the user.
|
|
442
|
-
*
|
|
443
|
-
* Returns a structured violation when the outcome is `"empty"` for a payload
|
|
444
|
-
* that nominally carried user-facing content (text or media bytes that ended
|
|
445
|
-
* up dropped by `resolveSendableOutboundReplyParts`/`sendMediaWithLeadingCaption`).
|
|
446
|
-
* Returns `null` for `"reasoning_skipped"` (intentional suppression),
|
|
447
|
-
* `"text"`, or `"media"` (successful visible sends).
|
|
448
|
-
*/
|
|
449
|
-
function evaluateMattermostNoVisibleReply(params) {
|
|
450
|
-
if (params.outcome !== "empty") return null;
|
|
451
|
-
const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
|
|
452
|
-
const mediaUrlCount = countOutboundMedia(params.payload);
|
|
453
|
-
if (finalText.length === 0 && mediaUrlCount === 0) return null;
|
|
454
|
-
return {
|
|
455
|
-
reason: "no-visible-reply-after-final-delivery",
|
|
456
|
-
outcome: params.outcome,
|
|
457
|
-
finalTextLength: finalText.length,
|
|
458
|
-
mediaUrlCount
|
|
459
|
-
};
|
|
460
|
-
}
|
|
461
|
-
function formatMattermostNoVisibleReplyLog(params) {
|
|
462
|
-
return `mattermost no-visible-reply: ${params.violation.reason} to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.violation.outcome} finalTextLength=${params.violation.finalTextLength} mediaUrlCount=${params.violation.mediaUrlCount}`;
|
|
463
|
-
}
|
|
464
|
-
//#endregion
|
|
465
|
-
//#region extensions/mattermost/src/mattermost/monitor-context.ts
|
|
466
|
-
function shouldUpdateMattermostDraftToolProgress(account) {
|
|
467
|
-
return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
|
|
468
|
-
}
|
|
469
|
-
function shouldSuppressMattermostDefaultToolProgressMessages(account) {
|
|
470
|
-
return account.streamingMode !== "off";
|
|
471
|
-
}
|
|
472
|
-
function buildMattermostModelPickerSelectMessageSid(params) {
|
|
473
|
-
const provider = normalizeLowercaseStringOrEmpty(params.provider);
|
|
474
|
-
const model = normalizeLowercaseStringOrEmpty(params.model);
|
|
475
|
-
return `interaction:${params.postId}:select:${provider}/${model}`;
|
|
476
|
-
}
|
|
477
|
-
function resolveMattermostReplyRootId(params) {
|
|
478
|
-
const threadRootId = normalizeOptionalString(params.threadRootId);
|
|
479
|
-
if (params.kind === "direct" && !threadRootId) return;
|
|
480
|
-
if (threadRootId) return threadRootId;
|
|
481
|
-
return normalizeOptionalString(params.replyToId);
|
|
482
|
-
}
|
|
483
|
-
function canFinalizeMattermostPreviewInPlace(params) {
|
|
484
|
-
return resolveMattermostReplyRootId({
|
|
485
|
-
kind: params.kind,
|
|
486
|
-
threadRootId: params.threadRootId,
|
|
487
|
-
replyToId: params.replyToId
|
|
488
|
-
}) === params.previewRootId?.trim();
|
|
489
|
-
}
|
|
490
|
-
function formatMattermostFinalDeliveryOutcomeLog(params) {
|
|
491
|
-
const violation = evaluateMattermostNoVisibleReply({
|
|
492
|
-
outcome: params.outcome,
|
|
493
|
-
payload: params.payload
|
|
494
|
-
});
|
|
495
|
-
if (violation) return formatMattermostNoVisibleReplyLog({
|
|
496
|
-
violation,
|
|
497
|
-
to: params.to,
|
|
498
|
-
accountId: params.accountId,
|
|
499
|
-
agentId: params.agentId
|
|
500
|
-
});
|
|
501
|
-
if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
|
|
502
|
-
}
|
|
503
|
-
function resolveMattermostEffectiveReplyToId(params) {
|
|
504
|
-
if (params.kind === "direct" && params.replyToMode === "off") return;
|
|
505
|
-
const threadRootId = normalizeOptionalString(params.threadRootId);
|
|
506
|
-
if (threadRootId) return threadRootId;
|
|
507
|
-
const postId = normalizeOptionalString(params.postId);
|
|
508
|
-
if (!postId) return;
|
|
509
|
-
return params.replyToMode === "all" || params.replyToMode === "first" || params.replyToMode === "batched" ? postId : void 0;
|
|
510
|
-
}
|
|
511
|
-
function resolveMattermostThreadSessionContext(params) {
|
|
512
|
-
const effectiveReplyToId = resolveMattermostEffectiveReplyToId({
|
|
513
|
-
kind: params.kind,
|
|
514
|
-
postId: params.postId,
|
|
515
|
-
replyToMode: params.replyToMode,
|
|
516
|
-
threadRootId: params.threadRootId
|
|
517
|
-
});
|
|
518
|
-
const threadKeys = resolveThreadSessionKeys$1({
|
|
519
|
-
baseSessionKey: params.baseSessionKey,
|
|
520
|
-
threadId: effectiveReplyToId,
|
|
521
|
-
parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
|
|
522
|
-
});
|
|
523
|
-
return {
|
|
524
|
-
effectiveReplyToId,
|
|
525
|
-
sessionKey: threadKeys.sessionKey,
|
|
526
|
-
parentSessionKey: threadKeys.parentSessionKey
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
function resolveMattermostPendingHistoryKey(params) {
|
|
530
|
-
return params.kind === "direct" ? null : params.sessionKey;
|
|
531
|
-
}
|
|
532
|
-
function resolveMattermostReactionChannelId(payload) {
|
|
533
|
-
return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
|
|
534
|
-
}
|
|
535
|
-
//#endregion
|
|
536
|
-
//#region extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
|
|
537
|
-
async function deliverMattermostReplyWithDraftPreview(params) {
|
|
538
|
-
if (isReasoningReplyPayload(params.payload)) return;
|
|
539
|
-
await deliverWithFinalizableLivePreviewAdapter({
|
|
540
|
-
kind: params.info.kind,
|
|
541
|
-
payload: params.payload,
|
|
542
|
-
adapter: defineFinalizableLivePreviewAdapter({
|
|
543
|
-
draft: {
|
|
544
|
-
flush: params.draftStream.flush,
|
|
545
|
-
clear: params.draftStream.clear,
|
|
546
|
-
discardPending: params.draftStream.discardPending,
|
|
547
|
-
seal: params.draftStream.seal,
|
|
548
|
-
id: params.draftStream.postId
|
|
549
|
-
},
|
|
550
|
-
buildFinalEdit: (payload) => {
|
|
551
|
-
const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
|
|
552
|
-
const ttsSupplement = getReplyPayloadTtsSupplement(payload);
|
|
553
|
-
const previewFinalText = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
|
|
554
|
-
if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
|
|
555
|
-
kind: params.kind,
|
|
556
|
-
previewRootId: params.effectiveReplyToId,
|
|
557
|
-
threadRootId: params.effectiveReplyToId,
|
|
558
|
-
replyToId: payload.replyToId
|
|
559
|
-
})) return;
|
|
560
|
-
return { message: previewFinalText };
|
|
561
|
-
},
|
|
562
|
-
editFinal: async (previewPostId, edit) => {
|
|
563
|
-
await updateMattermostPost(params.client, previewPostId, edit);
|
|
564
|
-
},
|
|
565
|
-
onPreviewFinalized: () => {
|
|
566
|
-
params.previewState.finalizedViaPreviewPost = true;
|
|
567
|
-
params.recordThreadParticipation?.();
|
|
568
|
-
},
|
|
569
|
-
buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
|
|
570
|
-
deliverSupplemental: async (payload) => {
|
|
571
|
-
await params.deliverPayload(payload);
|
|
572
|
-
},
|
|
573
|
-
logPreviewEditFailure: (err) => {
|
|
574
|
-
params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
|
|
575
|
-
}
|
|
576
|
-
}),
|
|
577
|
-
deliverNormally: async (payload) => {
|
|
578
|
-
const supplement = getReplyPayloadTtsSupplement(payload);
|
|
579
|
-
await params.deliverPayload(supplement && !payload.text?.trim() && supplement.visibleTextAlreadyDelivered !== true ? {
|
|
580
|
-
...payload,
|
|
581
|
-
text: supplement.spokenText
|
|
582
|
-
} : payload);
|
|
583
|
-
}
|
|
584
|
-
});
|
|
585
|
-
}
|
|
586
|
-
//#endregion
|
|
587
206
|
//#region extensions/mattermost/src/mattermost/monitor-websocket.ts
|
|
588
207
|
const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
|
|
589
208
|
const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
|
|
@@ -871,44 +490,6 @@ const MATTERMOST_INGRESS_COMPLETED_TTL_MS = 720 * 60 * 60 * 1e3;
|
|
|
871
490
|
const MATTERMOST_INGRESS_COMPLETED_MAX_ENTRIES = 2e4;
|
|
872
491
|
const MATTERMOST_INGRESS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
|
|
873
492
|
const MATTERMOST_INGRESS_FAILED_MAX_ENTRIES = 2e4;
|
|
874
|
-
/** Fan one merged Mattermost turn's adoption lifecycle across every source claim. */
|
|
875
|
-
function buildMattermostFlushIngressLifecycle(entries) {
|
|
876
|
-
const lifecycles = entries.map((entry) => entry.turnAdoptionLifecycle).filter((lifecycle) => lifecycle !== void 0);
|
|
877
|
-
const [firstLifecycle] = lifecycles;
|
|
878
|
-
if (!firstLifecycle) return {
|
|
879
|
-
lifecycle: void 0,
|
|
880
|
-
settle: async () => {}
|
|
881
|
-
};
|
|
882
|
-
let handedOff = false;
|
|
883
|
-
const adoptAll = async () => {
|
|
884
|
-
for (const lifecycle of lifecycles) await lifecycle.onAdopted();
|
|
885
|
-
};
|
|
886
|
-
return {
|
|
887
|
-
lifecycle: {
|
|
888
|
-
abortSignal: lifecycles.length === 1 ? firstLifecycle.abortSignal : AbortSignal.any(lifecycles.map((lifecycle) => lifecycle.abortSignal)),
|
|
889
|
-
onAdopted: async () => {
|
|
890
|
-
handedOff = true;
|
|
891
|
-
await adoptAll();
|
|
892
|
-
},
|
|
893
|
-
onDeferred: () => {
|
|
894
|
-
handedOff = true;
|
|
895
|
-
for (const lifecycle of lifecycles) lifecycle.onDeferred();
|
|
896
|
-
},
|
|
897
|
-
onAdoptionFinalizing: () => {
|
|
898
|
-
for (const lifecycle of lifecycles) lifecycle.onAdoptionFinalizing();
|
|
899
|
-
},
|
|
900
|
-
onAbandoned: async () => {
|
|
901
|
-
handedOff = true;
|
|
902
|
-
await Promise.all(lifecycles.map(async (lifecycle) => {
|
|
903
|
-
await lifecycle.onAbandoned();
|
|
904
|
-
}));
|
|
905
|
-
}
|
|
906
|
-
},
|
|
907
|
-
settle: async () => {
|
|
908
|
-
if (!handedOff) await adoptAll();
|
|
909
|
-
}
|
|
910
|
-
};
|
|
911
|
-
}
|
|
912
493
|
var MattermostIngressPermanentError = class extends Error {
|
|
913
494
|
constructor(reason, message, options) {
|
|
914
495
|
super(message, options);
|
|
@@ -1026,524 +607,217 @@ function createMattermostIngressMonitor(options) {
|
|
|
1026
607
|
};
|
|
1027
608
|
}
|
|
1028
609
|
//#endregion
|
|
1029
|
-
//#region extensions/mattermost/src/mattermost/
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
610
|
+
//#region extensions/mattermost/src/mattermost/no-visible-reply-diagnostic.ts
|
|
611
|
+
/**
|
|
612
|
+
* Detects the #80501 symptom: `deliverMattermostReplyPayload` accepted a
|
|
613
|
+
* substantive (non-reasoning) payload, called the underlying
|
|
614
|
+
* `deliverTextOrMediaReply`, and the outcome was `"empty"` — meaning the
|
|
615
|
+
* payload had no text and no media to send, so no Mattermost API call
|
|
616
|
+
* happened. The agent's run completes successfully, but no visible
|
|
617
|
+
* channel/thread reply ever surfaces to the user.
|
|
618
|
+
*
|
|
619
|
+
* Returns a structured violation when the outcome is `"empty"` for a payload
|
|
620
|
+
* that nominally carried user-facing content (text or media bytes that ended
|
|
621
|
+
* up dropped by `resolveSendableOutboundReplyParts`/`sendMediaWithLeadingCaption`).
|
|
622
|
+
* Returns `null` for `"reasoning_skipped"` (intentional suppression),
|
|
623
|
+
* `"text"`, or `"media"` (successful visible sends).
|
|
624
|
+
*/
|
|
625
|
+
function evaluateMattermostNoVisibleReply(params) {
|
|
626
|
+
if (params.outcome !== "empty") return null;
|
|
627
|
+
const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
|
|
628
|
+
const mediaUrlCount = countOutboundMedia(params.payload);
|
|
629
|
+
if (finalText.length === 0 && mediaUrlCount === 0) return null;
|
|
1044
630
|
return {
|
|
1045
|
-
|
|
1046
|
-
|
|
631
|
+
reason: "no-visible-reply-after-final-delivery",
|
|
632
|
+
outcome: params.outcome,
|
|
633
|
+
finalTextLength: finalText.length,
|
|
634
|
+
mediaUrlCount
|
|
1047
635
|
};
|
|
1048
636
|
}
|
|
637
|
+
function formatMattermostNoVisibleReplyLog(params) {
|
|
638
|
+
return `mattermost no-visible-reply: ${params.violation.reason} to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.violation.outcome} finalTextLength=${params.violation.finalTextLength} mediaUrlCount=${params.violation.mediaUrlCount}`;
|
|
639
|
+
}
|
|
1049
640
|
//#endregion
|
|
1050
|
-
//#region extensions/mattermost/src/mattermost/monitor-
|
|
1051
|
-
function
|
|
1052
|
-
return
|
|
641
|
+
//#region extensions/mattermost/src/mattermost/monitor-context.ts
|
|
642
|
+
function shouldUpdateMattermostDraftToolProgress(account) {
|
|
643
|
+
return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
|
|
1053
644
|
}
|
|
1054
|
-
function
|
|
1055
|
-
return
|
|
645
|
+
function shouldSuppressMattermostDefaultToolProgressMessages(account) {
|
|
646
|
+
return account.streamingMode !== "off";
|
|
1056
647
|
}
|
|
1057
|
-
function
|
|
1058
|
-
const
|
|
1059
|
-
const
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
648
|
+
function buildMattermostModelPickerSelectMessageSid(params) {
|
|
649
|
+
const provider = normalizeLowercaseStringOrEmpty(params.provider);
|
|
650
|
+
const model = normalizeLowercaseStringOrEmpty(params.model);
|
|
651
|
+
return `interaction:${params.postId}:select:${provider}/${model}`;
|
|
652
|
+
}
|
|
653
|
+
function resolveMattermostReplyRootId(params) {
|
|
654
|
+
const threadRootId = normalizeOptionalString(params.threadRootId);
|
|
655
|
+
if (params.kind === "direct" && !threadRootId) return;
|
|
656
|
+
if (threadRootId) return threadRootId;
|
|
657
|
+
return normalizeOptionalString(params.replyToId);
|
|
658
|
+
}
|
|
659
|
+
function canFinalizeMattermostPreviewInPlace(params) {
|
|
660
|
+
return resolveMattermostReplyRootId({
|
|
661
|
+
kind: params.kind,
|
|
662
|
+
threadRootId: params.threadRootId,
|
|
663
|
+
replyToId: params.replyToId
|
|
664
|
+
}) === params.previewRootId?.trim();
|
|
665
|
+
}
|
|
666
|
+
function formatMattermostFinalDeliveryOutcomeLog(params) {
|
|
667
|
+
const violation = evaluateMattermostNoVisibleReply({
|
|
668
|
+
outcome: params.outcome,
|
|
669
|
+
payload: params.payload
|
|
670
|
+
});
|
|
671
|
+
if (violation) return formatMattermostNoVisibleReplyLog({
|
|
672
|
+
violation,
|
|
673
|
+
to: params.to,
|
|
674
|
+
accountId: params.accountId,
|
|
675
|
+
agentId: params.agentId
|
|
1064
676
|
});
|
|
677
|
+
if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
|
|
1065
678
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
const
|
|
1069
|
-
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
const
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
};
|
|
1081
|
-
const
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
cache.set(key, {
|
|
1086
|
-
value,
|
|
1087
|
-
expiresAt
|
|
1088
|
-
});
|
|
1089
|
-
pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
|
|
1090
|
-
}
|
|
1091
|
-
};
|
|
1092
|
-
const resolveMattermostMedia = async (fileIds) => {
|
|
1093
|
-
const ids = normalizeStringEntries(fileIds ?? []);
|
|
1094
|
-
if (ids.length === 0) return [];
|
|
1095
|
-
const out = [];
|
|
1096
|
-
for (const fileId of ids) {
|
|
1097
|
-
let downloadUrl;
|
|
1098
|
-
try {
|
|
1099
|
-
downloadUrl = buildMattermostApiUrl(client.baseUrl, `/files/${fileId}`);
|
|
1100
|
-
} catch (err) {
|
|
1101
|
-
logger.debug?.(`mattermost: failed to resolve file ${fileId}: ${String(err)}`);
|
|
1102
|
-
out.push({ kind: "unknown" });
|
|
1103
|
-
continue;
|
|
1104
|
-
}
|
|
1105
|
-
try {
|
|
1106
|
-
const saved = await saveRemoteMedia({
|
|
1107
|
-
url: downloadUrl,
|
|
1108
|
-
requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
|
|
1109
|
-
filePathHint: fileId,
|
|
1110
|
-
maxBytes: mediaMaxBytes,
|
|
1111
|
-
ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
|
|
1112
|
-
responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
|
|
1113
|
-
readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
|
|
1114
|
-
});
|
|
1115
|
-
const contentType = saved.contentType ?? void 0;
|
|
1116
|
-
out.push({
|
|
1117
|
-
path: saved.path,
|
|
1118
|
-
contentType,
|
|
1119
|
-
kind: mediaKindFromMime(contentType) ?? "unknown"
|
|
1120
|
-
});
|
|
1121
|
-
} catch (err) {
|
|
1122
|
-
logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
|
|
1123
|
-
let contentType;
|
|
1124
|
-
try {
|
|
1125
|
-
contentType = (await client.request(`/files/${fileId}/info`)).mime_type?.trim() || void 0;
|
|
1126
|
-
} catch (infoErr) {
|
|
1127
|
-
logger.debug?.(`mattermost: failed to resolve metadata for file ${fileId}: ${String(infoErr)}`);
|
|
1128
|
-
}
|
|
1129
|
-
out.push({
|
|
1130
|
-
contentType,
|
|
1131
|
-
kind: mediaKindFromMime(contentType) ?? "unknown"
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
return out;
|
|
1136
|
-
};
|
|
1137
|
-
const sendTypingIndicator = async (channelId, parentId) => {
|
|
1138
|
-
await sendMattermostTyping(client, {
|
|
1139
|
-
channelId,
|
|
1140
|
-
parentId
|
|
1141
|
-
});
|
|
1142
|
-
};
|
|
1143
|
-
const resolveChannelInfo = async (channelId) => {
|
|
1144
|
-
const rawNow = Date.now();
|
|
1145
|
-
const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
|
|
1146
|
-
if (cached !== void 0) return cached;
|
|
1147
|
-
try {
|
|
1148
|
-
const info = await fetchMattermostChannel(client, channelId);
|
|
1149
|
-
setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
|
|
1150
|
-
return info;
|
|
1151
|
-
} catch (err) {
|
|
1152
|
-
logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
|
|
1153
|
-
setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
|
|
1154
|
-
return null;
|
|
1155
|
-
}
|
|
1156
|
-
};
|
|
1157
|
-
const resolveUserInfo = async (userId) => {
|
|
1158
|
-
const rawNow = Date.now();
|
|
1159
|
-
const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
|
|
1160
|
-
if (cached !== void 0) return cached;
|
|
1161
|
-
try {
|
|
1162
|
-
const info = await fetchMattermostUser(client, userId);
|
|
1163
|
-
setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
|
|
1164
|
-
return info;
|
|
1165
|
-
} catch (err) {
|
|
1166
|
-
logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
|
|
1167
|
-
setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
|
|
1168
|
-
return null;
|
|
1169
|
-
}
|
|
1170
|
-
};
|
|
1171
|
-
const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
|
|
1172
|
-
callbackUrl,
|
|
1173
|
-
accountId,
|
|
1174
|
-
channelId,
|
|
1175
|
-
buttons
|
|
679
|
+
function resolveMattermostEffectiveReplyToId(params) {
|
|
680
|
+
if (params.kind === "direct" && params.replyToMode === "off") return;
|
|
681
|
+
const threadRootId = normalizeOptionalString(params.threadRootId);
|
|
682
|
+
if (threadRootId) return threadRootId;
|
|
683
|
+
const postId = normalizeOptionalString(params.postId);
|
|
684
|
+
if (!postId) return;
|
|
685
|
+
return params.replyToMode === "all" || params.replyToMode === "first" || params.replyToMode === "batched" ? postId : void 0;
|
|
686
|
+
}
|
|
687
|
+
function resolveMattermostThreadSessionContext(params) {
|
|
688
|
+
const effectiveReplyToId = resolveMattermostEffectiveReplyToId({
|
|
689
|
+
kind: params.kind,
|
|
690
|
+
postId: params.postId,
|
|
691
|
+
replyToMode: params.replyToMode,
|
|
692
|
+
threadRootId: params.threadRootId
|
|
693
|
+
});
|
|
694
|
+
const threadKeys = resolveThreadSessionKeys$1({
|
|
695
|
+
baseSessionKey: params.baseSessionKey,
|
|
696
|
+
threadId: effectiveReplyToId,
|
|
697
|
+
parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
|
|
1176
698
|
});
|
|
1177
|
-
const updateModelPickerPost = async (paramsLocal) => {
|
|
1178
|
-
const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
|
|
1179
|
-
await updateMattermostPost(client, paramsLocal.postId, {
|
|
1180
|
-
message: paramsLocal.message,
|
|
1181
|
-
props
|
|
1182
|
-
});
|
|
1183
|
-
return {};
|
|
1184
|
-
};
|
|
1185
699
|
return {
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
resolveUserInfo,
|
|
1190
|
-
updateModelPickerPost
|
|
700
|
+
effectiveReplyToId,
|
|
701
|
+
sessionKey: threadKeys.sessionKey,
|
|
702
|
+
parentSessionKey: threadKeys.parentSessionKey
|
|
1191
703
|
};
|
|
1192
704
|
}
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
function buildSlashCommands(params) {
|
|
1196
|
-
const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
|
|
1197
|
-
if (!params.nativeSkills) return commandsToRegister;
|
|
1198
|
-
try {
|
|
1199
|
-
const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
|
|
1200
|
-
for (const spec of skillCommands) {
|
|
1201
|
-
const name = typeof spec.name === "string" ? spec.name.trim() : "";
|
|
1202
|
-
if (!name) continue;
|
|
1203
|
-
const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
|
|
1204
|
-
commandsToRegister.push({
|
|
1205
|
-
trigger,
|
|
1206
|
-
description: spec.description || `Run skill ${name}`,
|
|
1207
|
-
autoComplete: true,
|
|
1208
|
-
autoCompleteHint: "[args]",
|
|
1209
|
-
originalName: name
|
|
1210
|
-
});
|
|
1211
|
-
}
|
|
1212
|
-
} catch (err) {
|
|
1213
|
-
params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
|
|
1214
|
-
}
|
|
1215
|
-
return commandsToRegister;
|
|
1216
|
-
}
|
|
1217
|
-
function dedupeSlashCommands(commands) {
|
|
1218
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1219
|
-
return commands.filter((cmd) => {
|
|
1220
|
-
const key = cmd.trigger.trim();
|
|
1221
|
-
if (!key || seen.has(key)) return false;
|
|
1222
|
-
seen.add(key);
|
|
1223
|
-
return true;
|
|
1224
|
-
});
|
|
1225
|
-
}
|
|
1226
|
-
function buildTriggerMap(commands) {
|
|
1227
|
-
const triggerMap = /* @__PURE__ */ new Map();
|
|
1228
|
-
for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
|
|
1229
|
-
return triggerMap;
|
|
705
|
+
function resolveMattermostPendingHistoryKey(params) {
|
|
706
|
+
return params.kind === "direct" ? null : params.sessionKey;
|
|
1230
707
|
}
|
|
1231
|
-
function
|
|
1232
|
-
|
|
1233
|
-
const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
|
|
1234
|
-
const callbackHost = new URL(params.callbackUrl).hostname;
|
|
1235
|
-
if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
|
|
1236
|
-
} catch {}
|
|
708
|
+
function resolveMattermostReactionChannelId(payload) {
|
|
709
|
+
return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
|
|
1237
710
|
}
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
callbackUrl: params.callbackUrl,
|
|
1247
|
-
commands: params.commands,
|
|
1248
|
-
log: (msg) => params.runtime.log?.(msg)
|
|
1249
|
-
});
|
|
1250
|
-
registered.push(...created);
|
|
1251
|
-
} catch (err) {
|
|
1252
|
-
teamRegistrationFailures += 1;
|
|
1253
|
-
params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
|
|
711
|
+
//#endregion
|
|
712
|
+
//#region extensions/mattermost/src/mattermost/monitor-event-plan.ts
|
|
713
|
+
async function buildMattermostEventPlan(monitor, params) {
|
|
714
|
+
const channelInfo = params.channelInfo ?? await monitor.resources.resolveChannelInfo(params.channelId);
|
|
715
|
+
const channelType = channelInfo?.type?.trim() || params.channelTypeFallback?.trim();
|
|
716
|
+
if (!channelType) {
|
|
717
|
+
monitor.logVerboseMessage(`mattermost: drop ${params.dropLabel} (cannot resolve channel type for ${params.channelId})`);
|
|
718
|
+
return null;
|
|
1254
719
|
}
|
|
720
|
+
const kind = resolveMattermostTrustedChatKind({ channelType });
|
|
721
|
+
const teamId = params.teamId ?? channelInfo?.team_id ?? void 0;
|
|
722
|
+
const channelName = params.channelName ?? channelInfo?.name ?? "";
|
|
723
|
+
const channelDisplay = params.channelDisplay ?? channelInfo?.display_name ?? channelName;
|
|
724
|
+
const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${params.channelId}`;
|
|
725
|
+
const route = monitor.core.channel.routing.resolveAgentRoute({
|
|
726
|
+
cfg: monitor.cfg,
|
|
727
|
+
channel: "mattermost",
|
|
728
|
+
accountId: monitor.account.accountId,
|
|
729
|
+
teamId,
|
|
730
|
+
peer: {
|
|
731
|
+
kind,
|
|
732
|
+
id: kind === "direct" ? params.senderId : params.channelId
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
const thread = resolveMattermostThreadSessionContext({
|
|
736
|
+
baseSessionKey: route.sessionKey,
|
|
737
|
+
kind,
|
|
738
|
+
postId: params.postId,
|
|
739
|
+
replyToMode: resolveMattermostReplyToMode(monitor.account, kind),
|
|
740
|
+
threadRootId: params.threadRootId
|
|
741
|
+
});
|
|
742
|
+
const to = kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
|
|
1255
743
|
return {
|
|
1256
|
-
|
|
1257
|
-
|
|
744
|
+
channelId: params.channelId,
|
|
745
|
+
senderId: params.senderId,
|
|
746
|
+
channelInfo,
|
|
747
|
+
kind,
|
|
748
|
+
teamId,
|
|
749
|
+
channelName,
|
|
750
|
+
channelDisplay,
|
|
751
|
+
roomLabel,
|
|
752
|
+
route,
|
|
753
|
+
thread,
|
|
754
|
+
to,
|
|
755
|
+
finalizeContext: (context) => finalizeInboundContext({
|
|
756
|
+
...context,
|
|
757
|
+
From: kind === "direct" ? `mattermost:${params.senderId}` : kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
|
|
758
|
+
To: to,
|
|
759
|
+
SessionKey: thread.sessionKey,
|
|
760
|
+
DmScope: route.dmScope,
|
|
761
|
+
ParentSessionKey: thread.parentSessionKey,
|
|
762
|
+
AccountId: route.accountId,
|
|
763
|
+
ChatType: kind,
|
|
764
|
+
GroupChannel: channelName ? `#${channelName}` : void 0,
|
|
765
|
+
GroupSpace: teamId,
|
|
766
|
+
SenderId: params.senderId,
|
|
767
|
+
Provider: "mattermost",
|
|
768
|
+
Surface: "mattermost",
|
|
769
|
+
ReplyToId: thread.effectiveReplyToId,
|
|
770
|
+
MessageThreadId: thread.effectiveReplyToId,
|
|
771
|
+
OriginatingChannel: "mattermost",
|
|
772
|
+
OriginatingTo: to
|
|
773
|
+
}),
|
|
774
|
+
createReplyPlan: () => {
|
|
775
|
+
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
|
|
776
|
+
isDirect: kind === "direct",
|
|
777
|
+
dmRetryOptions: monitor.account.config.dmChannelRetry
|
|
778
|
+
});
|
|
779
|
+
return {
|
|
780
|
+
textLimit: monitor.core.channel.text.resolveTextChunkLimit(monitor.cfg, "mattermost", monitor.account.accountId, { fallbackLimit: monitor.account.textChunkLimit ?? 4e3 }),
|
|
781
|
+
tableMode: monitor.core.channel.text.resolveMarkdownTableMode({
|
|
782
|
+
cfg: monitor.cfg,
|
|
783
|
+
channel: "mattermost",
|
|
784
|
+
accountId: monitor.account.accountId
|
|
785
|
+
}),
|
|
786
|
+
deliveryBarrier,
|
|
787
|
+
replyPipeline: { typing: {
|
|
788
|
+
start: () => monitor.resources.sendTypingIndicator(params.channelId, thread.effectiveReplyToId),
|
|
789
|
+
onStartError: (error) => {
|
|
790
|
+
logTypingFailure({
|
|
791
|
+
log: monitor.logDebugMessage,
|
|
792
|
+
channel: "mattermost",
|
|
793
|
+
target: params.channelId,
|
|
794
|
+
error
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
} },
|
|
798
|
+
replyOptions: { disableBlockStreaming: typeof monitor.account.blockStreaming === "boolean" ? !monitor.account.blockStreaming : void 0 }
|
|
799
|
+
};
|
|
800
|
+
}
|
|
1258
801
|
};
|
|
1259
802
|
}
|
|
1260
|
-
async function registerMattermostMonitorSlashCommands(params) {
|
|
1261
|
-
const commandsRaw = params.account.config.commands;
|
|
1262
|
-
const slashConfig = resolveSlashCommandConfig(commandsRaw);
|
|
1263
|
-
if (!isSlashCommandsEnabled(slashConfig)) return;
|
|
1264
|
-
try {
|
|
1265
|
-
const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
|
|
1266
|
-
const slashCallbackUrl = resolveCallbackUrl({
|
|
1267
|
-
config: slashConfig,
|
|
1268
|
-
gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
|
|
1269
|
-
gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
|
|
1270
|
-
});
|
|
1271
|
-
warnOnSuspiciousCallbackUrl({
|
|
1272
|
-
runtime: params.runtime,
|
|
1273
|
-
baseUrl: params.baseUrl,
|
|
1274
|
-
callbackUrl: slashCallbackUrl
|
|
1275
|
-
});
|
|
1276
|
-
const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
|
|
1277
|
-
cfg: params.cfg,
|
|
1278
|
-
runtime: params.runtime,
|
|
1279
|
-
nativeSkills: slashConfig.nativeSkills === true
|
|
1280
|
-
}));
|
|
1281
|
-
const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
|
|
1282
|
-
client: params.client,
|
|
1283
|
-
teams,
|
|
1284
|
-
botUserId: params.botUserId,
|
|
1285
|
-
callbackUrl: slashCallbackUrl,
|
|
1286
|
-
commands: dedupedCommands,
|
|
1287
|
-
runtime: params.runtime
|
|
1288
|
-
});
|
|
1289
|
-
if (registered.length === 0) {
|
|
1290
|
-
params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
|
|
1291
|
-
return;
|
|
1292
|
-
}
|
|
1293
|
-
if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
|
|
1294
|
-
activateSlashCommands({
|
|
1295
|
-
account: params.account,
|
|
1296
|
-
commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
|
|
1297
|
-
registeredCommands: registered,
|
|
1298
|
-
triggerMap: buildTriggerMap(dedupedCommands),
|
|
1299
|
-
api: {
|
|
1300
|
-
cfg: params.cfg,
|
|
1301
|
-
runtime: params.runtime
|
|
1302
|
-
},
|
|
1303
|
-
log: (msg) => params.runtime.log?.(msg)
|
|
1304
|
-
});
|
|
1305
|
-
params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
|
|
1306
|
-
} catch (err) {
|
|
1307
|
-
params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
//#endregion
|
|
1311
|
-
//#region extensions/mattermost/src/mattermost/reconnect.ts
|
|
1312
|
-
/**
|
|
1313
|
-
* Reconnection loop with exponential backoff.
|
|
1314
|
-
*
|
|
1315
|
-
* Calls `connectFn` in a while loop. On normal resolve (connection closed),
|
|
1316
|
-
* the backoff resets. On thrown error (connection failed), the current delay is
|
|
1317
|
-
* used, then doubled for the next retry.
|
|
1318
|
-
* The loop exits when `abortSignal` fires.
|
|
1319
|
-
*/
|
|
1320
|
-
async function runWithReconnect(connectFn, opts = {}) {
|
|
1321
|
-
const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
|
|
1322
|
-
const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
|
|
1323
|
-
const random = opts.random ?? Math.random;
|
|
1324
|
-
const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
|
|
1325
|
-
let attempt = 0;
|
|
1326
|
-
while (!opts.abortSignal?.aborted) {
|
|
1327
|
-
let outcome = "resolved";
|
|
1328
|
-
let error;
|
|
1329
|
-
try {
|
|
1330
|
-
await connectFn();
|
|
1331
|
-
backoff.reset();
|
|
1332
|
-
} catch (err) {
|
|
1333
|
-
if (opts.abortSignal?.aborted) return;
|
|
1334
|
-
outcome = "rejected";
|
|
1335
|
-
error = err;
|
|
1336
|
-
opts.onError?.(err);
|
|
1337
|
-
}
|
|
1338
|
-
if (opts.abortSignal?.aborted) return;
|
|
1339
|
-
const delayMs = withJitter(backoff.current(), jitterRatio, random);
|
|
1340
|
-
if (!(opts.shouldReconnect?.({
|
|
1341
|
-
attempt,
|
|
1342
|
-
delayMs,
|
|
1343
|
-
outcome,
|
|
1344
|
-
error
|
|
1345
|
-
}) ?? true)) return;
|
|
1346
|
-
opts.onReconnect?.(delayMs);
|
|
1347
|
-
await sleepAbortable(delayMs, opts.abortSignal);
|
|
1348
|
-
if (outcome === "rejected") backoff.increase();
|
|
1349
|
-
attempt++;
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
function createReconnectBackoff(initialDelayMs, maxDelayMs) {
|
|
1353
|
-
let retryDelay = initialDelayMs;
|
|
1354
|
-
return {
|
|
1355
|
-
current: () => retryDelay,
|
|
1356
|
-
reset: () => {
|
|
1357
|
-
retryDelay = initialDelayMs;
|
|
1358
|
-
},
|
|
1359
|
-
increase: () => {
|
|
1360
|
-
retryDelay = Math.min(retryDelay * 2, maxDelayMs);
|
|
1361
|
-
}
|
|
1362
|
-
};
|
|
1363
|
-
}
|
|
1364
|
-
function withJitter(baseMs, jitterRatio, random) {
|
|
1365
|
-
if (jitterRatio <= 0) return baseMs;
|
|
1366
|
-
const normalized = Math.max(0, Math.min(1, random()));
|
|
1367
|
-
const spread = baseMs * jitterRatio;
|
|
1368
|
-
return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
|
|
1369
|
-
}
|
|
1370
|
-
function sleepAbortable(ms, signal) {
|
|
1371
|
-
return new Promise((resolve) => {
|
|
1372
|
-
if (signal?.aborted) {
|
|
1373
|
-
resolve();
|
|
1374
|
-
return;
|
|
1375
|
-
}
|
|
1376
|
-
const onAbort = () => {
|
|
1377
|
-
clearTimeout(timer);
|
|
1378
|
-
resolve();
|
|
1379
|
-
};
|
|
1380
|
-
const timer = setTimeout(() => {
|
|
1381
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1382
|
-
resolve();
|
|
1383
|
-
}, ms);
|
|
1384
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1385
|
-
});
|
|
1386
|
-
}
|
|
1387
|
-
//#endregion
|
|
1388
|
-
//#region extensions/mattermost/src/mattermost/thread-participation.ts
|
|
1389
|
-
const threadParticipation = createPersistentDedupeCache({
|
|
1390
|
-
globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
|
|
1391
|
-
ttlMs: 10080 * 60 * 1e3,
|
|
1392
|
-
maxSize: 5e3,
|
|
1393
|
-
persistent: {
|
|
1394
|
-
namespace: "mattermost.thread-participation",
|
|
1395
|
-
maxEntries: 1e3,
|
|
1396
|
-
openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
|
|
1397
|
-
logError: (error) => {
|
|
1398
|
-
try {
|
|
1399
|
-
getOptionalMattermostRuntime()?.logging.getChildLogger({
|
|
1400
|
-
plugin: "mattermost",
|
|
1401
|
-
feature: "thread-participation-state"
|
|
1402
|
-
}).warn("Mattermost persistent thread participation state failed", { error: String(error) });
|
|
1403
|
-
} catch {}
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
});
|
|
1407
|
-
function makeKey(accountId, channelId, threadRootId) {
|
|
1408
|
-
return `${accountId}:${channelId}:${threadRootId}`;
|
|
1409
|
-
}
|
|
1410
|
-
function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
|
|
1411
|
-
if (!accountId || !channelId || !threadRootId) return;
|
|
1412
|
-
threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
|
|
1413
|
-
...opts?.agentId ? { agentId: opts.agentId } : {},
|
|
1414
|
-
repliedAt: Date.now()
|
|
1415
|
-
});
|
|
1416
|
-
}
|
|
1417
|
-
async function hasMattermostThreadParticipationWithPersistence(params) {
|
|
1418
|
-
if (!params.accountId || !params.channelId || !params.threadRootId) return false;
|
|
1419
|
-
return await threadParticipation.lookup(makeKey(params.accountId, params.channelId, params.threadRootId));
|
|
1420
|
-
}
|
|
1421
803
|
//#endregion
|
|
1422
|
-
//#region extensions/mattermost/src/mattermost/monitor.ts
|
|
1423
|
-
function
|
|
1424
|
-
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
return
|
|
1428
|
-
|
|
1429
|
-
error: console.error,
|
|
1430
|
-
exit: (code) => {
|
|
1431
|
-
throw new Error(`exit ${code}`);
|
|
1432
|
-
}
|
|
1433
|
-
};
|
|
1434
|
-
}
|
|
1435
|
-
function isSystemPost(post) {
|
|
1436
|
-
return normalizeOptionalString(post.type) !== void 0;
|
|
1437
|
-
}
|
|
1438
|
-
function channelChatType(kind) {
|
|
1439
|
-
if (kind === "direct") return "direct";
|
|
1440
|
-
if (kind === "group") return "group";
|
|
1441
|
-
return "channel";
|
|
1442
|
-
}
|
|
1443
|
-
function createDisabledMattermostDraftStream() {
|
|
1444
|
-
const noopAsync = async () => {};
|
|
1445
|
-
return {
|
|
1446
|
-
update: () => {},
|
|
1447
|
-
updateAssistantText: () => {},
|
|
1448
|
-
flush: noopAsync,
|
|
1449
|
-
postId: () => void 0,
|
|
1450
|
-
clear: noopAsync,
|
|
1451
|
-
discardPending: noopAsync,
|
|
1452
|
-
seal: noopAsync,
|
|
1453
|
-
stop: noopAsync,
|
|
1454
|
-
forceNewMessage: noopAsync,
|
|
1455
|
-
settleBoundaries: noopAsync,
|
|
1456
|
-
resolveFinalText: (text) => ({
|
|
1457
|
-
kind: "full",
|
|
1458
|
-
text
|
|
1459
|
-
})
|
|
1460
|
-
};
|
|
1461
|
-
}
|
|
1462
|
-
function buildMattermostWsUrl(baseUrl) {
|
|
1463
|
-
const normalized = normalizeMattermostBaseUrl(baseUrl);
|
|
1464
|
-
if (!normalized) throw new Error("Mattermost baseUrl is required");
|
|
1465
|
-
return `${normalized.replace(/^http/i, "ws")}/api/v4/websocket`;
|
|
1466
|
-
}
|
|
1467
|
-
async function monitorMattermostProvider(opts = {}) {
|
|
1468
|
-
const core = getMattermostRuntime();
|
|
1469
|
-
const runtime = resolveRuntime(opts);
|
|
1470
|
-
const cfg = opts.config ?? core.config.current();
|
|
1471
|
-
const account = resolveMattermostAccount({
|
|
1472
|
-
cfg,
|
|
1473
|
-
accountId: opts.accountId
|
|
1474
|
-
});
|
|
1475
|
-
const pairing = createChannelPairingController({
|
|
1476
|
-
core,
|
|
1477
|
-
channel: "mattermost",
|
|
1478
|
-
accountId: account.accountId
|
|
1479
|
-
});
|
|
1480
|
-
const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
|
|
1481
|
-
if (!botToken) throw new Error(`Mattermost bot token missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.botToken or MATTERMOST_BOT_TOKEN for default).`);
|
|
1482
|
-
const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
|
|
1483
|
-
if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
|
|
1484
|
-
const client = createMattermostClient({
|
|
1485
|
-
baseUrl,
|
|
1486
|
-
botToken,
|
|
1487
|
-
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
|
|
1488
|
-
});
|
|
1489
|
-
let botUser;
|
|
1490
|
-
await runWithReconnect(async () => {
|
|
1491
|
-
botUser = await fetchMattermostMe(client);
|
|
1492
|
-
}, {
|
|
1493
|
-
abortSignal: opts.abortSignal,
|
|
1494
|
-
jitterRatio: .2,
|
|
1495
|
-
shouldReconnect: ({ outcome }) => outcome === "rejected",
|
|
1496
|
-
onError: (err) => {
|
|
1497
|
-
runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
|
|
1498
|
-
opts.statusSink?.({
|
|
1499
|
-
lastError: String(err),
|
|
1500
|
-
connected: false
|
|
1501
|
-
});
|
|
1502
|
-
},
|
|
1503
|
-
onReconnect: (delayMs) => {
|
|
1504
|
-
runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
|
|
1505
|
-
}
|
|
1506
|
-
});
|
|
1507
|
-
if (opts.abortSignal?.aborted) return;
|
|
1508
|
-
const botUserId = botUser.id;
|
|
1509
|
-
const botUsername = normalizeOptionalString(botUser.username);
|
|
1510
|
-
runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
|
|
1511
|
-
await registerMattermostMonitorSlashCommands({
|
|
1512
|
-
client,
|
|
1513
|
-
cfg,
|
|
1514
|
-
runtime,
|
|
1515
|
-
account,
|
|
1516
|
-
baseUrl,
|
|
1517
|
-
botUserId
|
|
1518
|
-
});
|
|
1519
|
-
const slashEnabled = getSlashCommandState(account.accountId) != null;
|
|
1520
|
-
setInteractionSecret(account.accountId, botToken);
|
|
1521
|
-
const interactionPath = resolveInteractionCallbackPath(account.accountId);
|
|
1522
|
-
const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
|
|
1523
|
-
gateway: cfg.gateway,
|
|
1524
|
-
interactions: account.config.interactions
|
|
1525
|
-
});
|
|
1526
|
-
setInteractionCallbackUrl(account.accountId, callbackUrl);
|
|
1527
|
-
const allowedInteractionSourceIps = normalizeInteractionSourceIps(account.config.interactions?.allowedSourceIps);
|
|
1528
|
-
try {
|
|
1529
|
-
const mmHost = new URL(baseUrl).hostname;
|
|
1530
|
-
const callbackHost = new URL(callbackUrl).hostname;
|
|
1531
|
-
if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} (loopback) while baseUrl is ${baseUrl}. This MAY be unreachable depending on your deployment. If button clicks don't work, set channels.mattermost.interactions.callbackBaseUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
|
|
1532
|
-
if (!isLoopbackHost(callbackHost) && allowedInteractionSourceIps.length === 0) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} without channels.mattermost.interactions.allowedSourceIps. For safety, non-loopback callback sources will be rejected until you allowlist the Mattermost server or trusted ingress IPs.`);
|
|
1533
|
-
} catch {}
|
|
1534
|
-
const effectiveInteractionSourceIps = allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"];
|
|
1535
|
-
const unregisterInteractions = registerPluginHttpRoute({
|
|
1536
|
-
path: interactionPath,
|
|
804
|
+
//#region extensions/mattermost/src/mattermost/monitor-interactions.ts
|
|
805
|
+
function registerMattermostInteractions(params) {
|
|
806
|
+
const { monitor } = params;
|
|
807
|
+
const { account, botUserId, cfg, client, core, pairing, resources, runtime } = monitor;
|
|
808
|
+
const { resolveChannelInfo } = resources;
|
|
809
|
+
return registerPluginHttpRoute({
|
|
810
|
+
path: params.interactionPath,
|
|
1537
811
|
fallbackPath: "/mattermost/interactions/default",
|
|
1538
812
|
auth: "plugin",
|
|
1539
813
|
handler: createMattermostInteractionHandler({
|
|
1540
814
|
client,
|
|
1541
815
|
botUserId,
|
|
1542
816
|
accountId: account.accountId,
|
|
1543
|
-
allowedSourceIps:
|
|
817
|
+
allowedSourceIps: params.allowedSourceIps,
|
|
1544
818
|
trustedProxies: cfg.gateway?.trustedProxies,
|
|
1545
819
|
allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
|
|
1546
|
-
handleInteraction: handleModelPickerInteraction,
|
|
820
|
+
handleInteraction: params.handleModelPickerInteraction,
|
|
1547
821
|
authorizeButtonClick: async ({ payload, post }) => {
|
|
1548
822
|
const channelInfo = await resolveChannelInfo(payload.channel_id);
|
|
1549
823
|
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
|
|
@@ -1574,128 +848,53 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
1574
848
|
};
|
|
1575
849
|
},
|
|
1576
850
|
resolveSessionKey: async ({ channelId, userId, post }) => {
|
|
1577
|
-
const
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
const teamId = channelInfo?.team_id ?? void 0;
|
|
1584
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
1585
|
-
cfg,
|
|
1586
|
-
channel: "mattermost",
|
|
1587
|
-
accountId: account.accountId,
|
|
1588
|
-
teamId,
|
|
1589
|
-
peer: {
|
|
1590
|
-
kind,
|
|
1591
|
-
id: kind === "direct" ? userId : channelId
|
|
1592
|
-
}
|
|
851
|
+
const eventPlan = await buildMattermostEventPlan(monitor, {
|
|
852
|
+
channelId,
|
|
853
|
+
senderId: userId,
|
|
854
|
+
postId: post.id,
|
|
855
|
+
threadRootId: post.root_id,
|
|
856
|
+
dropLabel: "interaction session event"
|
|
1593
857
|
});
|
|
1594
|
-
|
|
1595
|
-
return
|
|
1596
|
-
baseSessionKey: route.sessionKey,
|
|
1597
|
-
kind,
|
|
1598
|
-
postId: post.id || void 0,
|
|
1599
|
-
replyToMode,
|
|
1600
|
-
threadRootId: post.root_id
|
|
1601
|
-
}).sessionKey;
|
|
858
|
+
if (!eventPlan) throw new Error("Mattermost channel type could not be resolved");
|
|
859
|
+
return eventPlan.thread.sessionKey;
|
|
1602
860
|
},
|
|
1603
|
-
dispatchButtonClick: async (
|
|
1604
|
-
const
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
const chatType = channelChatType(kind);
|
|
1611
|
-
const teamId = channelInfo?.team_id ?? void 0;
|
|
1612
|
-
const channelName = channelInfo?.name ?? void 0;
|
|
1613
|
-
const channelDisplay = channelInfo?.display_name ?? channelName ?? optsLocal.channelId;
|
|
1614
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
1615
|
-
cfg,
|
|
1616
|
-
channel: "mattermost",
|
|
1617
|
-
accountId: account.accountId,
|
|
1618
|
-
teamId,
|
|
1619
|
-
peer: {
|
|
1620
|
-
kind,
|
|
1621
|
-
id: kind === "direct" ? optsLocal.userId : optsLocal.channelId
|
|
1622
|
-
}
|
|
1623
|
-
});
|
|
1624
|
-
const replyToMode = resolveMattermostReplyToMode(account, kind);
|
|
1625
|
-
const threadContext = resolveMattermostThreadSessionContext({
|
|
1626
|
-
baseSessionKey: route.sessionKey,
|
|
1627
|
-
kind,
|
|
1628
|
-
postId: optsLocal.post.id || optsLocal.postId,
|
|
1629
|
-
replyToMode,
|
|
1630
|
-
threadRootId: optsLocal.post.root_id
|
|
861
|
+
dispatchButtonClick: async (button) => {
|
|
862
|
+
const eventPlan = await buildMattermostEventPlan(monitor, {
|
|
863
|
+
channelId: button.channelId,
|
|
864
|
+
senderId: button.userId,
|
|
865
|
+
postId: button.post.id || button.postId,
|
|
866
|
+
threadRootId: button.post.root_id,
|
|
867
|
+
dropLabel: "interaction dispatch"
|
|
1631
868
|
});
|
|
1632
|
-
|
|
1633
|
-
const
|
|
1634
|
-
const
|
|
869
|
+
if (!eventPlan) return;
|
|
870
|
+
const { channelDisplay, kind, route, thread, to } = eventPlan;
|
|
871
|
+
const bodyText = `[Button click: user @${button.userName} selected "${button.actionName}"]`;
|
|
872
|
+
const ctxPayload = eventPlan.finalizeContext({
|
|
1635
873
|
Body: bodyText,
|
|
1636
874
|
BodyForAgent: bodyText,
|
|
1637
875
|
RawBody: bodyText,
|
|
1638
876
|
CommandBody: bodyText,
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
ParentSessionKey: threadContext.parentSessionKey,
|
|
1644
|
-
AccountId: route.accountId,
|
|
1645
|
-
ChatType: chatType,
|
|
1646
|
-
ConversationLabel: `mattermost:${optsLocal.userName}`,
|
|
1647
|
-
GroupSubject: kind !== "direct" ? channelDisplay : void 0,
|
|
1648
|
-
GroupChannel: channelName ? `#${channelName}` : void 0,
|
|
1649
|
-
GroupSpace: teamId,
|
|
1650
|
-
SenderName: optsLocal.userName,
|
|
1651
|
-
SenderId: optsLocal.userId,
|
|
1652
|
-
Provider: "mattermost",
|
|
1653
|
-
Surface: "mattermost",
|
|
1654
|
-
MessageSid: `interaction:${optsLocal.postId}:${optsLocal.actionId}`,
|
|
1655
|
-
ReplyToId: threadContext.effectiveReplyToId,
|
|
1656
|
-
MessageThreadId: threadContext.effectiveReplyToId,
|
|
877
|
+
ConversationLabel: `mattermost:${button.userName}`,
|
|
878
|
+
GroupSubject: kind !== "direct" ? channelDisplay || button.channelId : void 0,
|
|
879
|
+
SenderName: button.userName,
|
|
880
|
+
MessageSid: `interaction:${button.postId}:${button.actionId}`,
|
|
1657
881
|
WasMentioned: true,
|
|
1658
|
-
CommandAuthorized: false
|
|
1659
|
-
OriginatingChannel: "mattermost",
|
|
1660
|
-
OriginatingTo: to
|
|
882
|
+
CommandAuthorized: false
|
|
1661
883
|
});
|
|
1662
|
-
const
|
|
1663
|
-
|
|
884
|
+
const { deliveryBarrier, replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
|
|
885
|
+
await core.channel.inbound.dispatch({
|
|
1664
886
|
cfg,
|
|
1665
887
|
channel: "mattermost",
|
|
1666
|
-
accountId: account.accountId
|
|
1667
|
-
});
|
|
1668
|
-
const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
|
|
1669
|
-
cfg,
|
|
1670
|
-
agentId: route.agentId,
|
|
1671
|
-
channel: "mattermost",
|
|
1672
888
|
accountId: account.accountId,
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
error: err
|
|
1681
|
-
});
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
});
|
|
1685
|
-
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
|
|
1686
|
-
isDirect: kind === "direct",
|
|
1687
|
-
dmRetryOptions: account.config.dmChannelRetry
|
|
1688
|
-
});
|
|
1689
|
-
await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
|
|
1690
|
-
ctx: ctxPayload,
|
|
1691
|
-
cfg,
|
|
1692
|
-
dispatcherOptions: {
|
|
1693
|
-
...replyPipeline,
|
|
1694
|
-
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
|
|
1695
|
-
onDeliverySettled: deliveryBarrier.markDeliverySettled,
|
|
1696
|
-
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
|
|
889
|
+
route: {
|
|
890
|
+
agentId: route.agentId,
|
|
891
|
+
dmScope: route.dmScope,
|
|
892
|
+
sessionKey: thread.sessionKey
|
|
893
|
+
},
|
|
894
|
+
ctxPayload,
|
|
895
|
+
delivery: {
|
|
1697
896
|
deliver: async (payload) => {
|
|
1698
|
-
await deliverMattermostReplyPayload({
|
|
897
|
+
const result = toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
|
|
1699
898
|
core,
|
|
1700
899
|
cfg,
|
|
1701
900
|
payload,
|
|
@@ -1704,369 +903,1066 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
1704
903
|
agentId: route.agentId,
|
|
1705
904
|
replyToId: resolveMattermostReplyRootId({
|
|
1706
905
|
kind,
|
|
1707
|
-
threadRootId:
|
|
906
|
+
threadRootId: thread.effectiveReplyToId,
|
|
1708
907
|
replyToId: payload.replyToId
|
|
1709
908
|
}),
|
|
1710
909
|
textLimit,
|
|
1711
910
|
tableMode,
|
|
1712
911
|
sendMessage: sendMessageMattermost,
|
|
1713
912
|
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
1714
|
-
});
|
|
1715
|
-
runtime.log?.(`delivered button-click reply to ${to}`);
|
|
913
|
+
}));
|
|
914
|
+
if (result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
|
|
915
|
+
return result;
|
|
1716
916
|
},
|
|
1717
917
|
onError: (err, info) => {
|
|
1718
918
|
runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
|
|
1719
|
-
}
|
|
1720
|
-
typingCallbacks
|
|
919
|
+
}
|
|
1721
920
|
},
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
921
|
+
replyPipeline,
|
|
922
|
+
dispatcherOptions: {
|
|
923
|
+
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
|
|
924
|
+
onDeliverySettled: deliveryBarrier.markDeliverySettled,
|
|
925
|
+
humanDelay: resolveHumanDelayConfig(cfg, route.agentId)
|
|
926
|
+
},
|
|
927
|
+
replyOptions
|
|
1726
928
|
});
|
|
1727
929
|
},
|
|
1728
|
-
log: (
|
|
930
|
+
log: (message) => runtime.log?.(message)
|
|
931
|
+
}),
|
|
932
|
+
pluginId: "mattermost",
|
|
933
|
+
source: "mattermost-interactions",
|
|
934
|
+
accountId: account.accountId,
|
|
935
|
+
log: (message) => runtime.log?.(message)
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region extensions/mattermost/src/mattermost/monitor-model-picker.ts
|
|
940
|
+
function createMattermostModelPickerInteractionHandler(monitor) {
|
|
941
|
+
const { account, cfg, core, pairing, resources, runtime } = monitor;
|
|
942
|
+
const { resolveChannelInfo, updateModelPickerPost } = resources;
|
|
943
|
+
const runModelPickerCommand = async (params) => {
|
|
944
|
+
const { channelDisplay, kind, roomLabel, route, thread, to } = params.eventPlan;
|
|
945
|
+
const fromLabel = kind === "direct" ? `Mattermost DM from ${params.senderName}` : `Mattermost message in ${roomLabel} from ${params.senderName}`;
|
|
946
|
+
const ctxPayload = params.eventPlan.finalizeContext({
|
|
947
|
+
Body: params.commandText,
|
|
948
|
+
BodyForAgent: params.commandText,
|
|
949
|
+
RawBody: params.commandText,
|
|
950
|
+
CommandBody: params.commandText,
|
|
951
|
+
ConversationLabel: fromLabel,
|
|
952
|
+
GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
|
|
953
|
+
SenderName: params.senderName,
|
|
954
|
+
MessageSid: params.messageSid,
|
|
955
|
+
Timestamp: Date.now(),
|
|
956
|
+
WasMentioned: true,
|
|
957
|
+
CommandAuthorized: params.commandAuthorized,
|
|
958
|
+
CommandSource: "native"
|
|
959
|
+
});
|
|
960
|
+
const { deliveryBarrier, replyOptions, replyPipeline, tableMode, textLimit } = params.eventPlan.createReplyPlan();
|
|
961
|
+
await core.channel.inbound.dispatch({
|
|
962
|
+
cfg,
|
|
963
|
+
channel: "mattermost",
|
|
964
|
+
accountId: account.accountId,
|
|
965
|
+
route: {
|
|
966
|
+
agentId: route.agentId,
|
|
967
|
+
dmScope: route.dmScope,
|
|
968
|
+
sessionKey: thread.sessionKey
|
|
969
|
+
},
|
|
970
|
+
ctxPayload,
|
|
971
|
+
delivery: {
|
|
972
|
+
deliver: async (payload) => {
|
|
973
|
+
const trimmedPayload = {
|
|
974
|
+
...payload,
|
|
975
|
+
text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
|
|
976
|
+
};
|
|
977
|
+
return toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
|
|
978
|
+
core,
|
|
979
|
+
cfg,
|
|
980
|
+
payload: trimmedPayload,
|
|
981
|
+
to,
|
|
982
|
+
accountId: account.accountId,
|
|
983
|
+
agentId: route.agentId,
|
|
984
|
+
replyToId: resolveMattermostReplyRootId({
|
|
985
|
+
kind,
|
|
986
|
+
threadRootId: thread.effectiveReplyToId,
|
|
987
|
+
replyToId: trimmedPayload.replyToId
|
|
988
|
+
}),
|
|
989
|
+
textLimit,
|
|
990
|
+
tableMode: "off",
|
|
991
|
+
sendMessage: sendMessageMattermost,
|
|
992
|
+
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
993
|
+
}));
|
|
994
|
+
},
|
|
995
|
+
onError: (err, info) => {
|
|
996
|
+
runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
|
|
997
|
+
}
|
|
998
|
+
},
|
|
999
|
+
replyPipeline,
|
|
1000
|
+
dispatcherOptions: {
|
|
1001
|
+
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
|
|
1002
|
+
onDeliverySettled: deliveryBarrier.markDeliverySettled
|
|
1003
|
+
},
|
|
1004
|
+
replyOptions
|
|
1005
|
+
});
|
|
1006
|
+
};
|
|
1007
|
+
return async (params) => {
|
|
1008
|
+
const pickerState = parseMattermostModelPickerContext(params.context);
|
|
1009
|
+
if (!pickerState) return null;
|
|
1010
|
+
if (pickerState.ownerUserId !== params.payload.user_id) return { ephemeral_text: "Only the person who opened this picker can use it." };
|
|
1011
|
+
const updatePickerPost = (message, buttons) => updateModelPickerPost({
|
|
1012
|
+
channelId: params.payload.channel_id,
|
|
1013
|
+
postId: params.payload.post_id,
|
|
1014
|
+
message,
|
|
1015
|
+
buttons
|
|
1016
|
+
});
|
|
1017
|
+
const channelInfo = await resolveChannelInfo(params.payload.channel_id);
|
|
1018
|
+
const pickerCommandText = pickerState.action === "select" ? `/model ${pickerState.provider}/${pickerState.model}` : pickerState.action === "list" ? `/models ${pickerState.provider}` : "/models";
|
|
1019
|
+
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
|
|
1020
|
+
cfg,
|
|
1021
|
+
surface: "mattermost"
|
|
1022
|
+
});
|
|
1023
|
+
const auth = await authorizeMattermostCommandInvocation({
|
|
1024
|
+
account,
|
|
1025
|
+
cfg,
|
|
1026
|
+
senderId: params.payload.user_id,
|
|
1027
|
+
senderName: params.userName,
|
|
1028
|
+
channelId: params.payload.channel_id,
|
|
1029
|
+
channelInfo,
|
|
1030
|
+
readStoreAllowFrom: pairing.readAllowFromStore,
|
|
1031
|
+
allowTextCommands,
|
|
1032
|
+
hasControlCommand: core.channel.text.hasControlCommand(pickerCommandText, cfg)
|
|
1033
|
+
});
|
|
1034
|
+
if (!auth.ok) {
|
|
1035
|
+
if (auth.denyReason === "dm-pairing") {
|
|
1036
|
+
const { code } = await pairing.upsertPairingRequest({
|
|
1037
|
+
id: params.payload.user_id,
|
|
1038
|
+
meta: { name: params.userName }
|
|
1039
|
+
});
|
|
1040
|
+
return { ephemeral_text: core.channel.pairing.buildPairingReply({
|
|
1041
|
+
channel: "mattermost",
|
|
1042
|
+
idLine: `Your Mattermost user id: ${params.payload.user_id}`,
|
|
1043
|
+
code
|
|
1044
|
+
}) };
|
|
1045
|
+
}
|
|
1046
|
+
return { ephemeral_text: auth.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : auth.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : auth.denyReason === "channels-disabled" ? "Model picker actions are disabled in channels." : auth.denyReason === "channel-no-allowlist" ? "Model picker actions are not configured for this channel." : "Unauthorized." };
|
|
1047
|
+
}
|
|
1048
|
+
const teamId = auth.channelInfo.team_id ?? params.payload.team_id ?? void 0;
|
|
1049
|
+
const eventPlan = await buildMattermostEventPlan(monitor, {
|
|
1050
|
+
channelId: params.payload.channel_id,
|
|
1051
|
+
senderId: params.payload.user_id,
|
|
1052
|
+
postId: params.post.id || params.payload.post_id,
|
|
1053
|
+
threadRootId: params.post.root_id,
|
|
1054
|
+
channelInfo: auth.channelInfo,
|
|
1055
|
+
teamId,
|
|
1056
|
+
channelName: auth.channelName,
|
|
1057
|
+
channelDisplay: auth.channelDisplay,
|
|
1058
|
+
dropLabel: "model picker event"
|
|
1059
|
+
});
|
|
1060
|
+
if (!eventPlan) return { ephemeral_text: "Temporary error: unable to determine channel type. Please try again." };
|
|
1061
|
+
const modelSessionRoute = {
|
|
1062
|
+
agentId: eventPlan.route.agentId,
|
|
1063
|
+
sessionKey: eventPlan.thread.sessionKey
|
|
1064
|
+
};
|
|
1065
|
+
const data = await buildModelsProviderData(cfg, eventPlan.route.agentId);
|
|
1066
|
+
if (data.providers.length === 0) return await updatePickerPost("No models available.");
|
|
1067
|
+
if (pickerState.action === "providers" || pickerState.action === "back") {
|
|
1068
|
+
const currentModel = resolveMattermostModelPickerCurrentModel({
|
|
1069
|
+
cfg,
|
|
1070
|
+
route: modelSessionRoute,
|
|
1071
|
+
data
|
|
1072
|
+
});
|
|
1073
|
+
const view = renderMattermostProviderPickerView({
|
|
1074
|
+
ownerUserId: pickerState.ownerUserId,
|
|
1075
|
+
data,
|
|
1076
|
+
currentModel
|
|
1077
|
+
});
|
|
1078
|
+
return await updatePickerPost(view.text, view.buttons);
|
|
1079
|
+
}
|
|
1080
|
+
if (pickerState.action === "list") {
|
|
1081
|
+
const currentModel = resolveMattermostModelPickerCurrentModel({
|
|
1082
|
+
cfg,
|
|
1083
|
+
route: modelSessionRoute,
|
|
1084
|
+
data
|
|
1085
|
+
});
|
|
1086
|
+
const view = renderMattermostModelsPickerView({
|
|
1087
|
+
ownerUserId: pickerState.ownerUserId,
|
|
1088
|
+
data,
|
|
1089
|
+
provider: pickerState.provider,
|
|
1090
|
+
page: pickerState.page,
|
|
1091
|
+
currentModel
|
|
1092
|
+
});
|
|
1093
|
+
return await updatePickerPost(view.text, view.buttons);
|
|
1094
|
+
}
|
|
1095
|
+
const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
|
|
1096
|
+
if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
|
|
1097
|
+
(async () => {
|
|
1098
|
+
try {
|
|
1099
|
+
await runModelPickerCommand({
|
|
1100
|
+
commandText: `/model ${targetModelRef}`,
|
|
1101
|
+
commandAuthorized: auth.commandAuthorized,
|
|
1102
|
+
eventPlan,
|
|
1103
|
+
senderName: params.userName,
|
|
1104
|
+
messageSid: buildMattermostModelPickerSelectMessageSid({
|
|
1105
|
+
postId: params.payload.post_id,
|
|
1106
|
+
provider: pickerState.provider,
|
|
1107
|
+
model: pickerState.model
|
|
1108
|
+
})
|
|
1109
|
+
});
|
|
1110
|
+
const currentModel = resolveMattermostModelPickerCurrentModel({
|
|
1111
|
+
cfg,
|
|
1112
|
+
route: modelSessionRoute,
|
|
1113
|
+
data,
|
|
1114
|
+
readConsistency: "latest"
|
|
1115
|
+
});
|
|
1116
|
+
const view = renderMattermostModelsPickerView({
|
|
1117
|
+
ownerUserId: pickerState.ownerUserId,
|
|
1118
|
+
data,
|
|
1119
|
+
provider: pickerState.provider,
|
|
1120
|
+
page: pickerState.page,
|
|
1121
|
+
currentModel
|
|
1122
|
+
});
|
|
1123
|
+
await updatePickerPost(view.text, view.buttons);
|
|
1124
|
+
} catch (err) {
|
|
1125
|
+
runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
|
|
1126
|
+
}
|
|
1127
|
+
})();
|
|
1128
|
+
return {};
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
//#endregion
|
|
1132
|
+
//#region extensions/mattermost/src/mattermost/monitor-activation.ts
|
|
1133
|
+
function resolveMattermostInboundMentionDecision(params) {
|
|
1134
|
+
const implicitMentions = resolveChannelImplicitMentions({
|
|
1135
|
+
cfg: params.cfg,
|
|
1136
|
+
channel: "mattermost",
|
|
1137
|
+
accountId: params.accountId
|
|
1138
|
+
});
|
|
1139
|
+
return resolveInboundMentionDecision({
|
|
1140
|
+
facts: {
|
|
1141
|
+
canDetectMention: params.canDetectMention,
|
|
1142
|
+
wasMentioned: params.wasMentioned,
|
|
1143
|
+
implicitMentionKinds: params.implicitMentionKinds
|
|
1144
|
+
},
|
|
1145
|
+
policy: {
|
|
1146
|
+
isGroup: params.kind !== "direct",
|
|
1147
|
+
requireMention: params.requireMention,
|
|
1148
|
+
implicitMentions,
|
|
1149
|
+
allowTextCommands: params.allowTextCommands,
|
|
1150
|
+
hasControlCommand: params.hasControlCommand,
|
|
1151
|
+
commandAuthorized: params.commandAuthorized
|
|
1152
|
+
}
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region extensions/mattermost/src/mattermost/monitor-onchar.ts
|
|
1157
|
+
const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
|
|
1158
|
+
function resolveOncharPrefixes(prefixes) {
|
|
1159
|
+
const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
|
|
1160
|
+
return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
|
|
1161
|
+
}
|
|
1162
|
+
function stripOncharPrefix(text, prefixes) {
|
|
1163
|
+
const trimmed = text.trimStart();
|
|
1164
|
+
for (const prefix of prefixes) {
|
|
1165
|
+
if (!prefix) continue;
|
|
1166
|
+
if (trimmed.startsWith(prefix)) return {
|
|
1167
|
+
triggered: true,
|
|
1168
|
+
stripped: trimmed.slice(prefix.length).trimStart()
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
triggered: false,
|
|
1173
|
+
stripped: text
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
//#endregion
|
|
1177
|
+
//#region extensions/mattermost/src/mattermost/monitor-resources.ts
|
|
1178
|
+
function buildMattermostInboundMediaPayload(media) {
|
|
1179
|
+
return buildChannelInboundMediaPayload(toInboundMediaFacts(media));
|
|
1180
|
+
}
|
|
1181
|
+
function formatMattermostPendingMediaText(params) {
|
|
1182
|
+
return [params.body, formatMediaPlaceholderText(params.media)].filter(Boolean).join("\n").trim();
|
|
1183
|
+
}
|
|
1184
|
+
function formatMattermostInboundMediaText(params) {
|
|
1185
|
+
const materializedCount = params.materializedMedia.filter((media) => Boolean(media.path) || Boolean(media.url)).length;
|
|
1186
|
+
const unavailableCount = Math.max(0, params.nativeMedia.length - materializedCount);
|
|
1187
|
+
if (unavailableCount === 0) return params.body;
|
|
1188
|
+
return formatInboundMediaUnavailableText({
|
|
1189
|
+
body: params.body,
|
|
1190
|
+
notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
|
|
1194
|
+
const USER_CACHE_TTL_MS = 10 * 6e4;
|
|
1195
|
+
const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1e3;
|
|
1196
|
+
const MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
|
|
1197
|
+
const MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
|
|
1198
|
+
function createMattermostMonitorResources(params) {
|
|
1199
|
+
const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
|
|
1200
|
+
const channelCache = /* @__PURE__ */ new Map();
|
|
1201
|
+
const userCache = /* @__PURE__ */ new Map();
|
|
1202
|
+
const getCachedValue = (cache, key, nowMs) => {
|
|
1203
|
+
const cached = cache.get(key);
|
|
1204
|
+
if (!cached) return;
|
|
1205
|
+
if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
|
|
1206
|
+
cache.delete(key);
|
|
1207
|
+
};
|
|
1208
|
+
const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
|
|
1209
|
+
const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
|
|
1210
|
+
if (expiresAt !== void 0) {
|
|
1211
|
+
cache.delete(key);
|
|
1212
|
+
cache.set(key, {
|
|
1213
|
+
value,
|
|
1214
|
+
expiresAt
|
|
1215
|
+
});
|
|
1216
|
+
pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
const resolveMattermostMedia = async (fileIds) => {
|
|
1220
|
+
const ids = normalizeStringEntries(fileIds ?? []);
|
|
1221
|
+
if (ids.length === 0) return [];
|
|
1222
|
+
const out = [];
|
|
1223
|
+
for (const fileId of ids) {
|
|
1224
|
+
let downloadUrl;
|
|
1225
|
+
try {
|
|
1226
|
+
downloadUrl = buildMattermostApiUrl(client.baseUrl, `/files/${fileId}`);
|
|
1227
|
+
} catch (err) {
|
|
1228
|
+
logger.debug?.(`mattermost: failed to resolve file ${fileId}: ${String(err)}`);
|
|
1229
|
+
out.push({ kind: "unknown" });
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
try {
|
|
1233
|
+
const saved = await saveRemoteMedia({
|
|
1234
|
+
url: downloadUrl,
|
|
1235
|
+
requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
|
|
1236
|
+
filePathHint: fileId,
|
|
1237
|
+
maxBytes: mediaMaxBytes,
|
|
1238
|
+
ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
|
|
1239
|
+
responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
|
|
1240
|
+
readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
|
|
1241
|
+
});
|
|
1242
|
+
const contentType = saved.contentType ?? void 0;
|
|
1243
|
+
out.push({
|
|
1244
|
+
path: saved.path,
|
|
1245
|
+
contentType,
|
|
1246
|
+
kind: mediaKindFromMime(contentType) ?? "unknown"
|
|
1247
|
+
});
|
|
1248
|
+
} catch (err) {
|
|
1249
|
+
logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
|
|
1250
|
+
let contentType;
|
|
1251
|
+
try {
|
|
1252
|
+
contentType = (await client.request(`/files/${fileId}/info`)).mime_type?.trim() || void 0;
|
|
1253
|
+
} catch (infoErr) {
|
|
1254
|
+
logger.debug?.(`mattermost: failed to resolve metadata for file ${fileId}: ${String(infoErr)}`);
|
|
1255
|
+
}
|
|
1256
|
+
out.push({
|
|
1257
|
+
contentType,
|
|
1258
|
+
kind: mediaKindFromMime(contentType) ?? "unknown"
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
return out;
|
|
1263
|
+
};
|
|
1264
|
+
const sendTypingIndicator = async (channelId, parentId) => {
|
|
1265
|
+
await sendMattermostTyping(client, {
|
|
1266
|
+
channelId,
|
|
1267
|
+
parentId
|
|
1268
|
+
});
|
|
1269
|
+
};
|
|
1270
|
+
const resolveChannelInfo = async (channelId) => {
|
|
1271
|
+
const rawNow = Date.now();
|
|
1272
|
+
const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
|
|
1273
|
+
if (cached !== void 0) return cached;
|
|
1274
|
+
try {
|
|
1275
|
+
const info = await fetchMattermostChannel(client, channelId);
|
|
1276
|
+
setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
|
|
1277
|
+
return info;
|
|
1278
|
+
} catch (err) {
|
|
1279
|
+
logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
|
|
1280
|
+
setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
|
|
1281
|
+
return null;
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
const resolveUserInfo = async (userId) => {
|
|
1285
|
+
const rawNow = Date.now();
|
|
1286
|
+
const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
|
|
1287
|
+
if (cached !== void 0) return cached;
|
|
1288
|
+
try {
|
|
1289
|
+
const info = await fetchMattermostUser(client, userId);
|
|
1290
|
+
setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
|
|
1291
|
+
return info;
|
|
1292
|
+
} catch (err) {
|
|
1293
|
+
logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
|
|
1294
|
+
setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
|
|
1295
|
+
return null;
|
|
1296
|
+
}
|
|
1297
|
+
};
|
|
1298
|
+
const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
|
|
1299
|
+
callbackUrl,
|
|
1300
|
+
accountId,
|
|
1301
|
+
channelId,
|
|
1302
|
+
buttons
|
|
1303
|
+
});
|
|
1304
|
+
const updateModelPickerPost = async (paramsLocal) => {
|
|
1305
|
+
const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
|
|
1306
|
+
await updateMattermostPost(client, paramsLocal.postId, {
|
|
1307
|
+
message: paramsLocal.message,
|
|
1308
|
+
props
|
|
1309
|
+
});
|
|
1310
|
+
return {};
|
|
1311
|
+
};
|
|
1312
|
+
return {
|
|
1313
|
+
resolveMattermostMedia,
|
|
1314
|
+
sendTypingIndicator,
|
|
1315
|
+
resolveChannelInfo,
|
|
1316
|
+
resolveUserInfo,
|
|
1317
|
+
updateModelPickerPost
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
//#endregion
|
|
1321
|
+
//#region extensions/mattermost/src/mattermost/draft-stream.ts
|
|
1322
|
+
const MATTERMOST_STREAM_MAX_CHARS = 4e3;
|
|
1323
|
+
const DEFAULT_THROTTLE_MS = 1e3;
|
|
1324
|
+
function normalizeMattermostDraftText(text, maxChars) {
|
|
1325
|
+
const trimmed = text.trim();
|
|
1326
|
+
if (!trimmed) return "";
|
|
1327
|
+
if (trimmed.length <= maxChars) return trimmed;
|
|
1328
|
+
return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
|
|
1329
|
+
}
|
|
1330
|
+
function createMattermostDraftPreviewBoundaryController(params) {
|
|
1331
|
+
let hasStreamedContent = false;
|
|
1332
|
+
return {
|
|
1333
|
+
noteUpdate() {
|
|
1334
|
+
hasStreamedContent = true;
|
|
1335
|
+
},
|
|
1336
|
+
async noteBoundary() {
|
|
1337
|
+
if (!params.enabled) return;
|
|
1338
|
+
if (!hasStreamedContent) return;
|
|
1339
|
+
hasStreamedContent = false;
|
|
1340
|
+
await params.forceNewMessage();
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
function createMattermostDraftStream(params) {
|
|
1345
|
+
const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
|
|
1346
|
+
const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
|
|
1347
|
+
const streamState = {
|
|
1348
|
+
stopped: false,
|
|
1349
|
+
final: false
|
|
1350
|
+
};
|
|
1351
|
+
let currentGeneration = {
|
|
1352
|
+
lastSentText: "",
|
|
1353
|
+
latestSourceText: "",
|
|
1354
|
+
ready: Promise.resolve()
|
|
1355
|
+
};
|
|
1356
|
+
const sealedAssistantTexts = [];
|
|
1357
|
+
const sendOrEditStreamMessage = async (text) => {
|
|
1358
|
+
if (streamState.stopped && !streamState.final) return false;
|
|
1359
|
+
const target = currentGeneration;
|
|
1360
|
+
const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
|
|
1361
|
+
if (!normalized) return false;
|
|
1362
|
+
await target.ready;
|
|
1363
|
+
if (streamState.stopped && !streamState.final) return false;
|
|
1364
|
+
if (normalized === target.lastSentText) return true;
|
|
1365
|
+
try {
|
|
1366
|
+
if (target.postId) await updateMattermostPost(params.client, target.postId, { message: normalized });
|
|
1367
|
+
else {
|
|
1368
|
+
const postId = (await createMattermostPost(params.client, {
|
|
1369
|
+
channelId: params.channelId,
|
|
1370
|
+
message: normalized,
|
|
1371
|
+
rootId: params.rootId
|
|
1372
|
+
})).id?.trim();
|
|
1373
|
+
if (!postId) {
|
|
1374
|
+
streamState.stopped = true;
|
|
1375
|
+
params.warn?.("mattermost stream preview stopped (missing post id from create)");
|
|
1376
|
+
return false;
|
|
1377
|
+
}
|
|
1378
|
+
target.postId = postId;
|
|
1379
|
+
}
|
|
1380
|
+
target.lastSentText = normalized;
|
|
1381
|
+
return true;
|
|
1382
|
+
} catch (err) {
|
|
1383
|
+
streamState.stopped = true;
|
|
1384
|
+
params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1385
|
+
return false;
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
const clearMessageId = () => {
|
|
1389
|
+
currentGeneration.postId = void 0;
|
|
1390
|
+
};
|
|
1391
|
+
const isValidMessageId = (value) => typeof value === "string" && value.length > 0;
|
|
1392
|
+
const deleteMessage = async (postId) => {
|
|
1393
|
+
await deleteMattermostPost(params.client, postId);
|
|
1394
|
+
};
|
|
1395
|
+
const { loop, update: updateLifecycle, stop: stopLifecycle, stopForClear, clearWithStop, seal: sealLifecycle } = createFinalizableDraftLifecycle({
|
|
1396
|
+
throttleMs,
|
|
1397
|
+
state: streamState,
|
|
1398
|
+
sendOrEditStreamMessage,
|
|
1399
|
+
readMessageId: () => currentGeneration.postId,
|
|
1400
|
+
clearMessageId,
|
|
1401
|
+
isValidMessageId,
|
|
1402
|
+
deleteMessage,
|
|
1403
|
+
warn: params.warn,
|
|
1404
|
+
warnPrefix: "mattermost stream preview cleanup failed"
|
|
1405
|
+
});
|
|
1406
|
+
const forceNewMessage = () => {
|
|
1407
|
+
if (streamState.stopped || streamState.final) return Promise.resolve();
|
|
1408
|
+
const pendingText = loop.takePending();
|
|
1409
|
+
const inFlightAtBoundary = loop.waitForInFlight();
|
|
1410
|
+
const sealed = currentGeneration;
|
|
1411
|
+
const boundary = (async () => {
|
|
1412
|
+
try {
|
|
1413
|
+
await sealed.ready;
|
|
1414
|
+
await inFlightAtBoundary;
|
|
1415
|
+
if (streamState.stopped && !streamState.final) return;
|
|
1416
|
+
const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
|
|
1417
|
+
const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
|
|
1418
|
+
const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
|
|
1419
|
+
const firstChunk = chunks[0];
|
|
1420
|
+
if (!firstChunk) return;
|
|
1421
|
+
if (sealed.postId) {
|
|
1422
|
+
if (firstChunk !== sealed.lastSentText) await updateMattermostPost(params.client, sealed.postId, { message: firstChunk });
|
|
1423
|
+
} else await createMattermostPost(params.client, {
|
|
1424
|
+
channelId: params.channelId,
|
|
1425
|
+
message: firstChunk,
|
|
1426
|
+
rootId: params.rootId
|
|
1427
|
+
});
|
|
1428
|
+
for (const chunk of chunks.slice(1)) await createMattermostPost(params.client, {
|
|
1429
|
+
channelId: params.channelId,
|
|
1430
|
+
message: chunk,
|
|
1431
|
+
rootId: params.rootId
|
|
1432
|
+
});
|
|
1433
|
+
const assistantText = sealed.latestAssistantText?.trim();
|
|
1434
|
+
if (assistantText) sealedAssistantTexts.push(assistantText);
|
|
1435
|
+
} catch (err) {
|
|
1436
|
+
params.warn?.(`mattermost stream preview boundary flush failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1437
|
+
}
|
|
1438
|
+
})();
|
|
1439
|
+
currentGeneration = {
|
|
1440
|
+
lastSentText: "",
|
|
1441
|
+
latestSourceText: "",
|
|
1442
|
+
ready: boundary
|
|
1443
|
+
};
|
|
1444
|
+
loop.resetThrottleWindow();
|
|
1445
|
+
return boundary;
|
|
1446
|
+
};
|
|
1447
|
+
const flush = async () => {
|
|
1448
|
+
await loop.flush();
|
|
1449
|
+
await currentGeneration.ready;
|
|
1450
|
+
};
|
|
1451
|
+
const discardPending = async () => {
|
|
1452
|
+
await stopForClear();
|
|
1453
|
+
await currentGeneration.ready;
|
|
1454
|
+
};
|
|
1455
|
+
const clear = async () => {
|
|
1456
|
+
await clearWithStop(discardPending);
|
|
1457
|
+
};
|
|
1458
|
+
const seal = async () => {
|
|
1459
|
+
await sealLifecycle();
|
|
1460
|
+
await currentGeneration.ready;
|
|
1461
|
+
};
|
|
1462
|
+
const stop = async () => {
|
|
1463
|
+
await stopLifecycle();
|
|
1464
|
+
await currentGeneration.ready;
|
|
1465
|
+
};
|
|
1466
|
+
const update = (text) => {
|
|
1467
|
+
currentGeneration.latestSourceText = text;
|
|
1468
|
+
currentGeneration.latestAssistantText = void 0;
|
|
1469
|
+
updateLifecycle(text);
|
|
1470
|
+
};
|
|
1471
|
+
const updateAssistantText = (text) => {
|
|
1472
|
+
currentGeneration.latestSourceText = text;
|
|
1473
|
+
currentGeneration.latestAssistantText = text;
|
|
1474
|
+
updateLifecycle(text);
|
|
1475
|
+
};
|
|
1476
|
+
const settleBoundaries = async () => {
|
|
1477
|
+
await currentGeneration.ready;
|
|
1478
|
+
};
|
|
1479
|
+
const resolveFinalText = (text) => {
|
|
1480
|
+
if (sealedAssistantTexts.length === 0) return {
|
|
1481
|
+
kind: "full",
|
|
1482
|
+
text
|
|
1483
|
+
};
|
|
1484
|
+
let remainingText = text.trim();
|
|
1485
|
+
for (const sealedText of sealedAssistantTexts) {
|
|
1486
|
+
const completed = sealedText.trim();
|
|
1487
|
+
if (!completed || !remainingText.startsWith(completed)) return {
|
|
1488
|
+
kind: "full",
|
|
1489
|
+
text
|
|
1490
|
+
};
|
|
1491
|
+
const suffix = remainingText.slice(completed.length);
|
|
1492
|
+
if (suffix && !/^\r?\n/.test(suffix)) return {
|
|
1493
|
+
kind: "full",
|
|
1494
|
+
text
|
|
1495
|
+
};
|
|
1496
|
+
remainingText = suffix.replace(/^(?:\r?\n)+/, "");
|
|
1497
|
+
}
|
|
1498
|
+
const currentText = currentGeneration.latestAssistantText?.trim() ?? "";
|
|
1499
|
+
const remaining = remainingText.trim();
|
|
1500
|
+
if (currentText && !remaining.startsWith(currentText)) return {
|
|
1501
|
+
kind: "full",
|
|
1502
|
+
text
|
|
1503
|
+
};
|
|
1504
|
+
return remaining ? {
|
|
1505
|
+
kind: "remaining",
|
|
1506
|
+
text: remaining
|
|
1507
|
+
} : { kind: "already-delivered" };
|
|
1508
|
+
};
|
|
1509
|
+
params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
|
|
1510
|
+
return {
|
|
1511
|
+
update,
|
|
1512
|
+
updateAssistantText,
|
|
1513
|
+
flush,
|
|
1514
|
+
postId: () => currentGeneration.postId,
|
|
1515
|
+
clear,
|
|
1516
|
+
discardPending,
|
|
1517
|
+
seal,
|
|
1518
|
+
stop,
|
|
1519
|
+
forceNewMessage,
|
|
1520
|
+
settleBoundaries,
|
|
1521
|
+
resolveFinalText
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
//#endregion
|
|
1525
|
+
//#region extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
|
|
1526
|
+
async function deliverMattermostReplyWithDraftPreview(params) {
|
|
1527
|
+
if (isReasoningReplyPayload(params.payload)) return;
|
|
1528
|
+
await deliverWithFinalizableLivePreviewAdapter({
|
|
1529
|
+
kind: params.info.kind,
|
|
1530
|
+
payload: params.payload,
|
|
1531
|
+
adapter: defineFinalizableLivePreviewAdapter({
|
|
1532
|
+
draft: {
|
|
1533
|
+
flush: params.draftStream.flush,
|
|
1534
|
+
clear: params.draftStream.clear,
|
|
1535
|
+
discardPending: params.draftStream.discardPending,
|
|
1536
|
+
seal: params.draftStream.seal,
|
|
1537
|
+
id: params.draftStream.postId
|
|
1538
|
+
},
|
|
1539
|
+
buildFinalEdit: (payload) => {
|
|
1540
|
+
const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
|
|
1541
|
+
const ttsSupplement = getReplyPayloadTtsSupplement(payload);
|
|
1542
|
+
const previewFinalText = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
|
|
1543
|
+
if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
|
|
1544
|
+
kind: params.kind,
|
|
1545
|
+
previewRootId: params.effectiveReplyToId,
|
|
1546
|
+
threadRootId: params.effectiveReplyToId,
|
|
1547
|
+
replyToId: payload.replyToId
|
|
1548
|
+
})) return;
|
|
1549
|
+
return { message: previewFinalText };
|
|
1550
|
+
},
|
|
1551
|
+
editFinal: async (previewPostId, edit) => {
|
|
1552
|
+
await updateMattermostPost(params.client, previewPostId, edit);
|
|
1553
|
+
},
|
|
1554
|
+
onPreviewFinalized: () => {
|
|
1555
|
+
params.previewState.finalizedViaPreviewPost = true;
|
|
1556
|
+
params.recordThreadParticipation?.();
|
|
1557
|
+
},
|
|
1558
|
+
buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
|
|
1559
|
+
deliverSupplemental: async (payload) => {
|
|
1560
|
+
await params.deliverPayload(payload);
|
|
1561
|
+
},
|
|
1562
|
+
logPreviewEditFailure: (err) => {
|
|
1563
|
+
params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
|
|
1564
|
+
}
|
|
1729
1565
|
}),
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1566
|
+
deliverNormally: async (payload) => {
|
|
1567
|
+
const supplement = getReplyPayloadTtsSupplement(payload);
|
|
1568
|
+
await params.deliverPayload(supplement && !payload.text?.trim() && supplement.visibleTextAlreadyDelivered !== true ? {
|
|
1569
|
+
...payload,
|
|
1570
|
+
text: supplement.spokenText
|
|
1571
|
+
} : payload);
|
|
1572
|
+
}
|
|
1734
1573
|
});
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1574
|
+
}
|
|
1575
|
+
//#endregion
|
|
1576
|
+
//#region extensions/mattermost/src/mattermost/thread-participation.ts
|
|
1577
|
+
const threadParticipation = createPersistentDedupeCache({
|
|
1578
|
+
globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
|
|
1579
|
+
ttlMs: 10080 * 60 * 1e3,
|
|
1580
|
+
maxSize: 5e3,
|
|
1581
|
+
persistent: {
|
|
1582
|
+
namespace: "mattermost.thread-participation",
|
|
1583
|
+
maxEntries: 1e3,
|
|
1584
|
+
openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
|
|
1585
|
+
logError: (error) => {
|
|
1586
|
+
try {
|
|
1587
|
+
getOptionalMattermostRuntime()?.logging.getChildLogger({
|
|
1588
|
+
plugin: "mattermost",
|
|
1589
|
+
feature: "thread-participation-state"
|
|
1590
|
+
}).warn("Mattermost persistent thread participation state failed", { error: String(error) });
|
|
1591
|
+
} catch {}
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
});
|
|
1595
|
+
function makeKey(accountId, channelId, threadRootId) {
|
|
1596
|
+
return `${accountId}:${channelId}:${threadRootId}`;
|
|
1597
|
+
}
|
|
1598
|
+
function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
|
|
1599
|
+
if (!accountId || !channelId || !threadRootId) return;
|
|
1600
|
+
threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
|
|
1601
|
+
...opts?.agentId ? { agentId: opts.agentId } : {},
|
|
1602
|
+
repliedAt: Date.now()
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
async function hasMattermostThreadParticipationWithPersistence(params) {
|
|
1606
|
+
if (!params.accountId || !params.channelId || !params.threadRootId) return false;
|
|
1607
|
+
return await threadParticipation.lookup(makeKey(params.accountId, params.channelId, params.threadRootId));
|
|
1608
|
+
}
|
|
1609
|
+
//#endregion
|
|
1610
|
+
//#region extensions/mattermost/src/mattermost/monitor-turn.ts
|
|
1611
|
+
function createDisabledMattermostDraftStream() {
|
|
1612
|
+
const noopAsync = async () => {};
|
|
1613
|
+
return {
|
|
1614
|
+
update: () => {},
|
|
1615
|
+
updateAssistantText: () => {},
|
|
1616
|
+
flush: noopAsync,
|
|
1617
|
+
postId: () => void 0,
|
|
1618
|
+
clear: noopAsync,
|
|
1619
|
+
discardPending: noopAsync,
|
|
1620
|
+
seal: noopAsync,
|
|
1621
|
+
stop: noopAsync,
|
|
1622
|
+
forceNewMessage: noopAsync,
|
|
1623
|
+
settleBoundaries: noopAsync,
|
|
1624
|
+
resolveFinalText: (text) => ({
|
|
1625
|
+
kind: "full",
|
|
1626
|
+
text
|
|
1627
|
+
})
|
|
1739
1628
|
};
|
|
1740
|
-
|
|
1629
|
+
}
|
|
1630
|
+
async function dispatchMattermostInboundTurn(monitor, params) {
|
|
1631
|
+
const { account, cfg, client, core, runtime } = monitor;
|
|
1632
|
+
const { channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
|
|
1633
|
+
const { channelId, kind, route, senderId, thread, to } = eventPlan;
|
|
1634
|
+
const { effectiveReplyToId } = thread;
|
|
1635
|
+
const { deliveryBarrier, replyOptions, replyPipeline: baseReplyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
|
|
1636
|
+
const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
|
|
1637
|
+
const { onModelSelected, typingCallbacks, resolveResponsePrefix, ...dispatcherPipeline } = createChannelMessageReplyPipeline({
|
|
1741
1638
|
cfg,
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
}) ?? 8 * 1024 * 1024;
|
|
1745
|
-
const historyLimit = Math.max(0, cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
|
|
1746
|
-
const channelHistories = /* @__PURE__ */ new Map();
|
|
1747
|
-
const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
|
|
1748
|
-
const dmPolicy = account.config.dmPolicy ?? "pairing";
|
|
1749
|
-
const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
|
|
1750
|
-
providerConfigPresent: cfg.channels?.mattermost !== void 0,
|
|
1751
|
-
groupPolicy: account.config.groupPolicy,
|
|
1752
|
-
defaultGroupPolicy
|
|
1753
|
-
});
|
|
1754
|
-
warnMissingProviderGroupPolicyFallbackOnce({
|
|
1755
|
-
providerMissingFallbackApplied,
|
|
1756
|
-
providerKey: "mattermost",
|
|
1639
|
+
agentId: route.agentId,
|
|
1640
|
+
channel: "mattermost",
|
|
1757
1641
|
accountId: account.accountId,
|
|
1758
|
-
|
|
1642
|
+
typing: baseReplyPipeline.typing
|
|
1759
1643
|
});
|
|
1760
|
-
const
|
|
1761
|
-
|
|
1762
|
-
|
|
1644
|
+
const draftPreviewEnabled = account.streamingMode !== "off";
|
|
1645
|
+
const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
|
|
1646
|
+
const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
|
|
1647
|
+
const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
|
|
1763
1648
|
client,
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1649
|
+
channelId,
|
|
1650
|
+
rootId: effectiveReplyToId,
|
|
1651
|
+
throttleMs: 1200,
|
|
1652
|
+
chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
|
|
1653
|
+
log: monitor.logVerboseMessage,
|
|
1654
|
+
warn: monitor.logVerboseMessage
|
|
1655
|
+
}) : createDisabledMattermostDraftStream();
|
|
1656
|
+
const previewBoundaryController = createMattermostDraftPreviewBoundaryController({
|
|
1657
|
+
enabled: draftPreviewEnabled && account.streamingMode === "block",
|
|
1658
|
+
forceNewMessage: async () => {
|
|
1659
|
+
await draftStream.forceNewMessage();
|
|
1660
|
+
}
|
|
1768
1661
|
});
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
const
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1662
|
+
let lastPartialText = "";
|
|
1663
|
+
let firstAssistantPreviewPrefix;
|
|
1664
|
+
let firstAssistantPreviewPrefixPending = true;
|
|
1665
|
+
let currentAssistantPreviewUsesPrefix = false;
|
|
1666
|
+
let blockPreviewActivity = "none";
|
|
1667
|
+
let blockPreviewAssistantMessagePending = false;
|
|
1668
|
+
const progressDraft = createChannelProgressDraftCompositor({
|
|
1669
|
+
entry: account.config,
|
|
1670
|
+
mode: account.streamingMode,
|
|
1671
|
+
active: draftPreviewEnabled,
|
|
1672
|
+
seed: `${account.accountId}:${channelId}`,
|
|
1673
|
+
update: async (previewText, options) => {
|
|
1674
|
+
draftStream.update(previewText);
|
|
1675
|
+
if (options?.flush) await draftStream.flush();
|
|
1676
|
+
}
|
|
1677
|
+
});
|
|
1678
|
+
const enterBlockPreviewActivity = (activity) => {
|
|
1679
|
+
if (account.streamingMode !== "block") return;
|
|
1680
|
+
const continuesCurrentActivity = activity === "tool" && blockPreviewActivity === "tool" || activity === "text" && blockPreviewActivity === "text" && !blockPreviewAssistantMessagePending || activity === "reasoning" && blockPreviewActivity === "reasoning";
|
|
1681
|
+
const startsNewGeneration = !continuesCurrentActivity && blockPreviewActivity !== "reasoning";
|
|
1682
|
+
if (startsNewGeneration) currentAssistantPreviewUsesPrefix = false;
|
|
1683
|
+
const boundarySettled = startsNewGeneration ? previewBoundaryController.noteBoundary() : void 0;
|
|
1684
|
+
if (!continuesCurrentActivity) progressDraft.reset();
|
|
1685
|
+
blockPreviewActivity = activity;
|
|
1686
|
+
blockPreviewAssistantMessagePending = false;
|
|
1687
|
+
if (activity === "tool") lastPartialText = "";
|
|
1688
|
+
return boundarySettled;
|
|
1689
|
+
};
|
|
1690
|
+
const previewState = { finalizedViaPreviewPost: false };
|
|
1691
|
+
const resolvePreviewFinalText = (text) => {
|
|
1692
|
+
if (typeof text !== "string") return;
|
|
1693
|
+
const resolution = draftStream.resolveFinalText(text);
|
|
1694
|
+
const deliveryText = resolution.kind === "already-delivered" ? "" : resolution.text;
|
|
1695
|
+
const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
|
|
1696
|
+
const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
|
|
1697
|
+
if (!chunks.length && formatted) chunks.push(formatted);
|
|
1698
|
+
if (chunks.length !== 1) return;
|
|
1699
|
+
const trimmed = chunks[0]?.trim();
|
|
1700
|
+
if (!trimmed) return;
|
|
1701
|
+
if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
|
|
1702
|
+
return trimmed;
|
|
1703
|
+
};
|
|
1704
|
+
const updateDraftFromPartial = (text) => {
|
|
1705
|
+
const cleaned = text?.trim();
|
|
1706
|
+
if (!cleaned || cleaned === lastPartialText) return;
|
|
1707
|
+
if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
|
|
1708
|
+
const boundarySettled = enterBlockPreviewActivity("text");
|
|
1709
|
+
lastPartialText = cleaned;
|
|
1710
|
+
if (firstAssistantPreviewPrefixPending) {
|
|
1711
|
+
firstAssistantPreviewPrefix = resolveResponsePrefix?.();
|
|
1712
|
+
firstAssistantPreviewPrefixPending = false;
|
|
1713
|
+
currentAssistantPreviewUsesPrefix = Boolean(firstAssistantPreviewPrefix);
|
|
1714
|
+
}
|
|
1715
|
+
const previewText = currentAssistantPreviewUsesPrefix && firstAssistantPreviewPrefix ? cleaned.startsWith(firstAssistantPreviewPrefix) ? cleaned : `${firstAssistantPreviewPrefix} ${cleaned}` : cleaned;
|
|
1716
|
+
draftStream.updateAssistantText(previewText);
|
|
1717
|
+
previewBoundaryController.noteUpdate();
|
|
1718
|
+
return boundarySettled;
|
|
1719
|
+
};
|
|
1720
|
+
const dispatcherOptions = {
|
|
1721
|
+
...dispatcherPipeline,
|
|
1722
|
+
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
|
|
1723
|
+
onDeliverySettled: deliveryBarrier.markDeliverySettled,
|
|
1724
|
+
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
|
|
1725
|
+
typingCallbacks
|
|
1726
|
+
};
|
|
1727
|
+
const delivery = {
|
|
1728
|
+
deliver: async (payloadEntry, info) => {
|
|
1729
|
+
if (info.kind === "final") {
|
|
1730
|
+
await enterBlockPreviewActivity("text");
|
|
1731
|
+
await draftStream.settleBoundaries();
|
|
1732
|
+
progressDraft.markFinalReplyStarted();
|
|
1733
|
+
}
|
|
1734
|
+
const markThreadParticipation = () => {
|
|
1735
|
+
if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
|
|
1736
|
+
};
|
|
1737
|
+
await deliverMattermostReplyWithDraftPreview({
|
|
1738
|
+
payload: payloadEntry,
|
|
1739
|
+
info,
|
|
1740
|
+
kind,
|
|
1741
|
+
client,
|
|
1742
|
+
draftStream,
|
|
1743
|
+
effectiveReplyToId,
|
|
1744
|
+
resolvePreviewFinalText,
|
|
1745
|
+
previewState,
|
|
1746
|
+
logVerboseMessage: monitor.logVerboseMessage,
|
|
1747
|
+
recordThreadParticipation: markThreadParticipation,
|
|
1748
|
+
deliverPayload: async (payloadToDeliver) => {
|
|
1749
|
+
const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream.resolveFinalText(payloadToDeliver.text) : void 0;
|
|
1750
|
+
const resolvedPayload = finalTextResolution ? {
|
|
1751
|
+
...payloadToDeliver,
|
|
1752
|
+
text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
|
|
1753
|
+
} : payloadToDeliver;
|
|
1754
|
+
const outcome = await deliverMattermostReplyPayload({
|
|
1848
1755
|
core,
|
|
1849
1756
|
cfg,
|
|
1850
|
-
payload:
|
|
1757
|
+
payload: resolvedPayload,
|
|
1851
1758
|
to,
|
|
1852
1759
|
accountId: account.accountId,
|
|
1853
|
-
agentId:
|
|
1760
|
+
agentId: route.agentId,
|
|
1854
1761
|
replyToId: resolveMattermostReplyRootId({
|
|
1855
|
-
kind
|
|
1856
|
-
threadRootId:
|
|
1857
|
-
replyToId:
|
|
1762
|
+
kind,
|
|
1763
|
+
threadRootId: effectiveReplyToId,
|
|
1764
|
+
replyToId: payloadToDeliver.replyToId
|
|
1858
1765
|
}),
|
|
1859
1766
|
textLimit,
|
|
1860
|
-
tableMode
|
|
1767
|
+
tableMode,
|
|
1861
1768
|
sendMessage: sendMessageMattermost,
|
|
1862
1769
|
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
1863
|
-
});
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
return capturedTexts.join("\n\n").trim();
|
|
1876
|
-
};
|
|
1877
|
-
async function handleModelPickerInteraction(params) {
|
|
1878
|
-
const pickerState = parseMattermostModelPickerContext(params.context);
|
|
1879
|
-
if (!pickerState) return null;
|
|
1880
|
-
if (pickerState.ownerUserId !== params.payload.user_id) return { ephemeral_text: "Only the person who opened this picker can use it." };
|
|
1881
|
-
const channelInfo = await resolveChannelInfo(params.payload.channel_id);
|
|
1882
|
-
const pickerCommandText = pickerState.action === "select" ? `/model ${pickerState.provider}/${pickerState.model}` : pickerState.action === "list" ? `/models ${pickerState.provider}` : "/models";
|
|
1883
|
-
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
|
|
1884
|
-
cfg,
|
|
1885
|
-
surface: "mattermost"
|
|
1886
|
-
});
|
|
1887
|
-
const hasControlCommand = core.channel.text.hasControlCommand(pickerCommandText, cfg);
|
|
1888
|
-
const auth = await authorizeMattermostCommandInvocation({
|
|
1889
|
-
account,
|
|
1890
|
-
cfg,
|
|
1891
|
-
senderId: params.payload.user_id,
|
|
1892
|
-
senderName: params.userName,
|
|
1893
|
-
channelId: params.payload.channel_id,
|
|
1894
|
-
channelInfo,
|
|
1895
|
-
readStoreAllowFrom: pairing.readAllowFromStore,
|
|
1896
|
-
allowTextCommands,
|
|
1897
|
-
hasControlCommand
|
|
1898
|
-
});
|
|
1899
|
-
if (!auth.ok) {
|
|
1900
|
-
if (auth.denyReason === "dm-pairing") {
|
|
1901
|
-
const { code } = await pairing.upsertPairingRequest({
|
|
1902
|
-
id: params.payload.user_id,
|
|
1903
|
-
meta: { name: params.userName }
|
|
1904
|
-
});
|
|
1905
|
-
return { ephemeral_text: core.channel.pairing.buildPairingReply({
|
|
1906
|
-
channel: "mattermost",
|
|
1907
|
-
idLine: `Your Mattermost user id: ${params.payload.user_id}`,
|
|
1908
|
-
code
|
|
1909
|
-
}) };
|
|
1910
|
-
}
|
|
1911
|
-
return { ephemeral_text: auth.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : auth.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : auth.denyReason === "channels-disabled" ? "Model picker actions are disabled in channels." : auth.denyReason === "channel-no-allowlist" ? "Model picker actions are not configured for this channel." : "Unauthorized." };
|
|
1912
|
-
}
|
|
1913
|
-
const kind = auth.kind;
|
|
1914
|
-
const chatType = auth.chatType;
|
|
1915
|
-
const teamId = auth.channelInfo.team_id ?? params.payload.team_id ?? void 0;
|
|
1916
|
-
const channelName = auth.channelName || void 0;
|
|
1917
|
-
const channelDisplay = auth.channelDisplay || auth.channelName || params.payload.channel_id;
|
|
1918
|
-
const roomLabel = auth.roomLabel;
|
|
1919
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
1920
|
-
cfg,
|
|
1921
|
-
channel: "mattermost",
|
|
1922
|
-
accountId: account.accountId,
|
|
1923
|
-
teamId,
|
|
1924
|
-
peer: {
|
|
1925
|
-
kind,
|
|
1926
|
-
id: kind === "direct" ? params.payload.user_id : params.payload.channel_id
|
|
1927
|
-
}
|
|
1928
|
-
});
|
|
1929
|
-
const replyToMode = resolveMattermostReplyToMode(account, kind);
|
|
1930
|
-
const threadContext = resolveMattermostThreadSessionContext({
|
|
1931
|
-
baseSessionKey: route.sessionKey,
|
|
1932
|
-
kind,
|
|
1933
|
-
postId: params.post.id || params.payload.post_id,
|
|
1934
|
-
replyToMode,
|
|
1935
|
-
threadRootId: params.post.root_id
|
|
1936
|
-
});
|
|
1937
|
-
const modelSessionRoute = {
|
|
1938
|
-
agentId: route.agentId,
|
|
1939
|
-
sessionKey: threadContext.sessionKey
|
|
1940
|
-
};
|
|
1941
|
-
const data = await buildModelsProviderData(cfg, route.agentId);
|
|
1942
|
-
if (data.providers.length === 0) return await updateModelPickerPost({
|
|
1943
|
-
channelId: params.payload.channel_id,
|
|
1944
|
-
postId: params.payload.post_id,
|
|
1945
|
-
message: "No models available."
|
|
1946
|
-
});
|
|
1947
|
-
if (pickerState.action === "providers" || pickerState.action === "back") {
|
|
1948
|
-
const currentModel = resolveMattermostModelPickerCurrentModel({
|
|
1949
|
-
cfg,
|
|
1950
|
-
route: modelSessionRoute,
|
|
1951
|
-
data
|
|
1952
|
-
});
|
|
1953
|
-
const view = renderMattermostProviderPickerView({
|
|
1954
|
-
ownerUserId: pickerState.ownerUserId,
|
|
1955
|
-
data,
|
|
1956
|
-
currentModel
|
|
1957
|
-
});
|
|
1958
|
-
return await updateModelPickerPost({
|
|
1959
|
-
channelId: params.payload.channel_id,
|
|
1960
|
-
postId: params.payload.post_id,
|
|
1961
|
-
message: view.text,
|
|
1962
|
-
buttons: view.buttons
|
|
1963
|
-
});
|
|
1964
|
-
}
|
|
1965
|
-
if (pickerState.action === "list") {
|
|
1966
|
-
const currentModel = resolveMattermostModelPickerCurrentModel({
|
|
1967
|
-
cfg,
|
|
1968
|
-
route: modelSessionRoute,
|
|
1969
|
-
data
|
|
1970
|
-
});
|
|
1971
|
-
const view = renderMattermostModelsPickerView({
|
|
1972
|
-
ownerUserId: pickerState.ownerUserId,
|
|
1973
|
-
data,
|
|
1974
|
-
provider: pickerState.provider,
|
|
1975
|
-
page: pickerState.page,
|
|
1976
|
-
currentModel
|
|
1977
|
-
});
|
|
1978
|
-
return await updateModelPickerPost({
|
|
1979
|
-
channelId: params.payload.channel_id,
|
|
1980
|
-
postId: params.payload.post_id,
|
|
1981
|
-
message: view.text,
|
|
1982
|
-
buttons: view.buttons
|
|
1770
|
+
});
|
|
1771
|
+
if (outcome === "text" || outcome === "media") markThreadParticipation();
|
|
1772
|
+
else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
|
|
1773
|
+
const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
|
|
1774
|
+
outcome,
|
|
1775
|
+
payload: resolvedPayload,
|
|
1776
|
+
to,
|
|
1777
|
+
accountId: account.accountId,
|
|
1778
|
+
agentId: route.agentId
|
|
1779
|
+
});
|
|
1780
|
+
if (deliveryLog) runtime.log?.(deliveryLog);
|
|
1781
|
+
}
|
|
1983
1782
|
});
|
|
1783
|
+
if (info.kind === "final") progressDraft.markFinalReplyDelivered();
|
|
1784
|
+
},
|
|
1785
|
+
onError: (err, info) => {
|
|
1786
|
+
runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
|
|
1984
1787
|
}
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
messageSid: buildMattermostModelPickerSelectMessageSid({
|
|
2006
|
-
postId: params.payload.post_id,
|
|
2007
|
-
provider: pickerState.provider,
|
|
2008
|
-
model: pickerState.model
|
|
2009
|
-
}),
|
|
2010
|
-
effectiveReplyToId: threadContext.effectiveReplyToId,
|
|
2011
|
-
deliverReplies: true
|
|
2012
|
-
});
|
|
2013
|
-
const updatedModel = resolveMattermostModelPickerCurrentModel({
|
|
1788
|
+
};
|
|
1789
|
+
const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
|
|
1790
|
+
route,
|
|
1791
|
+
sessionKey: route.sessionKey
|
|
1792
|
+
});
|
|
1793
|
+
try {
|
|
1794
|
+
await core.channel.inbound.run({
|
|
1795
|
+
channel: "mattermost",
|
|
1796
|
+
accountId: route.accountId,
|
|
1797
|
+
raw: post,
|
|
1798
|
+
adapter: {
|
|
1799
|
+
ingest: () => ({
|
|
1800
|
+
id: post.id ?? `${to}:${Date.now()}`,
|
|
1801
|
+
timestamp: post.create_at ?? void 0,
|
|
1802
|
+
rawText,
|
|
1803
|
+
textForAgent: ctxPayload.BodyForAgent,
|
|
1804
|
+
textForCommands: ctxPayload.CommandBody,
|
|
1805
|
+
raw: post
|
|
1806
|
+
}),
|
|
1807
|
+
resolveTurn: () => ({
|
|
2014
1808
|
cfg,
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
1809
|
+
channel: "mattermost",
|
|
1810
|
+
accountId: route.accountId,
|
|
1811
|
+
route: {
|
|
1812
|
+
agentId: route.agentId,
|
|
1813
|
+
dmScope: route.dmScope,
|
|
1814
|
+
sessionKey: route.sessionKey
|
|
1815
|
+
},
|
|
1816
|
+
ctxPayload,
|
|
1817
|
+
record: {
|
|
1818
|
+
updateLastRoute: kind === "direct" ? {
|
|
1819
|
+
sessionKey: inboundLastRouteSessionKey,
|
|
1820
|
+
channel: "mattermost",
|
|
1821
|
+
to,
|
|
1822
|
+
accountId: route.accountId,
|
|
1823
|
+
mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
|
|
1824
|
+
ownerRecipient: pinnedMainDmOwner,
|
|
1825
|
+
senderRecipient: normalizeMattermostAllowEntry(senderId),
|
|
1826
|
+
onSkip: ({ ownerRecipient, senderRecipient }) => {
|
|
1827
|
+
monitor.logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
|
|
1828
|
+
}
|
|
1829
|
+
} : void 0
|
|
1830
|
+
} : void 0,
|
|
1831
|
+
onRecordError: (err) => {
|
|
1832
|
+
monitor.logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
|
|
1833
|
+
}
|
|
1834
|
+
},
|
|
1835
|
+
history: {
|
|
1836
|
+
isGroup: Boolean(historyKey),
|
|
1837
|
+
historyKey: historyKey ?? void 0,
|
|
1838
|
+
historyMap: channelHistories,
|
|
1839
|
+
limit: historyLimit
|
|
1840
|
+
},
|
|
1841
|
+
dispatcherOptions,
|
|
1842
|
+
delivery,
|
|
1843
|
+
replyOptions: {
|
|
1844
|
+
...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
|
|
1845
|
+
allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
|
|
1846
|
+
preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
|
|
1847
|
+
onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
|
|
1848
|
+
disableBlockStreaming: draftPreviewEnabled ? true : replyOptions.disableBlockStreaming,
|
|
1849
|
+
...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
|
|
1850
|
+
onModelSelected,
|
|
1851
|
+
onPartialReply: (payloadResult) => account.streamingMode === "progress" ? void 0 : updateDraftFromPartial(payloadResult.text),
|
|
1852
|
+
onAssistantMessageStart: () => {
|
|
1853
|
+
lastPartialText = "";
|
|
1854
|
+
progressDraft.resetReasoningProgress();
|
|
1855
|
+
if (account.streamingMode === "block") {
|
|
1856
|
+
blockPreviewAssistantMessagePending = true;
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
if (account.streamingMode !== "progress") progressDraft.reset();
|
|
1860
|
+
},
|
|
1861
|
+
onReasoningEnd: () => {
|
|
1862
|
+
lastPartialText = "";
|
|
1863
|
+
progressDraft.resetReasoningProgress();
|
|
1864
|
+
if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
|
|
1865
|
+
},
|
|
1866
|
+
onReasoningStream: async (payloadResult) => {
|
|
1867
|
+
if (account.streamingMode === "progress") {
|
|
1868
|
+
await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
if (!lastPartialText) {
|
|
1872
|
+
const boundarySettled = enterBlockPreviewActivity("reasoning");
|
|
1873
|
+
draftStream.update("Thinking…");
|
|
1874
|
+
previewBoundaryController.noteUpdate();
|
|
1875
|
+
await boundarySettled;
|
|
1876
|
+
}
|
|
1877
|
+
},
|
|
1878
|
+
onToolStart: async (payloadValue) => {
|
|
1879
|
+
if (!draftToolProgressEnabled) return;
|
|
1880
|
+
const boundarySettled = enterBlockPreviewActivity("tool");
|
|
1881
|
+
const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
|
|
1882
|
+
event: "tool",
|
|
1883
|
+
itemId: payloadValue.itemId,
|
|
1884
|
+
toolCallId: payloadValue.toolCallId,
|
|
1885
|
+
name: payloadValue.name,
|
|
1886
|
+
phase: payloadValue.phase,
|
|
1887
|
+
args: payloadValue.args
|
|
1888
|
+
}, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
|
|
1889
|
+
previewBoundaryController.noteUpdate();
|
|
1890
|
+
await Promise.all([boundarySettled, progressSettled]);
|
|
1891
|
+
},
|
|
1892
|
+
onItemEvent: async (payloadLocal) => {
|
|
1893
|
+
if (!draftToolProgressEnabled) return;
|
|
1894
|
+
const boundarySettled = enterBlockPreviewActivity("tool");
|
|
1895
|
+
const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
|
|
1896
|
+
event: "item",
|
|
1897
|
+
itemId: payloadLocal.itemId,
|
|
1898
|
+
itemKind: payloadLocal.kind,
|
|
1899
|
+
title: payloadLocal.title,
|
|
1900
|
+
name: payloadLocal.name,
|
|
1901
|
+
phase: payloadLocal.phase,
|
|
1902
|
+
status: payloadLocal.status,
|
|
1903
|
+
summary: payloadLocal.summary,
|
|
1904
|
+
progressText: payloadLocal.progressText,
|
|
1905
|
+
meta: payloadLocal.meta
|
|
1906
|
+
}), { startImmediately: true });
|
|
1907
|
+
previewBoundaryController.noteUpdate();
|
|
1908
|
+
await Promise.all([boundarySettled, progressSettled]);
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
})
|
|
2034
1912
|
}
|
|
2035
|
-
})
|
|
2036
|
-
|
|
1913
|
+
});
|
|
1914
|
+
} finally {
|
|
1915
|
+
try {
|
|
1916
|
+
await draftStream.stop();
|
|
1917
|
+
} catch (err) {
|
|
1918
|
+
monitor.logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
|
|
1919
|
+
}
|
|
2037
1920
|
}
|
|
2038
|
-
|
|
1921
|
+
}
|
|
1922
|
+
//#endregion
|
|
1923
|
+
//#region extensions/mattermost/src/mattermost/monitor-posts.ts
|
|
1924
|
+
function createMattermostPostHandler(monitor) {
|
|
1925
|
+
const { account, botUserId, botUsername, cfg, core, groupPolicy, pairing, resources } = monitor;
|
|
1926
|
+
const { resolveMattermostMedia, resolveUserInfo } = resources;
|
|
1927
|
+
const channelHistories = /* @__PURE__ */ new Map();
|
|
1928
|
+
const historyLimit = Math.max(0, cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
|
|
1929
|
+
return async (post, payload, turnAdoptionLifecycle, messageIds) => {
|
|
2039
1930
|
const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
|
|
2040
1931
|
if (!channelId) {
|
|
2041
|
-
logVerboseMessage("mattermost: drop post (missing channel id)");
|
|
1932
|
+
monitor.logVerboseMessage("mattermost: drop post (missing channel id)");
|
|
2042
1933
|
return;
|
|
2043
1934
|
}
|
|
2044
1935
|
if (!post.id) {
|
|
2045
|
-
logVerboseMessage("mattermost: drop post (missing message id)");
|
|
1936
|
+
monitor.logVerboseMessage("mattermost: drop post (missing message id)");
|
|
2046
1937
|
return;
|
|
2047
1938
|
}
|
|
2048
1939
|
const allMessageIds = messageIds?.length ? messageIds : [post.id];
|
|
2049
1940
|
const senderId = post.user_id ?? payload.broadcast?.user_id;
|
|
2050
1941
|
if (!senderId) {
|
|
2051
|
-
logVerboseMessage("mattermost: drop post (missing sender id)");
|
|
1942
|
+
monitor.logVerboseMessage("mattermost: drop post (missing sender id)");
|
|
2052
1943
|
return;
|
|
2053
1944
|
}
|
|
2054
1945
|
if (senderId === botUserId) {
|
|
2055
|
-
logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
|
|
2056
|
-
return;
|
|
2057
|
-
}
|
|
2058
|
-
if (isSystemPost(post)) {
|
|
2059
|
-
logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
|
|
1946
|
+
monitor.logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
|
|
2060
1947
|
return;
|
|
2061
1948
|
}
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
if (!channelType) {
|
|
2065
|
-
logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
|
|
1949
|
+
if (normalizeOptionalString(post.type) !== void 0) {
|
|
1950
|
+
monitor.logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
|
|
2066
1951
|
return;
|
|
2067
1952
|
}
|
|
2068
|
-
const
|
|
2069
|
-
|
|
1953
|
+
const eventPlan = await buildMattermostEventPlan(monitor, {
|
|
1954
|
+
channelId,
|
|
1955
|
+
senderId,
|
|
1956
|
+
postId: post.id,
|
|
1957
|
+
threadRootId: normalizeOptionalString(post.root_id),
|
|
1958
|
+
channelTypeFallback: payload.data?.channel_type,
|
|
1959
|
+
teamId: payload.data?.team_id,
|
|
1960
|
+
channelName: payload.data?.channel_name,
|
|
1961
|
+
channelDisplay: payload.data?.channel_display_name,
|
|
1962
|
+
dropLabel: "post"
|
|
1963
|
+
});
|
|
1964
|
+
if (!eventPlan) return;
|
|
1965
|
+
const { channelDisplay, kind, roomLabel, route, thread } = eventPlan;
|
|
2070
1966
|
const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
|
|
2071
1967
|
const rawPostText = typeof post.message === "string" ? post.message : "";
|
|
2072
1968
|
const rawText = normalizeOptionalString(rawPostText) ?? "";
|
|
@@ -2093,7 +1989,7 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2093
1989
|
if (accessDecision.ingress.decision !== "allow") {
|
|
2094
1990
|
if (kind === "direct") {
|
|
2095
1991
|
if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
|
|
2096
|
-
logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
|
|
1992
|
+
monitor.logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
|
|
2097
1993
|
return;
|
|
2098
1994
|
}
|
|
2099
1995
|
if (accessDecision.ingress.decision === "pairing") {
|
|
@@ -2101,7 +1997,7 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2101
1997
|
id: senderId,
|
|
2102
1998
|
meta: { name: senderName }
|
|
2103
1999
|
});
|
|
2104
|
-
logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
|
|
2000
|
+
monitor.logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
|
|
2105
2001
|
if (created) try {
|
|
2106
2002
|
await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
|
|
2107
2003
|
channel: "mattermost",
|
|
@@ -2111,67 +2007,44 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2111
2007
|
cfg,
|
|
2112
2008
|
accountId: account.accountId
|
|
2113
2009
|
});
|
|
2114
|
-
|
|
2010
|
+
monitor.statusSink?.({ lastOutboundAt: Date.now() });
|
|
2115
2011
|
} catch (err) {
|
|
2116
|
-
logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
|
|
2012
|
+
monitor.logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
|
|
2117
2013
|
}
|
|
2118
2014
|
return;
|
|
2119
2015
|
}
|
|
2120
|
-
logVerboseMessage(formatMattermostDirectMessageDropLog({
|
|
2016
|
+
monitor.logVerboseMessage(formatMattermostDirectMessageDropLog({
|
|
2121
2017
|
senderId,
|
|
2122
|
-
dmPolicy,
|
|
2018
|
+
dmPolicy: account.config.dmPolicy ?? "pairing",
|
|
2123
2019
|
reasonCode: accessDecision.senderAccess.reasonCode
|
|
2124
2020
|
}));
|
|
2125
2021
|
return;
|
|
2126
2022
|
}
|
|
2127
2023
|
if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
|
|
2128
|
-
logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
|
|
2024
|
+
monitor.logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
|
|
2129
2025
|
return;
|
|
2130
2026
|
}
|
|
2131
2027
|
if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
|
|
2132
|
-
logVerboseMessage("mattermost: drop group message (no group allowlist)");
|
|
2028
|
+
monitor.logVerboseMessage("mattermost: drop group message (no group allowlist)");
|
|
2133
2029
|
return;
|
|
2134
2030
|
}
|
|
2135
2031
|
if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
|
|
2136
|
-
logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
|
|
2032
|
+
monitor.logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
|
|
2137
2033
|
return;
|
|
2138
2034
|
}
|
|
2139
|
-
logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
|
|
2035
|
+
monitor.logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
|
|
2140
2036
|
return;
|
|
2141
2037
|
}
|
|
2142
2038
|
if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
|
|
2143
2039
|
logInboundDrop({
|
|
2144
|
-
log: logVerboseMessage,
|
|
2040
|
+
log: monitor.logVerboseMessage,
|
|
2145
2041
|
channel: "mattermost",
|
|
2146
2042
|
reason: "control command (unauthorized)",
|
|
2147
2043
|
target: senderId
|
|
2148
2044
|
});
|
|
2149
2045
|
return;
|
|
2150
2046
|
}
|
|
2151
|
-
const
|
|
2152
|
-
const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
|
|
2153
|
-
const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
|
|
2154
|
-
const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
|
|
2155
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
2156
|
-
cfg,
|
|
2157
|
-
channel: "mattermost",
|
|
2158
|
-
accountId: account.accountId,
|
|
2159
|
-
teamId,
|
|
2160
|
-
peer: {
|
|
2161
|
-
kind,
|
|
2162
|
-
id: kind === "direct" ? senderId : channelId
|
|
2163
|
-
}
|
|
2164
|
-
});
|
|
2165
|
-
const baseSessionKey = route.sessionKey;
|
|
2166
|
-
const threadRootId = normalizeOptionalString(post.root_id);
|
|
2167
|
-
const replyToMode = resolveMattermostReplyToMode(account, kind);
|
|
2168
|
-
const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
|
|
2169
|
-
baseSessionKey,
|
|
2170
|
-
kind,
|
|
2171
|
-
postId: post.id,
|
|
2172
|
-
replyToMode,
|
|
2173
|
-
threadRootId
|
|
2174
|
-
});
|
|
2047
|
+
const { effectiveReplyToId, sessionKey } = thread;
|
|
2175
2048
|
const historyKey = resolveMattermostPendingHistoryKey({
|
|
2176
2049
|
kind,
|
|
2177
2050
|
sessionKey
|
|
@@ -2184,17 +2057,16 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2184
2057
|
body: rawText,
|
|
2185
2058
|
media: nativeMedia
|
|
2186
2059
|
});
|
|
2187
|
-
const pendingSender = senderName;
|
|
2188
2060
|
const recordPendingHistory = () => {
|
|
2189
2061
|
const trimmed = pendingBody.trim();
|
|
2190
2062
|
createChannelHistoryWindow({ historyMap: channelHistories }).record({
|
|
2191
2063
|
limit: historyLimit,
|
|
2192
2064
|
historyKey: historyKey ?? "",
|
|
2193
2065
|
entry: historyKey && trimmed ? {
|
|
2194
|
-
sender:
|
|
2066
|
+
sender: senderName,
|
|
2195
2067
|
body: trimmed,
|
|
2196
2068
|
timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
|
|
2197
|
-
messageId: post.id
|
|
2069
|
+
messageId: post.id
|
|
2198
2070
|
} : null
|
|
2199
2071
|
});
|
|
2200
2072
|
};
|
|
@@ -2218,7 +2090,6 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2218
2090
|
groupId: channelId,
|
|
2219
2091
|
requireMentionOverride: account.requireMention
|
|
2220
2092
|
});
|
|
2221
|
-
const implicitMentionKinds = implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged);
|
|
2222
2093
|
const mentionDecision = resolveMattermostInboundMentionDecision({
|
|
2223
2094
|
cfg,
|
|
2224
2095
|
accountId: account.accountId,
|
|
@@ -2226,19 +2097,19 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2226
2097
|
requireMention: shouldRequireMention || oncharEnabled,
|
|
2227
2098
|
canDetectMention: canDetectMention || oncharEnabled,
|
|
2228
2099
|
wasMentioned: wasMentioned || oncharTriggered,
|
|
2229
|
-
implicitMentionKinds,
|
|
2100
|
+
implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged),
|
|
2230
2101
|
allowTextCommands,
|
|
2231
2102
|
hasControlCommand: isControlCommand,
|
|
2232
2103
|
commandAuthorized
|
|
2233
2104
|
});
|
|
2234
2105
|
const { shouldBypassMention } = mentionDecision;
|
|
2235
2106
|
if (mentionDecision.shouldSkip && oncharEnabled && !oncharTriggered && !wasMentioned && !shouldBypassMention) {
|
|
2236
|
-
logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
|
|
2107
|
+
monitor.logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
|
|
2237
2108
|
recordPendingHistory();
|
|
2238
2109
|
return;
|
|
2239
2110
|
}
|
|
2240
2111
|
if (mentionDecision.shouldSkip) {
|
|
2241
|
-
logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
|
|
2112
|
+
monitor.logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
|
|
2242
2113
|
recordPendingHistory();
|
|
2243
2114
|
return;
|
|
2244
2115
|
}
|
|
@@ -2253,7 +2124,7 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2253
2124
|
rawText: rawPostText,
|
|
2254
2125
|
botUsername
|
|
2255
2126
|
})) {
|
|
2256
|
-
logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
|
|
2127
|
+
monitor.logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
|
|
2257
2128
|
return;
|
|
2258
2129
|
}
|
|
2259
2130
|
const bodyForAgent = bodyText || rawText.trim();
|
|
@@ -2270,13 +2141,13 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2270
2141
|
directLabel: senderName,
|
|
2271
2142
|
directId: senderId
|
|
2272
2143
|
});
|
|
2273
|
-
const textWithId = `${bodyText}\n[mattermost message id: ${post.id
|
|
2144
|
+
const textWithId = `${bodyText}\n[mattermost message id: ${post.id} channel: ${channelId}]`;
|
|
2274
2145
|
let combinedBody = formatInboundEnvelope({
|
|
2275
2146
|
channel: "Mattermost",
|
|
2276
2147
|
from: fromLabel,
|
|
2277
2148
|
timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
|
|
2278
2149
|
body: textWithId,
|
|
2279
|
-
chatType,
|
|
2150
|
+
chatType: kind,
|
|
2280
2151
|
sender: {
|
|
2281
2152
|
name: senderName,
|
|
2282
2153
|
id: senderId
|
|
@@ -2291,52 +2162,34 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2291
2162
|
from: fromLabel,
|
|
2292
2163
|
timestamp: entry.timestamp,
|
|
2293
2164
|
body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
|
|
2294
|
-
chatType,
|
|
2165
|
+
chatType: kind,
|
|
2295
2166
|
senderLabel: entry.sender
|
|
2296
2167
|
})
|
|
2297
2168
|
});
|
|
2298
|
-
const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
|
|
2299
|
-
const mediaPayload = buildMattermostInboundMediaPayload(mediaList);
|
|
2300
2169
|
const commandBody = rawText.trim();
|
|
2301
2170
|
const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
|
|
2302
2171
|
historyKey,
|
|
2303
2172
|
limit: historyLimit
|
|
2304
2173
|
}) : void 0;
|
|
2305
|
-
const ctxPayload =
|
|
2174
|
+
const ctxPayload = eventPlan.finalizeContext({
|
|
2306
2175
|
Body: combinedBody,
|
|
2307
2176
|
BodyForAgent: bodyForAgent,
|
|
2308
2177
|
InboundHistory: inboundHistory,
|
|
2309
2178
|
RawBody: commandBody,
|
|
2310
2179
|
CommandBody: commandBody,
|
|
2311
2180
|
BodyForCommands: commandBody,
|
|
2312
|
-
From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
|
|
2313
|
-
To: to,
|
|
2314
|
-
SessionKey: sessionKey,
|
|
2315
|
-
DmScope: route.dmScope,
|
|
2316
|
-
ParentSessionKey: parentSessionKey,
|
|
2317
|
-
AccountId: route.accountId,
|
|
2318
|
-
ChatType: chatType,
|
|
2319
2181
|
ConversationLabel: fromLabel,
|
|
2320
2182
|
GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
|
|
2321
|
-
GroupChannel: channelName ? `#${channelName}` : void 0,
|
|
2322
|
-
GroupSpace: teamId,
|
|
2323
2183
|
SenderName: senderName,
|
|
2324
|
-
|
|
2325
|
-
Provider: "mattermost",
|
|
2326
|
-
Surface: "mattermost",
|
|
2327
|
-
MessageSid: post.id ?? void 0,
|
|
2184
|
+
MessageSid: post.id,
|
|
2328
2185
|
MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
|
|
2329
2186
|
MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
|
|
2330
2187
|
MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
|
|
2331
|
-
ReplyToId: effectiveReplyToId,
|
|
2332
|
-
MessageThreadId: effectiveReplyToId,
|
|
2333
2188
|
Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
|
|
2334
2189
|
WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
|
|
2335
2190
|
CommandAuthorized: commandAuthorized,
|
|
2336
2191
|
CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
|
|
2337
|
-
|
|
2338
|
-
OriginatingTo: to,
|
|
2339
|
-
...mediaPayload
|
|
2192
|
+
...buildMattermostInboundMediaPayload(mediaList)
|
|
2340
2193
|
});
|
|
2341
2194
|
const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
|
|
2342
2195
|
dmScope: cfg.session?.dmScope,
|
|
@@ -2344,419 +2197,428 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2344
2197
|
normalizeEntry: normalizeMattermostAllowEntry
|
|
2345
2198
|
}) : null;
|
|
2346
2199
|
const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
|
|
2347
|
-
logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2200
|
+
monitor.logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
|
|
2201
|
+
await dispatchMattermostInboundTurn(monitor, {
|
|
2202
|
+
post,
|
|
2203
|
+
rawText,
|
|
2204
|
+
ctxPayload,
|
|
2205
|
+
eventPlan,
|
|
2206
|
+
historyKey,
|
|
2207
|
+
historyLimit,
|
|
2208
|
+
channelHistories,
|
|
2209
|
+
pinnedMainDmOwner,
|
|
2210
|
+
turnAdoptionLifecycle
|
|
2353
2211
|
});
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
//#endregion
|
|
2215
|
+
//#region extensions/mattermost/src/mattermost/monitor-reactions.ts
|
|
2216
|
+
function createMattermostReactionHandler(monitor) {
|
|
2217
|
+
const { account, botUserId, cfg, core, groupPolicy, pairing, resources } = monitor;
|
|
2218
|
+
const { resolveUserInfo } = resources;
|
|
2219
|
+
return async (payload) => {
|
|
2220
|
+
const reactionData = payload.data?.reaction;
|
|
2221
|
+
if (!reactionData) return;
|
|
2222
|
+
let reaction = null;
|
|
2223
|
+
if (typeof reactionData === "string") try {
|
|
2224
|
+
reaction = JSON.parse(reactionData);
|
|
2225
|
+
} catch {
|
|
2226
|
+
return;
|
|
2227
|
+
}
|
|
2228
|
+
else if (typeof reactionData === "object") reaction = reactionData;
|
|
2229
|
+
const userId = reaction?.user_id?.trim();
|
|
2230
|
+
const postId = reaction?.post_id?.trim();
|
|
2231
|
+
const emojiName = reaction?.emoji_name?.trim();
|
|
2232
|
+
if (!userId || !postId || !emojiName || userId === botUserId) return;
|
|
2233
|
+
const action = payload.event === "reaction_removed" ? "removed" : "added";
|
|
2234
|
+
const senderName = normalizeOptionalString((await resolveUserInfo(userId))?.username) ?? userId;
|
|
2235
|
+
const channelId = resolveMattermostReactionChannelId(payload);
|
|
2236
|
+
if (!channelId) {
|
|
2237
|
+
monitor.logVerboseMessage("mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)");
|
|
2238
|
+
return;
|
|
2239
|
+
}
|
|
2240
|
+
const eventPlan = await buildMattermostEventPlan(monitor, {
|
|
2241
|
+
channelId,
|
|
2242
|
+
senderId: userId,
|
|
2243
|
+
dropLabel: "reaction"
|
|
2371
2244
|
});
|
|
2372
|
-
|
|
2373
|
-
const
|
|
2374
|
-
const
|
|
2375
|
-
|
|
2376
|
-
|
|
2245
|
+
if (!eventPlan) return;
|
|
2246
|
+
const { kind, route } = eventPlan;
|
|
2247
|
+
const reactionAccess = await resolveMattermostMonitorInboundAccess({
|
|
2248
|
+
account,
|
|
2249
|
+
cfg,
|
|
2250
|
+
senderId: userId,
|
|
2251
|
+
senderName,
|
|
2377
2252
|
channelId,
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
enabled: draftPreviewEnabled && account.streamingMode === "block",
|
|
2386
|
-
forceNewMessage: async () => {
|
|
2387
|
-
await draftStream.forceNewMessage();
|
|
2388
|
-
}
|
|
2253
|
+
kind,
|
|
2254
|
+
groupPolicy,
|
|
2255
|
+
readStoreAllowFrom: pairing.readAllowFromStore,
|
|
2256
|
+
allowTextCommands: false,
|
|
2257
|
+
hasControlCommand: false,
|
|
2258
|
+
eventKind: "reaction",
|
|
2259
|
+
mayPair: false
|
|
2389
2260
|
});
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
mode: account.streamingMode,
|
|
2399
|
-
active: draftPreviewEnabled,
|
|
2400
|
-
seed: `${account.accountId}:${channelId}`,
|
|
2401
|
-
update: async (previewText, options) => {
|
|
2402
|
-
draftStream.update(previewText);
|
|
2403
|
-
if (options?.flush) await draftStream.flush();
|
|
2404
|
-
}
|
|
2261
|
+
if (reactionAccess.ingress.decision !== "allow") {
|
|
2262
|
+
monitor.logVerboseMessage(kind === "direct" ? `mattermost: drop reaction (dmPolicy=${account.config.dmPolicy ?? "pairing"} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode})` : `mattermost: drop reaction (groupPolicy=${groupPolicy} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode} channel=${channelId})`);
|
|
2263
|
+
return;
|
|
2264
|
+
}
|
|
2265
|
+
const eventText = `Mattermost reaction ${action}: :${emojiName}: by @${senderName} on post ${postId} in channel ${channelId}`;
|
|
2266
|
+
core.system.enqueueSystemEvent(eventText, {
|
|
2267
|
+
sessionKey: route.sessionKey,
|
|
2268
|
+
contextKey: `mattermost:reaction:${postId}:${emojiName}:${userId}:${action}`
|
|
2405
2269
|
});
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
const
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2270
|
+
monitor.logVerboseMessage(`mattermost reaction: ${action} :${emojiName}: by ${senderName} on ${postId}`);
|
|
2271
|
+
};
|
|
2272
|
+
}
|
|
2273
|
+
//#endregion
|
|
2274
|
+
//#region extensions/mattermost/src/mattermost/monitor-slash.ts
|
|
2275
|
+
function buildSlashCommands(params) {
|
|
2276
|
+
const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
|
|
2277
|
+
if (!params.nativeSkills) return commandsToRegister;
|
|
2278
|
+
try {
|
|
2279
|
+
const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
|
|
2280
|
+
for (const spec of skillCommands) {
|
|
2281
|
+
const name = typeof spec.name === "string" ? spec.name.trim() : "";
|
|
2282
|
+
if (!name) continue;
|
|
2283
|
+
const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
|
|
2284
|
+
commandsToRegister.push({
|
|
2285
|
+
trigger,
|
|
2286
|
+
description: spec.description || `Run skill ${name}`,
|
|
2287
|
+
autoComplete: true,
|
|
2288
|
+
autoCompleteHint: "[args]",
|
|
2289
|
+
originalName: name
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
} catch (err) {
|
|
2293
|
+
params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
|
|
2294
|
+
}
|
|
2295
|
+
return commandsToRegister;
|
|
2296
|
+
}
|
|
2297
|
+
function dedupeSlashCommands(commands) {
|
|
2298
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2299
|
+
return commands.filter((cmd) => {
|
|
2300
|
+
const key = cmd.trigger.trim();
|
|
2301
|
+
if (!key || seen.has(key)) return false;
|
|
2302
|
+
seen.add(key);
|
|
2303
|
+
return true;
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
function buildTriggerMap(commands) {
|
|
2307
|
+
const triggerMap = /* @__PURE__ */ new Map();
|
|
2308
|
+
for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
|
|
2309
|
+
return triggerMap;
|
|
2310
|
+
}
|
|
2311
|
+
function warnOnSuspiciousCallbackUrl(params) {
|
|
2312
|
+
try {
|
|
2313
|
+
const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
|
|
2314
|
+
const callbackHost = new URL(params.callbackUrl).hostname;
|
|
2315
|
+
if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
|
|
2316
|
+
} catch {}
|
|
2317
|
+
}
|
|
2318
|
+
async function registerSlashCommandsAcrossTeams(params) {
|
|
2319
|
+
const registered = [];
|
|
2320
|
+
let teamRegistrationFailures = 0;
|
|
2321
|
+
for (const team of params.teams) try {
|
|
2322
|
+
const created = await registerSlashCommands({
|
|
2323
|
+
client: params.client,
|
|
2324
|
+
teamId: team.id,
|
|
2325
|
+
creatorUserId: params.botUserId,
|
|
2326
|
+
callbackUrl: params.callbackUrl,
|
|
2327
|
+
commands: params.commands,
|
|
2328
|
+
log: (msg) => params.runtime.log?.(msg)
|
|
2456
2329
|
});
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
|
|
2510
|
-
const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
|
|
2511
|
-
outcome,
|
|
2512
|
-
payload: resolvedPayload,
|
|
2513
|
-
to,
|
|
2514
|
-
accountId: account.accountId,
|
|
2515
|
-
agentId: route.agentId
|
|
2516
|
-
});
|
|
2517
|
-
if (deliveryLog) runtime.log?.(deliveryLog);
|
|
2518
|
-
}
|
|
2519
|
-
});
|
|
2520
|
-
if (info.kind === "final") progressDraft.markFinalReplyDelivered();
|
|
2330
|
+
registered.push(...created);
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
teamRegistrationFailures += 1;
|
|
2333
|
+
params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
|
|
2334
|
+
}
|
|
2335
|
+
return {
|
|
2336
|
+
registered,
|
|
2337
|
+
teamRegistrationFailures
|
|
2338
|
+
};
|
|
2339
|
+
}
|
|
2340
|
+
async function registerMattermostMonitorSlashCommands(params) {
|
|
2341
|
+
const commandsRaw = params.account.config.commands;
|
|
2342
|
+
const slashConfig = resolveSlashCommandConfig(commandsRaw);
|
|
2343
|
+
if (!isSlashCommandsEnabled(slashConfig)) return;
|
|
2344
|
+
try {
|
|
2345
|
+
const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
|
|
2346
|
+
const slashCallbackUrl = resolveCallbackUrl({
|
|
2347
|
+
config: slashConfig,
|
|
2348
|
+
gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
|
|
2349
|
+
gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
|
|
2350
|
+
});
|
|
2351
|
+
warnOnSuspiciousCallbackUrl({
|
|
2352
|
+
runtime: params.runtime,
|
|
2353
|
+
baseUrl: params.baseUrl,
|
|
2354
|
+
callbackUrl: slashCallbackUrl
|
|
2355
|
+
});
|
|
2356
|
+
const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
|
|
2357
|
+
cfg: params.cfg,
|
|
2358
|
+
runtime: params.runtime,
|
|
2359
|
+
nativeSkills: slashConfig.nativeSkills === true
|
|
2360
|
+
}));
|
|
2361
|
+
const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
|
|
2362
|
+
client: params.client,
|
|
2363
|
+
teams,
|
|
2364
|
+
botUserId: params.botUserId,
|
|
2365
|
+
callbackUrl: slashCallbackUrl,
|
|
2366
|
+
commands: dedupedCommands,
|
|
2367
|
+
runtime: params.runtime
|
|
2368
|
+
});
|
|
2369
|
+
if (registered.length === 0) {
|
|
2370
|
+
params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
|
|
2371
|
+
return;
|
|
2372
|
+
}
|
|
2373
|
+
if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
|
|
2374
|
+
activateSlashCommands({
|
|
2375
|
+
account: params.account,
|
|
2376
|
+
commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
|
|
2377
|
+
registeredCommands: registered,
|
|
2378
|
+
triggerMap: buildTriggerMap(dedupedCommands),
|
|
2379
|
+
api: {
|
|
2380
|
+
cfg: params.cfg,
|
|
2381
|
+
runtime: params.runtime
|
|
2521
2382
|
},
|
|
2522
|
-
|
|
2523
|
-
runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
|
|
2524
|
-
}
|
|
2525
|
-
};
|
|
2526
|
-
const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
|
|
2527
|
-
route,
|
|
2528
|
-
sessionKey: route.sessionKey
|
|
2383
|
+
log: (msg) => params.runtime.log?.(msg)
|
|
2529
2384
|
});
|
|
2385
|
+
params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
|
|
2386
|
+
} catch (err) {
|
|
2387
|
+
params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
//#endregion
|
|
2391
|
+
//#region extensions/mattermost/src/mattermost/reconnect.ts
|
|
2392
|
+
/**
|
|
2393
|
+
* Reconnection loop with exponential backoff.
|
|
2394
|
+
*
|
|
2395
|
+
* Calls `connectFn` in a while loop. On normal resolve (connection closed),
|
|
2396
|
+
* the backoff resets. On thrown error (connection failed), the current delay is
|
|
2397
|
+
* used, then doubled for the next retry.
|
|
2398
|
+
* The loop exits when `abortSignal` fires.
|
|
2399
|
+
*/
|
|
2400
|
+
async function runWithReconnect(connectFn, opts = {}) {
|
|
2401
|
+
const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
|
|
2402
|
+
const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
|
|
2403
|
+
const random = opts.random ?? Math.random;
|
|
2404
|
+
const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
|
|
2405
|
+
let attempt = 0;
|
|
2406
|
+
while (!opts.abortSignal?.aborted) {
|
|
2407
|
+
let outcome = "resolved";
|
|
2408
|
+
let error;
|
|
2530
2409
|
try {
|
|
2531
|
-
await
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
timestamp: post.create_at ?? void 0,
|
|
2539
|
-
rawText,
|
|
2540
|
-
textForAgent: ctxPayload.BodyForAgent,
|
|
2541
|
-
textForCommands: ctxPayload.CommandBody,
|
|
2542
|
-
raw: post
|
|
2543
|
-
}),
|
|
2544
|
-
resolveTurn: () => ({
|
|
2545
|
-
cfg,
|
|
2546
|
-
channel: "mattermost",
|
|
2547
|
-
accountId: route.accountId,
|
|
2548
|
-
route: {
|
|
2549
|
-
agentId: route.agentId,
|
|
2550
|
-
dmScope: route.dmScope,
|
|
2551
|
-
sessionKey: route.sessionKey
|
|
2552
|
-
},
|
|
2553
|
-
ctxPayload,
|
|
2554
|
-
record: {
|
|
2555
|
-
updateLastRoute: kind === "direct" ? {
|
|
2556
|
-
sessionKey: inboundLastRouteSessionKey,
|
|
2557
|
-
channel: "mattermost",
|
|
2558
|
-
to,
|
|
2559
|
-
accountId: route.accountId,
|
|
2560
|
-
mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
|
|
2561
|
-
ownerRecipient: pinnedMainDmOwner,
|
|
2562
|
-
senderRecipient: normalizeMattermostAllowEntry(senderId),
|
|
2563
|
-
onSkip: ({ ownerRecipient, senderRecipient }) => {
|
|
2564
|
-
logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
|
|
2565
|
-
}
|
|
2566
|
-
} : void 0
|
|
2567
|
-
} : void 0,
|
|
2568
|
-
onRecordError: (err) => {
|
|
2569
|
-
logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
|
|
2570
|
-
}
|
|
2571
|
-
},
|
|
2572
|
-
history: {
|
|
2573
|
-
isGroup: Boolean(historyKey),
|
|
2574
|
-
historyKey: historyKey ?? void 0,
|
|
2575
|
-
historyMap: channelHistories,
|
|
2576
|
-
limit: historyLimit
|
|
2577
|
-
},
|
|
2578
|
-
dispatcherOptions,
|
|
2579
|
-
delivery,
|
|
2580
|
-
replyOptions: {
|
|
2581
|
-
...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
|
|
2582
|
-
allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
|
|
2583
|
-
preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
|
|
2584
|
-
onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
|
|
2585
|
-
disableBlockStreaming: draftPreviewEnabled ? true : typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
|
|
2586
|
-
...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
|
|
2587
|
-
onModelSelected,
|
|
2588
|
-
onPartialReply: (payloadResult) => {
|
|
2589
|
-
if (account.streamingMode !== "progress") return updateDraftFromPartial(payloadResult.text);
|
|
2590
|
-
},
|
|
2591
|
-
onAssistantMessageStart: () => {
|
|
2592
|
-
lastPartialText = "";
|
|
2593
|
-
progressDraft.resetReasoningProgress();
|
|
2594
|
-
if (account.streamingMode === "block") {
|
|
2595
|
-
blockPreviewAssistantMessagePending = true;
|
|
2596
|
-
return;
|
|
2597
|
-
}
|
|
2598
|
-
if (account.streamingMode !== "progress") progressDraft.reset();
|
|
2599
|
-
},
|
|
2600
|
-
onReasoningEnd: () => {
|
|
2601
|
-
lastPartialText = "";
|
|
2602
|
-
progressDraft.resetReasoningProgress();
|
|
2603
|
-
if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
|
|
2604
|
-
},
|
|
2605
|
-
onReasoningStream: async (payloadResult) => {
|
|
2606
|
-
if (account.streamingMode === "progress") {
|
|
2607
|
-
await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
|
|
2608
|
-
return;
|
|
2609
|
-
}
|
|
2610
|
-
if (!lastPartialText) {
|
|
2611
|
-
const boundarySettled = enterBlockPreviewActivity("reasoning");
|
|
2612
|
-
draftStream.update("Thinking…");
|
|
2613
|
-
previewBoundaryController.noteUpdate();
|
|
2614
|
-
await boundarySettled;
|
|
2615
|
-
}
|
|
2616
|
-
},
|
|
2617
|
-
onToolStart: async (payloadValue) => {
|
|
2618
|
-
if (!draftToolProgressEnabled) return;
|
|
2619
|
-
const boundarySettled = enterBlockPreviewActivity("tool");
|
|
2620
|
-
const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
|
|
2621
|
-
event: "tool",
|
|
2622
|
-
itemId: payloadValue.itemId,
|
|
2623
|
-
toolCallId: payloadValue.toolCallId,
|
|
2624
|
-
name: payloadValue.name,
|
|
2625
|
-
phase: payloadValue.phase,
|
|
2626
|
-
args: payloadValue.args
|
|
2627
|
-
}, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
|
|
2628
|
-
previewBoundaryController.noteUpdate();
|
|
2629
|
-
await Promise.all([boundarySettled, progressSettled]);
|
|
2630
|
-
},
|
|
2631
|
-
onItemEvent: async (payloadLocal) => {
|
|
2632
|
-
if (!draftToolProgressEnabled) return;
|
|
2633
|
-
const boundarySettled = enterBlockPreviewActivity("tool");
|
|
2634
|
-
const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
|
|
2635
|
-
event: "item",
|
|
2636
|
-
itemId: payloadLocal.itemId,
|
|
2637
|
-
itemKind: payloadLocal.kind,
|
|
2638
|
-
title: payloadLocal.title,
|
|
2639
|
-
name: payloadLocal.name,
|
|
2640
|
-
phase: payloadLocal.phase,
|
|
2641
|
-
status: payloadLocal.status,
|
|
2642
|
-
summary: payloadLocal.summary,
|
|
2643
|
-
progressText: payloadLocal.progressText,
|
|
2644
|
-
meta: payloadLocal.meta
|
|
2645
|
-
}), { startImmediately: true });
|
|
2646
|
-
previewBoundaryController.noteUpdate();
|
|
2647
|
-
await Promise.all([boundarySettled, progressSettled]);
|
|
2648
|
-
}
|
|
2649
|
-
}
|
|
2650
|
-
})
|
|
2651
|
-
}
|
|
2652
|
-
});
|
|
2653
|
-
} finally {
|
|
2654
|
-
try {
|
|
2655
|
-
await draftStream.stop();
|
|
2656
|
-
} catch (err) {
|
|
2657
|
-
logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
|
|
2658
|
-
}
|
|
2410
|
+
await connectFn();
|
|
2411
|
+
backoff.reset();
|
|
2412
|
+
} catch (err) {
|
|
2413
|
+
if (opts.abortSignal?.aborted) return;
|
|
2414
|
+
outcome = "rejected";
|
|
2415
|
+
error = err;
|
|
2416
|
+
opts.onError?.(err);
|
|
2659
2417
|
}
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
}
|
|
2668
|
-
|
|
2418
|
+
if (opts.abortSignal?.aborted) return;
|
|
2419
|
+
const delayMs = withJitter(backoff.current(), jitterRatio, random);
|
|
2420
|
+
if (!(opts.shouldReconnect?.({
|
|
2421
|
+
attempt,
|
|
2422
|
+
delayMs,
|
|
2423
|
+
outcome,
|
|
2424
|
+
error
|
|
2425
|
+
}) ?? true)) return;
|
|
2426
|
+
opts.onReconnect?.(delayMs);
|
|
2427
|
+
await sleepAbortable(delayMs, opts.abortSignal);
|
|
2428
|
+
if (outcome === "rejected") backoff.increase();
|
|
2429
|
+
attempt++;
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
function createReconnectBackoff(initialDelayMs, maxDelayMs) {
|
|
2433
|
+
let retryDelay = initialDelayMs;
|
|
2434
|
+
return {
|
|
2435
|
+
current: () => retryDelay,
|
|
2436
|
+
reset: () => {
|
|
2437
|
+
retryDelay = initialDelayMs;
|
|
2438
|
+
},
|
|
2439
|
+
increase: () => {
|
|
2440
|
+
retryDelay = Math.min(retryDelay * 2, maxDelayMs);
|
|
2669
2441
|
}
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
if (
|
|
2681
|
-
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
function withJitter(baseMs, jitterRatio, random) {
|
|
2445
|
+
if (jitterRatio <= 0) return baseMs;
|
|
2446
|
+
const normalized = Math.max(0, Math.min(1, random()));
|
|
2447
|
+
const spread = baseMs * jitterRatio;
|
|
2448
|
+
return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
|
|
2449
|
+
}
|
|
2450
|
+
function sleepAbortable(ms, signal) {
|
|
2451
|
+
return new Promise((resolve) => {
|
|
2452
|
+
if (signal?.aborted) {
|
|
2453
|
+
resolve();
|
|
2682
2454
|
return;
|
|
2683
2455
|
}
|
|
2684
|
-
const
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2456
|
+
const onAbort = () => {
|
|
2457
|
+
clearTimeout(timer);
|
|
2458
|
+
resolve();
|
|
2459
|
+
};
|
|
2460
|
+
const timer = setTimeout(() => {
|
|
2461
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2462
|
+
resolve();
|
|
2463
|
+
}, ms);
|
|
2464
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
//#endregion
|
|
2468
|
+
//#region extensions/mattermost/src/mattermost/monitor.ts
|
|
2469
|
+
async function monitorMattermostProvider(opts = {}) {
|
|
2470
|
+
const core = getMattermostRuntime();
|
|
2471
|
+
const runtime = opts.runtime ?? {
|
|
2472
|
+
log: console.log,
|
|
2473
|
+
error: console.error,
|
|
2474
|
+
exit: (code) => {
|
|
2475
|
+
throw new Error(`exit ${code}`);
|
|
2688
2476
|
}
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2477
|
+
};
|
|
2478
|
+
const cfg = opts.config ?? core.config.current();
|
|
2479
|
+
const account = resolveMattermostAccount({
|
|
2480
|
+
cfg,
|
|
2481
|
+
accountId: opts.accountId
|
|
2482
|
+
});
|
|
2483
|
+
const pairing = createChannelPairingController({
|
|
2484
|
+
core,
|
|
2485
|
+
channel: "mattermost",
|
|
2486
|
+
accountId: account.accountId
|
|
2487
|
+
});
|
|
2488
|
+
const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
|
|
2489
|
+
if (!botToken) throw new Error(`Mattermost bot token missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.botToken or MATTERMOST_BOT_TOKEN for default).`);
|
|
2490
|
+
const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
|
|
2491
|
+
if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
|
|
2492
|
+
const client = createMattermostClient({
|
|
2493
|
+
baseUrl,
|
|
2494
|
+
botToken,
|
|
2495
|
+
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
|
|
2496
|
+
});
|
|
2497
|
+
let botUser;
|
|
2498
|
+
await runWithReconnect(async () => {
|
|
2499
|
+
botUser = await fetchMattermostMe(client);
|
|
2500
|
+
}, {
|
|
2501
|
+
abortSignal: opts.abortSignal,
|
|
2502
|
+
jitterRatio: .2,
|
|
2503
|
+
shouldReconnect: ({ outcome }) => outcome === "rejected",
|
|
2504
|
+
onError: (err) => {
|
|
2505
|
+
runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
|
|
2506
|
+
opts.statusSink?.({
|
|
2507
|
+
lastError: String(err),
|
|
2508
|
+
connected: false
|
|
2509
|
+
});
|
|
2510
|
+
},
|
|
2511
|
+
onReconnect: (delayMs) => {
|
|
2512
|
+
runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
|
|
2708
2513
|
}
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2514
|
+
});
|
|
2515
|
+
if (opts.abortSignal?.aborted) return;
|
|
2516
|
+
const botUserId = botUser.id;
|
|
2517
|
+
const botUsername = normalizeOptionalString(botUser.username);
|
|
2518
|
+
runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
|
|
2519
|
+
await registerMattermostMonitorSlashCommands({
|
|
2520
|
+
client,
|
|
2521
|
+
cfg,
|
|
2522
|
+
runtime,
|
|
2523
|
+
account,
|
|
2524
|
+
baseUrl,
|
|
2525
|
+
botUserId
|
|
2526
|
+
});
|
|
2527
|
+
const slashEnabled = getSlashCommandState(account.accountId) != null;
|
|
2528
|
+
setInteractionSecret(account.accountId, botToken);
|
|
2529
|
+
const interactionPath = resolveInteractionCallbackPath(account.accountId);
|
|
2530
|
+
const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
|
|
2531
|
+
gateway: cfg.gateway,
|
|
2532
|
+
interactions: account.config.interactions
|
|
2533
|
+
});
|
|
2534
|
+
setInteractionCallbackUrl(account.accountId, callbackUrl);
|
|
2535
|
+
const allowedInteractionSourceIps = normalizeTrimmedStringList(account.config.interactions?.allowedSourceIps);
|
|
2536
|
+
try {
|
|
2537
|
+
const mmHost = new URL(baseUrl).hostname;
|
|
2538
|
+
const callbackHost = new URL(callbackUrl).hostname;
|
|
2539
|
+
if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} (loopback) while baseUrl is ${baseUrl}. This MAY be unreachable depending on your deployment. If button clicks don't work, set channels.mattermost.interactions.callbackBaseUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
|
|
2540
|
+
if (!isLoopbackHost(callbackHost) && allowedInteractionSourceIps.length === 0) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} without channels.mattermost.interactions.allowedSourceIps. For safety, non-loopback callback sources will be rejected until you allowlist the Mattermost server or trusted ingress IPs.`);
|
|
2541
|
+
} catch {}
|
|
2542
|
+
const logger = core.logging.getChildLogger({ module: "mattermost" });
|
|
2543
|
+
const logVerboseMessage = (message) => {
|
|
2544
|
+
if (core.logging.shouldLogVerbose()) logger.debug?.(message);
|
|
2726
2545
|
};
|
|
2727
|
-
const
|
|
2546
|
+
const mediaMaxBytes = resolveChannelMediaMaxBytes({
|
|
2728
2547
|
cfg,
|
|
2729
|
-
|
|
2548
|
+
resolveChannelLimitMb: () => void 0,
|
|
2549
|
+
accountId: account.accountId
|
|
2550
|
+
}) ?? 8 * 1024 * 1024;
|
|
2551
|
+
const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
|
|
2552
|
+
providerConfigPresent: cfg.channels?.mattermost !== void 0,
|
|
2553
|
+
groupPolicy: account.config.groupPolicy,
|
|
2554
|
+
defaultGroupPolicy: resolveDefaultGroupPolicy(cfg)
|
|
2555
|
+
});
|
|
2556
|
+
warnMissingProviderGroupPolicyFallbackOnce({
|
|
2557
|
+
providerMissingFallbackApplied,
|
|
2558
|
+
providerKey: "mattermost",
|
|
2559
|
+
accountId: account.accountId,
|
|
2560
|
+
log: logVerboseMessage
|
|
2561
|
+
});
|
|
2562
|
+
const monitor = {
|
|
2563
|
+
core,
|
|
2564
|
+
runtime,
|
|
2565
|
+
cfg,
|
|
2566
|
+
account,
|
|
2567
|
+
client,
|
|
2568
|
+
pairing,
|
|
2569
|
+
botUserId,
|
|
2570
|
+
botUsername,
|
|
2571
|
+
groupPolicy,
|
|
2572
|
+
resources: createMattermostMonitorResources({
|
|
2573
|
+
accountId: account.accountId,
|
|
2574
|
+
callbackUrl,
|
|
2575
|
+
client,
|
|
2576
|
+
logger: { debug: (message) => logger.debug?.(String(message)) },
|
|
2577
|
+
mediaMaxBytes,
|
|
2578
|
+
saveRemoteMedia: (params) => core.channel.media.saveRemoteMedia(params),
|
|
2579
|
+
mediaKindFromMime: (contentType) => core.media.mediaKindFromMime(contentType)
|
|
2580
|
+
}),
|
|
2581
|
+
logDebugMessage: (message) => logger.debug?.(message),
|
|
2582
|
+
logVerboseMessage,
|
|
2583
|
+
statusSink: opts.statusSink
|
|
2584
|
+
};
|
|
2585
|
+
const unregisterInteractions = registerMattermostInteractions({
|
|
2586
|
+
monitor,
|
|
2587
|
+
interactionPath,
|
|
2588
|
+
allowedSourceIps: allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"],
|
|
2589
|
+
handleModelPickerInteraction: createMattermostModelPickerInteractionHandler(monitor)
|
|
2730
2590
|
});
|
|
2591
|
+
const handlePost = createMattermostPostHandler(monitor);
|
|
2592
|
+
const handleReactionEvent = createMattermostReactionHandler(monitor);
|
|
2731
2593
|
const debouncer = core.channel.debounce.createInboundDebouncer({
|
|
2732
|
-
debounceMs:
|
|
2594
|
+
debounceMs: core.channel.debounce.resolveInboundDebounceMs({
|
|
2595
|
+
cfg,
|
|
2596
|
+
channel: "mattermost"
|
|
2597
|
+
}),
|
|
2733
2598
|
buildKey: (entry) => {
|
|
2734
2599
|
const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
|
|
2735
2600
|
if (!channelId) return null;
|
|
2736
2601
|
const threadId = normalizeOptionalString(entry.post.root_id);
|
|
2737
|
-
|
|
2738
|
-
return `mattermost:${account.accountId}:${channelId}:${threadKey}`;
|
|
2602
|
+
return `mattermost:${account.accountId}:${channelId}:${threadId ? `thread:${threadId}` : "channel"}`;
|
|
2739
2603
|
},
|
|
2740
2604
|
shouldDebounce: (entry) => {
|
|
2741
|
-
if (entry.post.file_ids
|
|
2605
|
+
if (entry.post.file_ids?.length) return false;
|
|
2742
2606
|
const text = normalizeOptionalString(entry.post.message) ?? "";
|
|
2743
|
-
|
|
2744
|
-
return !core.channel.commands.isControlCommandMessage(text, cfg);
|
|
2607
|
+
return Boolean(text) && !core.channel.commands.isControlCommandMessage(text, cfg);
|
|
2745
2608
|
},
|
|
2746
2609
|
onFlush: async (entries) => {
|
|
2747
2610
|
const last = entries.at(-1);
|
|
2748
2611
|
if (!last) return;
|
|
2749
|
-
const { lifecycle, settle } =
|
|
2612
|
+
const { lifecycle, settle } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
|
|
2750
2613
|
try {
|
|
2751
2614
|
if (entries.length === 1) {
|
|
2752
2615
|
await handlePost(last.post, last.payload, lifecycle);
|
|
2753
2616
|
await settle();
|
|
2754
2617
|
return;
|
|
2755
2618
|
}
|
|
2756
|
-
const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
|
|
2757
2619
|
const mergedPost = {
|
|
2758
2620
|
...last.post,
|
|
2759
|
-
message:
|
|
2621
|
+
message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
|
|
2760
2622
|
file_ids: []
|
|
2761
2623
|
};
|
|
2762
2624
|
await handlePost(mergedPost, last.payload, lifecycle, entries.map((entry) => entry.post.id));
|
|
@@ -2783,23 +2645,18 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2783
2645
|
return { kind: "deferred" };
|
|
2784
2646
|
}
|
|
2785
2647
|
});
|
|
2786
|
-
|
|
2787
|
-
let seq = 1;
|
|
2648
|
+
let sequence = 1;
|
|
2788
2649
|
const connectOnce = createMattermostConnectOnce({
|
|
2789
|
-
wsUrl,
|
|
2650
|
+
wsUrl: `${baseUrl.replace(/^http/i, "ws")}/api/v4/websocket`,
|
|
2790
2651
|
botToken,
|
|
2791
2652
|
abortSignal: opts.abortSignal,
|
|
2792
2653
|
statusSink: opts.statusSink,
|
|
2793
2654
|
runtime,
|
|
2794
2655
|
webSocketFactory: opts.webSocketFactory,
|
|
2795
|
-
nextSeq: () =>
|
|
2796
|
-
getBotUpdateAt: async () =>
|
|
2797
|
-
return (await fetchMattermostMe(client)).update_at ?? 0;
|
|
2798
|
-
},
|
|
2656
|
+
nextSeq: () => sequence++,
|
|
2657
|
+
getBotUpdateAt: async () => (await fetchMattermostMe(client)).update_at ?? 0,
|
|
2799
2658
|
onPosted: ingress.receive,
|
|
2800
|
-
onReaction:
|
|
2801
|
-
await handleReactionEvent(payload);
|
|
2802
|
-
}
|
|
2659
|
+
onReaction: handleReactionEvent
|
|
2803
2660
|
});
|
|
2804
2661
|
let slashShutdownCleanup = null;
|
|
2805
2662
|
if (slashEnabled) {
|
|
@@ -2810,7 +2667,7 @@ async function monitorMattermostProvider(opts = {}) {
|
|
|
2810
2667
|
slashShutdownCleanup = cleanupSlashCommands({
|
|
2811
2668
|
client,
|
|
2812
2669
|
commands,
|
|
2813
|
-
log: (
|
|
2670
|
+
log: (message) => runtime.log?.(message)
|
|
2814
2671
|
}).catch((err) => {
|
|
2815
2672
|
runtime.error?.(`mattermost: slash cleanup failed: ${String(err)}`);
|
|
2816
2673
|
});
|
|
@@ -2849,9 +2706,8 @@ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivate
|
|
|
2849
2706
|
error: "baseUrl missing"
|
|
2850
2707
|
};
|
|
2851
2708
|
const url = `${normalized}/api/v4/users/me`;
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
try {
|
|
2709
|
+
return await runChannelProbe(void 0, async ({ elapsedMs }) => {
|
|
2710
|
+
const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : void 0;
|
|
2855
2711
|
const { response: res, release } = await fetchWithSsrFGuard({
|
|
2856
2712
|
url,
|
|
2857
2713
|
init: { headers: { Authorization: `Bearer ${botToken}` } },
|
|
@@ -2861,35 +2717,32 @@ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivate
|
|
|
2861
2717
|
...deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
|
|
2862
2718
|
...deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}
|
|
2863
2719
|
});
|
|
2720
|
+
const requestElapsedMs = elapsedMs();
|
|
2864
2721
|
try {
|
|
2865
|
-
const elapsedMs = Date.now() - start;
|
|
2866
2722
|
if (!res.ok) {
|
|
2867
2723
|
const detail = await readMattermostError(res);
|
|
2868
2724
|
return {
|
|
2869
2725
|
ok: false,
|
|
2870
2726
|
status: res.status,
|
|
2871
2727
|
error: detail || res.statusText,
|
|
2872
|
-
elapsedMs
|
|
2728
|
+
elapsedMs: requestElapsedMs
|
|
2873
2729
|
};
|
|
2874
2730
|
}
|
|
2875
2731
|
const bot = await readProviderJsonResponse(res, "Mattermost probe /users/me");
|
|
2876
2732
|
return {
|
|
2877
2733
|
ok: true,
|
|
2878
2734
|
status: res.status,
|
|
2879
|
-
elapsedMs,
|
|
2735
|
+
elapsedMs: requestElapsedMs,
|
|
2880
2736
|
bot
|
|
2881
2737
|
};
|
|
2882
2738
|
} finally {
|
|
2883
2739
|
await release();
|
|
2884
2740
|
}
|
|
2885
|
-
}
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
elapsedMs: Date.now() - start
|
|
2891
|
-
};
|
|
2892
|
-
}
|
|
2741
|
+
}, (error) => ({
|
|
2742
|
+
ok: false,
|
|
2743
|
+
status: null,
|
|
2744
|
+
error: formatErrorMessage(error)
|
|
2745
|
+
}));
|
|
2893
2746
|
}
|
|
2894
2747
|
//#endregion
|
|
2895
2748
|
//#region extensions/mattermost/src/mattermost/reactions.ts
|