@openclaw/mattermost 2026.9.6 → 2026.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/icon.png +0 -0
- package/dist/.setup/{channel-plugin-api-CCmaCFdK.mjs → channel-plugin-api-Bc8Qc1-t.mjs} +2 -2
- package/dist/.setup/{channel-plugin-api-CzBhdovL.mjs → channel-plugin-api-DXqHarCt.mjs} +2 -2
- package/dist/.setup/{channel-plugin-runtime-yAOg5GcM.mjs → channel-plugin-runtime-B0CAMiHe.mjs} +122 -160
- package/dist/.setup/channel.runtime-E2B5dNrh.mjs +383 -0
- package/dist/.setup/{client-BSSVve1x.mjs → client-CVeeTqCO.mjs} +18 -39
- package/dist/.setup/doctor-contract-BI6SB2cd.mjs +175 -0
- package/dist/.setup/{interactions-rBQWCbK8.mjs → interactions-DMSZYnEx.mjs} +170 -80
- package/dist/.setup/{channel.runtime-CihvzY84.mjs → monitor-BZyzPkkb.mjs} +172 -628
- package/dist/.setup/{monitor-auth-CCpN0z_f.mjs → monitor-auth-aZ0b1gqx.mjs} +9 -14
- package/dist/.setup/{normalize-DM54w7ud.mjs → normalize-BCjtmxtp.mjs} +8 -17
- package/dist/.setup/rolldown-runtime-BBjsoOtd.mjs +27 -0
- package/dist/.setup/send-ClgX-usq.mjs +438 -0
- package/dist/.setup/{slash-state-DfnmzXMr.mjs → slash-state-Dni1XNc1.mjs} +144 -781
- package/dist/api.js +2 -2
- package/dist/channel-plugin-api.js +2 -2
- package/dist/channel-plugin-runtime.js +1 -1
- package/dist/doctor-contract-api.js +1 -1
- package/dist/policy-api.js +1 -1
- package/dist/runtime-api.js +2 -23
- package/dist/setup-entry.js +1 -1
- package/dist/slash-route-api.js +1 -1
- package/openclaw.plugin.json +20 -0
- package/package.json +4 -4
- package/dist/.setup/doctor-contract-mvORF4f6.mjs +0 -18
|
@@ -1,29 +1,24 @@
|
|
|
1
|
+
import { l as isWildcardBindHost } from "./interactions-DMSZYnEx.mjs";
|
|
1
2
|
import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { r as createMattermostClient, s as fetchMattermostChannel, v as sendMattermostTyping } from "./client-CVeeTqCO.mjs";
|
|
4
|
+
import { D as sendHttpRequestRejection, b as logTypingFailure, h as isRequestBodyLimitError, i as normalizeMattermostAllowList, l as buildPreparedModelsProviderData, p as createWebhookInFlightLimiter, t as authorizeMattermostCommandInvocation, x as readRequestBodyWithLimit } from "./monitor-auth-aZ0b1gqx.mjs";
|
|
5
|
+
import { a as resolveMattermostPresentation, i as requiresMattermostMediaUpload } from "./normalize-BCjtmxtp.mjs";
|
|
6
|
+
import { t as sendMessageMattermost } from "./send-ClgX-usq.mjs";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
7
8
|
import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
|
|
8
|
-
import { asFiniteNumber,
|
|
9
|
+
import { asFiniteNumber, normalizeOptionalString, normalizeStringifiedOptionalString, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
9
10
|
import { createAcceptedChannelDeliveryResult, createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
|
|
10
11
|
import { asDateTimestampMs, parseStrictInteger, resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
|
|
11
12
|
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
12
|
-
import { createMessageReceiptFromOutboundResults, listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
|
|
13
13
|
import { resolveStoredModelOverride } from "openclaw/plugin-sdk/command-auth-native";
|
|
14
|
-
import { resolveChannelMediaMaxBytes } from "openclaw/plugin-sdk/account-helpers";
|
|
15
14
|
import { deliverTextOrMediaReply, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
16
|
-
import { FormatCapabilityProfile, convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
|
|
17
|
-
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
|
|
18
|
-
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
19
|
-
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
20
15
|
import { truncateUtf16Safe, truncateUtf8Prefix } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
21
16
|
import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
|
|
22
|
-
import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
|
|
23
17
|
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
18
|
+
import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
|
|
19
|
+
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
|
|
20
|
+
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
21
|
+
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
27
22
|
const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
|
|
28
23
|
/**
|
|
29
24
|
* Built-in OpenClaw commands to register as native slash commands.
|
|
@@ -31,107 +26,64 @@ const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
|
|
|
31
26
|
*/
|
|
32
27
|
const DEFAULT_COMMAND_SPECS = [
|
|
33
28
|
{
|
|
34
|
-
trigger: "oc_status",
|
|
35
29
|
originalName: "status",
|
|
36
|
-
description: "Show session status (model, usage, uptime)"
|
|
37
|
-
autoComplete: true
|
|
30
|
+
description: "Show session status (model, usage, uptime)"
|
|
38
31
|
},
|
|
39
32
|
{
|
|
40
|
-
trigger: "oc_model",
|
|
41
33
|
originalName: "model",
|
|
42
34
|
description: "View or change the current model",
|
|
43
|
-
autoComplete: true,
|
|
44
35
|
autoCompleteHint: "[model-name] [--runtime runtime]"
|
|
45
36
|
},
|
|
46
37
|
{
|
|
47
|
-
trigger: "oc_models",
|
|
48
38
|
originalName: "models",
|
|
49
39
|
description: "Browse available models",
|
|
50
|
-
autoComplete: true,
|
|
51
40
|
autoCompleteHint: "[provider]"
|
|
52
41
|
},
|
|
53
42
|
{
|
|
54
|
-
trigger: "oc_new",
|
|
55
43
|
originalName: "new",
|
|
56
|
-
description: "Start a new conversation session"
|
|
57
|
-
autoComplete: true
|
|
44
|
+
description: "Start a new conversation session"
|
|
58
45
|
},
|
|
59
46
|
{
|
|
60
|
-
trigger: "oc_help",
|
|
61
47
|
originalName: "help",
|
|
62
|
-
description: "Show available commands"
|
|
63
|
-
autoComplete: true
|
|
48
|
+
description: "Show available commands"
|
|
64
49
|
},
|
|
65
50
|
{
|
|
66
|
-
trigger: "oc_think",
|
|
67
51
|
originalName: "think",
|
|
68
52
|
description: "Set thinking/reasoning level",
|
|
69
|
-
autoComplete: true,
|
|
70
53
|
autoCompleteHint: "[off|low|medium|high]"
|
|
71
54
|
},
|
|
72
55
|
{
|
|
73
|
-
trigger: "oc_reasoning",
|
|
74
56
|
originalName: "reasoning",
|
|
75
57
|
description: "Toggle reasoning mode",
|
|
76
|
-
autoComplete: true,
|
|
77
58
|
autoCompleteHint: "[on|off]"
|
|
78
59
|
},
|
|
79
60
|
{
|
|
80
|
-
trigger: "oc_verbose",
|
|
81
61
|
originalName: "verbose",
|
|
82
62
|
description: "Toggle verbose mode",
|
|
83
|
-
autoComplete: true,
|
|
84
63
|
autoCompleteHint: "[on|off]"
|
|
85
64
|
},
|
|
86
65
|
{
|
|
87
|
-
trigger: "oc_queue",
|
|
88
66
|
originalName: "queue",
|
|
89
67
|
description: "Adjust active-run queue behavior",
|
|
90
|
-
autoComplete: true,
|
|
91
68
|
autoCompleteHint: "[steer|followup|collect|interrupt] [debounce:2s] [cap:N] [drop:old|new|summarize]"
|
|
92
69
|
}
|
|
93
|
-
]
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
70
|
+
].map((spec) => Object.assign(spec, {
|
|
71
|
+
trigger: `oc_${spec.originalName}`,
|
|
72
|
+
autoComplete: true
|
|
73
|
+
}));
|
|
97
74
|
async function listMattermostCommands(client, teamId, init) {
|
|
98
75
|
return await client.request(`/commands?team_id=${encodeURIComponent(teamId)}&custom_only=true`, init);
|
|
99
76
|
}
|
|
100
|
-
/**
|
|
101
|
-
* Get a custom slash command by id.
|
|
102
|
-
*/
|
|
103
77
|
async function getMattermostCommand(client, commandId, init) {
|
|
104
78
|
return await client.request(`/commands/${encodeURIComponent(commandId)}`, init);
|
|
105
79
|
}
|
|
106
|
-
/**
|
|
107
|
-
* Create a custom slash command on a Mattermost team.
|
|
108
|
-
*/
|
|
109
|
-
async function createMattermostCommand(client, params) {
|
|
110
|
-
return await client.request("/commands", {
|
|
111
|
-
method: "POST",
|
|
112
|
-
body: JSON.stringify(params)
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Delete a custom slash command.
|
|
117
|
-
*/
|
|
118
80
|
async function deleteMattermostCommand(client, commandId) {
|
|
119
|
-
await client.request(`/commands/${encodeURIComponent(commandId)}`, {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
* Update an existing custom slash command.
|
|
123
|
-
*/
|
|
124
|
-
async function updateMattermostCommand(client, params) {
|
|
125
|
-
return await client.request(`/commands/${encodeURIComponent(params.id)}`, {
|
|
126
|
-
method: "PUT",
|
|
127
|
-
body: JSON.stringify(params)
|
|
81
|
+
await client.request(`/commands/${encodeURIComponent(commandId)}`, {
|
|
82
|
+
method: "DELETE",
|
|
83
|
+
discardResponse: true
|
|
128
84
|
});
|
|
129
85
|
}
|
|
130
|
-
/**
|
|
131
|
-
* Register all OpenClaw slash commands for a given team.
|
|
132
|
-
* Skips commands that are already registered with the same trigger + callback URL.
|
|
133
|
-
* Returns the list of newly created command IDs.
|
|
134
|
-
*/
|
|
86
|
+
/** Reconcile owned commands without modifying another integration's trigger. */
|
|
135
87
|
async function registerSlashCommands(params) {
|
|
136
88
|
const { client, teamId, creatorUserId, callbackUrl, commands, log } = params;
|
|
137
89
|
const normalizedCreatorUserId = creatorUserId.trim();
|
|
@@ -154,48 +106,47 @@ async function registerSlashCommands(params) {
|
|
|
154
106
|
const description = truncateUtf8Prefix(spec.description, MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES);
|
|
155
107
|
const existingForTrigger = existingByTrigger.get(spec.trigger) ?? [];
|
|
156
108
|
const ownedCommands = existingForTrigger.filter((cmd) => cmd.creator_id?.trim() === normalizedCreatorUserId);
|
|
157
|
-
|
|
158
|
-
if (ownedCommands.length === 0 && foreignCommands.length > 0) {
|
|
109
|
+
if (ownedCommands.length === 0 && existingForTrigger.length > 0) {
|
|
159
110
|
log?.(`mattermost: trigger /${spec.trigger} already used by non-OpenClaw command(s); skipping to avoid mutating external integrations`);
|
|
160
111
|
continue;
|
|
161
112
|
}
|
|
162
113
|
if (ownedCommands.length > 1) log?.(`mattermost: multiple owned commands found for /${spec.trigger}; using the first and leaving extras untouched`);
|
|
163
114
|
const existingCmd = ownedCommands[0];
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
115
|
+
const command = {
|
|
116
|
+
team_id: teamId,
|
|
117
|
+
trigger: spec.trigger,
|
|
118
|
+
method: "P",
|
|
119
|
+
url: callbackUrl,
|
|
120
|
+
description,
|
|
121
|
+
auto_complete: spec.autoComplete,
|
|
122
|
+
auto_complete_desc: description,
|
|
123
|
+
auto_complete_hint: spec.autoCompleteHint
|
|
124
|
+
};
|
|
125
|
+
const recordCommand = (receipt, managed) => {
|
|
167
126
|
registered.push({
|
|
168
|
-
id:
|
|
127
|
+
id: receipt.id,
|
|
169
128
|
trigger: spec.trigger,
|
|
170
129
|
teamId,
|
|
171
|
-
token:
|
|
130
|
+
token: receipt.token,
|
|
172
131
|
url: callbackUrl,
|
|
173
|
-
managed
|
|
132
|
+
managed
|
|
174
133
|
});
|
|
134
|
+
};
|
|
135
|
+
if (existingCmd?.url === callbackUrl && existingCmd.method === "P") {
|
|
136
|
+
log?.(`mattermost: command /${spec.trigger} already registered (id=${existingCmd.id})`);
|
|
137
|
+
recordCommand(existingCmd, false);
|
|
175
138
|
continue;
|
|
176
139
|
}
|
|
177
|
-
if (existingCmd
|
|
140
|
+
if (existingCmd) {
|
|
178
141
|
log?.(`mattermost: command /${spec.trigger} exists with different callback settings; updating (id=${existingCmd.id})`);
|
|
179
142
|
try {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
auto_complete: spec.autoComplete,
|
|
188
|
-
auto_complete_desc: description,
|
|
189
|
-
auto_complete_hint: spec.autoCompleteHint
|
|
190
|
-
});
|
|
191
|
-
registered.push({
|
|
192
|
-
id: updated.id,
|
|
193
|
-
trigger: spec.trigger,
|
|
194
|
-
teamId,
|
|
195
|
-
token: updated.token,
|
|
196
|
-
url: callbackUrl,
|
|
197
|
-
managed: false
|
|
198
|
-
});
|
|
143
|
+
recordCommand(await client.request(`/commands/${encodeURIComponent(existingCmd.id)}`, {
|
|
144
|
+
method: "PUT",
|
|
145
|
+
body: JSON.stringify({
|
|
146
|
+
id: existingCmd.id,
|
|
147
|
+
...command
|
|
148
|
+
})
|
|
149
|
+
}), false);
|
|
199
150
|
continue;
|
|
200
151
|
} catch (err) {
|
|
201
152
|
log?.(`mattermost: failed to update command /${spec.trigger} (id=${existingCmd.id}): ${String(err)}`);
|
|
@@ -209,34 +160,18 @@ async function registerSlashCommands(params) {
|
|
|
209
160
|
}
|
|
210
161
|
}
|
|
211
162
|
try {
|
|
212
|
-
const created = await
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
method: "P",
|
|
216
|
-
url: callbackUrl,
|
|
217
|
-
description,
|
|
218
|
-
auto_complete: spec.autoComplete,
|
|
219
|
-
auto_complete_desc: description,
|
|
220
|
-
auto_complete_hint: spec.autoCompleteHint
|
|
163
|
+
const created = await client.request("/commands", {
|
|
164
|
+
method: "POST",
|
|
165
|
+
body: JSON.stringify(command)
|
|
221
166
|
});
|
|
222
167
|
log?.(`mattermost: registered command /${spec.trigger} (id=${created.id})`);
|
|
223
|
-
|
|
224
|
-
id: created.id,
|
|
225
|
-
trigger: spec.trigger,
|
|
226
|
-
teamId,
|
|
227
|
-
token: created.token,
|
|
228
|
-
url: callbackUrl,
|
|
229
|
-
managed: true
|
|
230
|
-
});
|
|
168
|
+
recordCommand(created, true);
|
|
231
169
|
} catch (err) {
|
|
232
170
|
log?.(`mattermost: failed to register command /${spec.trigger}: ${String(err)}`);
|
|
233
171
|
}
|
|
234
172
|
}
|
|
235
173
|
return registered;
|
|
236
174
|
}
|
|
237
|
-
/**
|
|
238
|
-
* Clean up all registered slash commands.
|
|
239
|
-
*/
|
|
240
175
|
async function cleanupSlashCommands(params) {
|
|
241
176
|
const { client, commands, log } = params;
|
|
242
177
|
for (const cmd of commands) {
|
|
@@ -249,53 +184,34 @@ async function cleanupSlashCommands(params) {
|
|
|
249
184
|
}
|
|
250
185
|
}
|
|
251
186
|
}
|
|
252
|
-
/**
|
|
253
|
-
* Parse a Mattermost slash command callback payload from a URL-encoded or JSON body.
|
|
254
|
-
*/
|
|
255
187
|
function parseSlashCommandPayload(body, contentType) {
|
|
256
188
|
if (!body) return null;
|
|
257
189
|
try {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
const
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
channel_id: channelId,
|
|
271
|
-
channel_name: typeof parsed.channel_name === "string" ? parsed.channel_name : void 0,
|
|
272
|
-
user_id: userId,
|
|
273
|
-
user_name: typeof parsed.user_name === "string" ? parsed.user_name : void 0,
|
|
274
|
-
command,
|
|
275
|
-
text: typeof parsed.text === "string" ? parsed.text : "",
|
|
276
|
-
trigger_id: typeof parsed.trigger_id === "string" ? parsed.trigger_id : void 0,
|
|
277
|
-
response_url: typeof parsed.response_url === "string" ? parsed.response_url : void 0
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
const params = new URLSearchParams(body);
|
|
281
|
-
const token = params.get("token");
|
|
282
|
-
const teamId = params.get("team_id");
|
|
283
|
-
const channelId = params.get("channel_id");
|
|
284
|
-
const userId = params.get("user_id");
|
|
285
|
-
const command = params.get("command");
|
|
190
|
+
const json = contentType?.includes("application/json");
|
|
191
|
+
const parsed = json ? JSON.parse(body) : void 0;
|
|
192
|
+
const form = json ? void 0 : new URLSearchParams(body);
|
|
193
|
+
const read = (key) => {
|
|
194
|
+
const value = form ? form.get(key) : parsed?.[key];
|
|
195
|
+
return typeof value === "string" ? value : void 0;
|
|
196
|
+
};
|
|
197
|
+
const token = read("token");
|
|
198
|
+
const teamId = read("team_id");
|
|
199
|
+
const channelId = read("channel_id");
|
|
200
|
+
const userId = read("user_id");
|
|
201
|
+
const command = read("command");
|
|
286
202
|
if (!token || !teamId || !channelId || !userId || !command) return null;
|
|
287
203
|
return {
|
|
288
204
|
token,
|
|
289
205
|
team_id: teamId,
|
|
290
|
-
team_domain:
|
|
206
|
+
team_domain: read("team_domain"),
|
|
291
207
|
channel_id: channelId,
|
|
292
|
-
channel_name:
|
|
208
|
+
channel_name: read("channel_name"),
|
|
293
209
|
user_id: userId,
|
|
294
|
-
user_name:
|
|
210
|
+
user_name: read("user_name"),
|
|
295
211
|
command,
|
|
296
|
-
text:
|
|
297
|
-
trigger_id:
|
|
298
|
-
response_url:
|
|
212
|
+
text: read("text") ?? "",
|
|
213
|
+
trigger_id: read("trigger_id"),
|
|
214
|
+
response_url: read("response_url")
|
|
299
215
|
};
|
|
300
216
|
} catch {
|
|
301
217
|
return null;
|
|
@@ -332,13 +248,8 @@ function resolveSlashCommandConfig(raw) {
|
|
|
332
248
|
};
|
|
333
249
|
}
|
|
334
250
|
function isSlashCommandsEnabled(config) {
|
|
335
|
-
|
|
336
|
-
if (config.native === false) return false;
|
|
337
|
-
return false;
|
|
251
|
+
return config.native === true;
|
|
338
252
|
}
|
|
339
|
-
/**
|
|
340
|
-
* Build the callback URL that Mattermost will POST to when a command is invoked.
|
|
341
|
-
*/
|
|
342
253
|
function resolveCallbackUrl(params) {
|
|
343
254
|
if (params.config.callbackUrl) return params.config.callbackUrl;
|
|
344
255
|
let host = params.gatewayHost && !isWildcardBindHost(params.gatewayHost) ? params.gatewayHost : "localhost";
|
|
@@ -369,16 +280,8 @@ function splitModelRef(modelRef) {
|
|
|
369
280
|
model
|
|
370
281
|
};
|
|
371
282
|
}
|
|
372
|
-
function readContextString(context, key, fallback = "") {
|
|
373
|
-
return readStringField(context, key) ?? fallback;
|
|
374
|
-
}
|
|
375
|
-
function readContextNumber(context, key) {
|
|
376
|
-
const value = context[key];
|
|
377
|
-
return asFiniteNumber(value) ?? parseStrictInteger(value);
|
|
378
|
-
}
|
|
379
283
|
function normalizePage(value) {
|
|
380
|
-
|
|
381
|
-
return Math.max(1, Math.floor(value));
|
|
284
|
+
return Math.max(1, Math.floor(asFiniteNumber(value) ?? 1));
|
|
382
285
|
}
|
|
383
286
|
function paginateItems(items, page, pageSize = MODELS_PAGE_SIZE) {
|
|
384
287
|
const totalPages = Math.max(1, Math.ceil(items.length / pageSize));
|
|
@@ -393,16 +296,6 @@ function paginateItems(items, page, pageSize = MODELS_PAGE_SIZE) {
|
|
|
393
296
|
totalItems: items.length
|
|
394
297
|
};
|
|
395
298
|
}
|
|
396
|
-
function buildContext(state) {
|
|
397
|
-
return {
|
|
398
|
-
[MATTERMOST_MODEL_PICKER_CONTEXT_KEY]: true,
|
|
399
|
-
...state
|
|
400
|
-
};
|
|
401
|
-
}
|
|
402
|
-
function buildButtonId(state) {
|
|
403
|
-
const digest = createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 12);
|
|
404
|
-
return `${ACTION_IDS[state.action]}${digest}`;
|
|
405
|
-
}
|
|
406
299
|
function buildButton(params) {
|
|
407
300
|
const baseState = params.action === "providers" || params.action === "back" ? {
|
|
408
301
|
action: params.action,
|
|
@@ -419,11 +312,15 @@ function buildButton(params) {
|
|
|
419
312
|
page: normalizePage(params.page),
|
|
420
313
|
model: normalizeStringifiedOptionalString(params.model) ?? ""
|
|
421
314
|
};
|
|
315
|
+
const digest = createHash("sha256").update(JSON.stringify(baseState)).digest("hex").slice(0, 12);
|
|
422
316
|
return {
|
|
423
|
-
id:
|
|
317
|
+
id: `${ACTION_IDS[baseState.action]}${digest}`,
|
|
424
318
|
text: params.text,
|
|
425
319
|
...params.style ? { style: params.style } : {},
|
|
426
|
-
context:
|
|
320
|
+
context: {
|
|
321
|
+
[MATTERMOST_MODEL_PICKER_CONTEXT_KEY]: true,
|
|
322
|
+
...baseState
|
|
323
|
+
}
|
|
427
324
|
};
|
|
428
325
|
}
|
|
429
326
|
function getProviderModels(data, provider) {
|
|
@@ -447,15 +344,15 @@ function resolveMattermostModelPickerEntry(commandText) {
|
|
|
447
344
|
}
|
|
448
345
|
function parseMattermostModelPickerContext(context) {
|
|
449
346
|
if (!context || context[MATTERMOST_MODEL_PICKER_CONTEXT_KEY] !== true) return null;
|
|
450
|
-
const ownerUserId = normalizeOptionalString(
|
|
451
|
-
const action = normalizeOptionalString(
|
|
347
|
+
const ownerUserId = normalizeOptionalString(context.ownerUserId) ?? "";
|
|
348
|
+
const action = normalizeOptionalString(context.action) ?? "";
|
|
452
349
|
if (!ownerUserId) return null;
|
|
453
350
|
if (action === "providers" || action === "back") return {
|
|
454
351
|
action,
|
|
455
352
|
ownerUserId
|
|
456
353
|
};
|
|
457
|
-
const provider = normalizeProviderId(
|
|
458
|
-
const page =
|
|
354
|
+
const provider = normalizeProviderId(readStringField(context, "provider") ?? "");
|
|
355
|
+
const page = asFiniteNumber(context.page) ?? parseStrictInteger(context.page);
|
|
459
356
|
if (!provider) return null;
|
|
460
357
|
if (action === "list") return {
|
|
461
358
|
action,
|
|
@@ -464,7 +361,7 @@ function parseMattermostModelPickerContext(context) {
|
|
|
464
361
|
page: normalizePage(page)
|
|
465
362
|
};
|
|
466
363
|
if (action === "select") {
|
|
467
|
-
const model = normalizeOptionalString(
|
|
364
|
+
const model = normalizeOptionalString(context.model) ?? "";
|
|
468
365
|
if (!model) return null;
|
|
469
366
|
return {
|
|
470
367
|
action,
|
|
@@ -485,18 +382,15 @@ function resolveMattermostModelPickerCurrentModel(params) {
|
|
|
485
382
|
const fallback = `${params.data.resolvedDefault.provider}/${params.data.resolvedDefault.model}`;
|
|
486
383
|
try {
|
|
487
384
|
const storePath = resolveStorePath(params.cfg.session?.store, { agentId: params.route.agentId });
|
|
488
|
-
const
|
|
385
|
+
const loadSessionEntry = (sessionKey) => getSessionEntry({
|
|
489
386
|
storePath,
|
|
490
|
-
sessionKey
|
|
387
|
+
sessionKey,
|
|
491
388
|
...params.readConsistency === "latest" ? { readConsistency: "latest" } : {}
|
|
492
389
|
});
|
|
390
|
+
const sessionEntry = loadSessionEntry(params.route.sessionKey);
|
|
493
391
|
const override = resolveStoredModelOverride({
|
|
494
392
|
sessionEntry,
|
|
495
|
-
loadSessionEntry
|
|
496
|
-
storePath,
|
|
497
|
-
sessionKey,
|
|
498
|
-
...params.readConsistency === "latest" ? { readConsistency: "latest" } : {}
|
|
499
|
-
}),
|
|
393
|
+
loadSessionEntry,
|
|
500
394
|
sessionKey: params.route.sessionKey,
|
|
501
395
|
parentSessionKey: sessionEntry?.parentSessionKey,
|
|
502
396
|
defaultProvider: params.data.resolvedDefault.provider
|
|
@@ -674,448 +568,6 @@ async function deliverMattermostReplyPayload(params) {
|
|
|
674
568
|
};
|
|
675
569
|
}
|
|
676
570
|
//#endregion
|
|
677
|
-
//#region extensions/mattermost/src/mattermost/target-resolution.ts
|
|
678
|
-
const MATTERMOST_OPAQUE_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
679
|
-
const MATTERMOST_OPAQUE_TARGET_CACHE_TTL_MS = 3e5;
|
|
680
|
-
const mattermostOpaqueTargetCache = /* @__PURE__ */ new Map();
|
|
681
|
-
function cacheMattermostOpaqueTarget(key, kind) {
|
|
682
|
-
mattermostOpaqueTargetCache.set(key, {
|
|
683
|
-
kind,
|
|
684
|
-
expiresAt: Date.now() + MATTERMOST_OPAQUE_TARGET_CACHE_TTL_MS
|
|
685
|
-
});
|
|
686
|
-
pruneMapToMaxSize(mattermostOpaqueTargetCache, MATTERMOST_OPAQUE_TARGET_CACHE_MAX_ENTRIES);
|
|
687
|
-
}
|
|
688
|
-
function getCachedMattermostOpaqueTargetKind(key) {
|
|
689
|
-
const cached = mattermostOpaqueTargetCache.get(key);
|
|
690
|
-
if (!cached) return;
|
|
691
|
-
if (cached.expiresAt <= Date.now()) {
|
|
692
|
-
mattermostOpaqueTargetCache.delete(key);
|
|
693
|
-
return;
|
|
694
|
-
}
|
|
695
|
-
return cached.kind;
|
|
696
|
-
}
|
|
697
|
-
function cacheKey$1(baseUrl, token, id) {
|
|
698
|
-
return `${baseUrl}::${token}::${id}`;
|
|
699
|
-
}
|
|
700
|
-
/** Mattermost IDs are 26-character lowercase alphanumeric strings. */
|
|
701
|
-
function isMattermostId(value) {
|
|
702
|
-
return /^[a-z0-9]{26}$/.test(value);
|
|
703
|
-
}
|
|
704
|
-
function parseMattermostTarget(raw) {
|
|
705
|
-
const trimmed = raw.trim();
|
|
706
|
-
if (!trimmed) throw new Error("Recipient is required for Mattermost sends");
|
|
707
|
-
const lower = normalizeLowercaseStringOrEmpty(trimmed);
|
|
708
|
-
if (lower.startsWith("channel:")) {
|
|
709
|
-
const id = trimmed.slice(8).trim();
|
|
710
|
-
if (!id) throw new Error("Channel id is required for Mattermost sends");
|
|
711
|
-
if (id.startsWith("#")) {
|
|
712
|
-
const name = id.slice(1).trim();
|
|
713
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
714
|
-
return {
|
|
715
|
-
kind: "channel-name",
|
|
716
|
-
name
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
if (!isMattermostId(id)) return {
|
|
720
|
-
kind: "channel-name",
|
|
721
|
-
name: id
|
|
722
|
-
};
|
|
723
|
-
return {
|
|
724
|
-
kind: "channel",
|
|
725
|
-
id
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
if (lower.startsWith("user:")) {
|
|
729
|
-
const id = trimmed.slice(5).trim();
|
|
730
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
731
|
-
return {
|
|
732
|
-
kind: "user",
|
|
733
|
-
id
|
|
734
|
-
};
|
|
735
|
-
}
|
|
736
|
-
if (lower.startsWith("mattermost:")) {
|
|
737
|
-
const id = trimmed.slice(11).trim();
|
|
738
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
739
|
-
return {
|
|
740
|
-
kind: "user",
|
|
741
|
-
id
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
if (trimmed.startsWith("@")) {
|
|
745
|
-
const username = trimmed.slice(1).trim();
|
|
746
|
-
if (!username) throw new Error("Username is required for Mattermost sends");
|
|
747
|
-
return {
|
|
748
|
-
kind: "user",
|
|
749
|
-
username
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
if (trimmed.startsWith("#")) {
|
|
753
|
-
const name = trimmed.slice(1).trim();
|
|
754
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
755
|
-
return {
|
|
756
|
-
kind: "channel-name",
|
|
757
|
-
name
|
|
758
|
-
};
|
|
759
|
-
}
|
|
760
|
-
if (!isMattermostId(trimmed)) return {
|
|
761
|
-
kind: "channel-name",
|
|
762
|
-
name: trimmed
|
|
763
|
-
};
|
|
764
|
-
return {
|
|
765
|
-
kind: "channel",
|
|
766
|
-
id: trimmed
|
|
767
|
-
};
|
|
768
|
-
}
|
|
769
|
-
function isExplicitMattermostTarget(raw) {
|
|
770
|
-
const trimmed = raw.trim();
|
|
771
|
-
if (!trimmed) return false;
|
|
772
|
-
return /^(channel|user|mattermost):/i.test(trimmed) || trimmed.startsWith("@") || trimmed.startsWith("#");
|
|
773
|
-
}
|
|
774
|
-
async function resolveMattermostOpaqueTarget(params) {
|
|
775
|
-
const input = params.input.trim();
|
|
776
|
-
if (!input || isExplicitMattermostTarget(input) || !isMattermostId(input)) return null;
|
|
777
|
-
let client;
|
|
778
|
-
if ("client" in params) client = params.client;
|
|
779
|
-
else {
|
|
780
|
-
const account = resolveMattermostAccount({
|
|
781
|
-
cfg: params.cfg,
|
|
782
|
-
accountId: params.accountId
|
|
783
|
-
});
|
|
784
|
-
if (!account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
|
|
785
|
-
const token = normalizeOptionalString(account.botToken);
|
|
786
|
-
const baseUrl = normalizeMattermostBaseUrl(account.baseUrl);
|
|
787
|
-
if (!token || !baseUrl) return null;
|
|
788
|
-
client = createMattermostClient({
|
|
789
|
-
baseUrl,
|
|
790
|
-
botToken: token,
|
|
791
|
-
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
|
|
792
|
-
});
|
|
793
|
-
}
|
|
794
|
-
const key = cacheKey$1(client.baseUrl, client.token, input);
|
|
795
|
-
const cachedKind = getCachedMattermostOpaqueTargetKind(key);
|
|
796
|
-
if (cachedKind) return {
|
|
797
|
-
kind: cachedKind,
|
|
798
|
-
id: input,
|
|
799
|
-
to: cachedKind === "user" ? `user:${input}` : `channel:${input}`
|
|
800
|
-
};
|
|
801
|
-
try {
|
|
802
|
-
await fetchMattermostUser(client, input);
|
|
803
|
-
cacheMattermostOpaqueTarget(key, "user");
|
|
804
|
-
return {
|
|
805
|
-
kind: "user",
|
|
806
|
-
id: input,
|
|
807
|
-
to: `user:${input}`
|
|
808
|
-
};
|
|
809
|
-
} catch (err) {
|
|
810
|
-
if (parseMattermostApiStatus(err) !== 404) return {
|
|
811
|
-
kind: "channel",
|
|
812
|
-
id: input,
|
|
813
|
-
to: `channel:${input}`
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
try {
|
|
817
|
-
const channel = await fetchMattermostChannel(client, input);
|
|
818
|
-
const channelKind = resolveMattermostTrustedChatKind({ channelType: channel.type }) === "group" ? "group" : "channel";
|
|
819
|
-
cacheMattermostOpaqueTarget(key, channelKind);
|
|
820
|
-
return {
|
|
821
|
-
kind: channelKind,
|
|
822
|
-
id: input,
|
|
823
|
-
to: `channel:${input}`
|
|
824
|
-
};
|
|
825
|
-
} catch {
|
|
826
|
-
return {
|
|
827
|
-
kind: "channel",
|
|
828
|
-
id: input,
|
|
829
|
-
to: `channel:${input}`
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
//#endregion
|
|
834
|
-
//#region extensions/mattermost/src/mattermost/send.ts
|
|
835
|
-
const MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES = 64;
|
|
836
|
-
const MATTERMOST_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
837
|
-
const MATTERMOST_FORMAT_PROFILE = FormatCapabilityProfile.define({
|
|
838
|
-
mechanism: "markdown",
|
|
839
|
-
chunk: {
|
|
840
|
-
limit: 16383,
|
|
841
|
-
unit: "chars"
|
|
842
|
-
}
|
|
843
|
-
});
|
|
844
|
-
function renderMattermostMarkdown(markdown, tableMode) {
|
|
845
|
-
return tableMode === "off" && MATTERMOST_FORMAT_PROFILE.constructs.table === "native" ? markdown : convertMarkdownTables(markdown, tableMode);
|
|
846
|
-
}
|
|
847
|
-
const botUserCache = /* @__PURE__ */ new Map();
|
|
848
|
-
const userByNameCache = /* @__PURE__ */ new Map();
|
|
849
|
-
const channelByNameCache = /* @__PURE__ */ new Map();
|
|
850
|
-
const dmChannelCache = /* @__PURE__ */ new Map();
|
|
851
|
-
function cacheOutboundEntry(cache, key, value, maxEntries) {
|
|
852
|
-
cache.delete(key);
|
|
853
|
-
cache.set(key, value);
|
|
854
|
-
pruneMapToMaxSize(cache, maxEntries);
|
|
855
|
-
}
|
|
856
|
-
const getCore = () => getMattermostRuntime();
|
|
857
|
-
function createMattermostSendReceipt(params) {
|
|
858
|
-
return createMessageReceiptFromOutboundResults({
|
|
859
|
-
kind: params.kind,
|
|
860
|
-
...params.replyToId ? { replyToId: params.replyToId } : {},
|
|
861
|
-
results: [{
|
|
862
|
-
channel: "mattermost",
|
|
863
|
-
messageId: params.messageId,
|
|
864
|
-
channelId: params.channelId
|
|
865
|
-
}]
|
|
866
|
-
});
|
|
867
|
-
}
|
|
868
|
-
function resolveMattermostReceiptKind(params) {
|
|
869
|
-
if (params.fileIds?.length) return "media";
|
|
870
|
-
if (params.buttons?.length || params.props) return "card";
|
|
871
|
-
return "text";
|
|
872
|
-
}
|
|
873
|
-
function recordMattermostOutboundActivity(accountId) {
|
|
874
|
-
try {
|
|
875
|
-
getCore().channel.activity.record({
|
|
876
|
-
channel: "mattermost",
|
|
877
|
-
accountId,
|
|
878
|
-
direction: "outbound"
|
|
879
|
-
});
|
|
880
|
-
} catch (error) {
|
|
881
|
-
if (!(error instanceof Error) || error.message !== "Mattermost runtime not initialized") throw error;
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
function cacheKey(baseUrl, token) {
|
|
885
|
-
return `${baseUrl}::${token}`;
|
|
886
|
-
}
|
|
887
|
-
function normalizeMessage(text, mediaUrl) {
|
|
888
|
-
return [normalizeOptionalString(text) ?? "", normalizeOptionalString(mediaUrl)].filter(Boolean).join("\n");
|
|
889
|
-
}
|
|
890
|
-
function isHttpUrl(value) {
|
|
891
|
-
return /^https?:\/\//i.test(value);
|
|
892
|
-
}
|
|
893
|
-
async function resolveBotUser(client) {
|
|
894
|
-
const key = cacheKey(client.baseUrl, client.token);
|
|
895
|
-
const cached = botUserCache.get(key);
|
|
896
|
-
if (cached) return cached;
|
|
897
|
-
const user = await fetchMattermostMe(client);
|
|
898
|
-
cacheOutboundEntry(botUserCache, key, user, MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES);
|
|
899
|
-
return user;
|
|
900
|
-
}
|
|
901
|
-
async function resolveUserIdByUsername(params) {
|
|
902
|
-
const { client, username } = params;
|
|
903
|
-
const key = `${cacheKey(client.baseUrl, client.token)}::${normalizeLowercaseStringOrEmpty(username)}`;
|
|
904
|
-
const cached = userByNameCache.get(key);
|
|
905
|
-
if (cached?.id) return cached.id;
|
|
906
|
-
const user = await fetchMattermostUserByUsername(client, username);
|
|
907
|
-
cacheOutboundEntry(userByNameCache, key, user, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
|
|
908
|
-
return user.id;
|
|
909
|
-
}
|
|
910
|
-
async function resolveChannelIdByName(params) {
|
|
911
|
-
const { client, name } = params;
|
|
912
|
-
const key = `${cacheKey(client.baseUrl, client.token)}::channel::${normalizeLowercaseStringOrEmpty(name)}`;
|
|
913
|
-
const cached = channelByNameCache.get(key);
|
|
914
|
-
if (cached) return cached;
|
|
915
|
-
const me = await fetchMattermostMe(client);
|
|
916
|
-
const teams = await fetchMattermostUserTeams(client, me.id);
|
|
917
|
-
for (const team of teams) try {
|
|
918
|
-
const channel = await fetchMattermostChannelByName(client, team.id, name);
|
|
919
|
-
if (channel?.id) {
|
|
920
|
-
cacheOutboundEntry(channelByNameCache, key, channel.id, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
|
|
921
|
-
return channel.id;
|
|
922
|
-
}
|
|
923
|
-
} catch (error) {
|
|
924
|
-
if (parseMattermostApiStatus(error) !== 404) throw error;
|
|
925
|
-
}
|
|
926
|
-
throw new Error(`Mattermost channel "#${name}" not found in any team the bot belongs to`);
|
|
927
|
-
}
|
|
928
|
-
function mergeDmRetryOptions(base, override) {
|
|
929
|
-
const merged = {
|
|
930
|
-
maxRetries: override?.maxRetries ?? base?.maxRetries,
|
|
931
|
-
initialDelayMs: override?.initialDelayMs ?? base?.initialDelayMs,
|
|
932
|
-
maxDelayMs: override?.maxDelayMs ?? base?.maxDelayMs,
|
|
933
|
-
timeoutMs: override?.timeoutMs ?? base?.timeoutMs,
|
|
934
|
-
onRetry: override?.onRetry
|
|
935
|
-
};
|
|
936
|
-
if (merged.maxRetries === void 0 && merged.initialDelayMs === void 0 && merged.maxDelayMs === void 0 && merged.timeoutMs === void 0 && merged.onRetry === void 0) return;
|
|
937
|
-
return merged;
|
|
938
|
-
}
|
|
939
|
-
async function resolveTargetChannelId(params) {
|
|
940
|
-
if (params.target.kind === "channel") return params.target.id;
|
|
941
|
-
if (params.target.kind === "channel-name") return await resolveChannelIdByName({
|
|
942
|
-
client: params.client,
|
|
943
|
-
name: params.target.name
|
|
944
|
-
});
|
|
945
|
-
const userId = params.target.id ? params.target.id : await resolveUserIdByUsername({
|
|
946
|
-
client: params.client,
|
|
947
|
-
username: params.target.username ?? ""
|
|
948
|
-
});
|
|
949
|
-
const dmKey = `${cacheKey(params.client.baseUrl, params.client.token)}::dm::${userId}`;
|
|
950
|
-
const cachedDm = dmChannelCache.get(dmKey);
|
|
951
|
-
if (cachedDm) return cachedDm;
|
|
952
|
-
const botUser = await resolveBotUser(params.client);
|
|
953
|
-
const channel = await createMattermostDirectChannelWithRetry(params.client, [botUser.id, userId], {
|
|
954
|
-
...params.dmRetryOptions,
|
|
955
|
-
onRetry: (attempt, delayMs, error) => {
|
|
956
|
-
params.dmRetryOptions?.onRetry?.(attempt, delayMs, error);
|
|
957
|
-
if (params.logger) params.logger.warn?.(`DM channel creation retry ${attempt} after ${delayMs}ms: ${error.message}`);
|
|
958
|
-
}
|
|
959
|
-
});
|
|
960
|
-
cacheOutboundEntry(dmChannelCache, dmKey, channel.id, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
|
|
961
|
-
return channel.id;
|
|
962
|
-
}
|
|
963
|
-
async function resolveMattermostSendContext(to, opts) {
|
|
964
|
-
const core = getCore();
|
|
965
|
-
const logger = core.logging.getChildLogger({ module: "mattermost" });
|
|
966
|
-
if (!opts?.cfg) throw new Error("Mattermost send requires a resolved runtime config. Load and resolve config at the command or gateway boundary, then pass cfg through the runtime path.");
|
|
967
|
-
const cfg = requireRuntimeConfig(opts.cfg, "Mattermost send");
|
|
968
|
-
const account = resolveMattermostAccount({
|
|
969
|
-
cfg,
|
|
970
|
-
accountId: opts.accountId
|
|
971
|
-
});
|
|
972
|
-
const token = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
|
|
973
|
-
if (!token) throw new Error(`Mattermost bot token missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.botToken or MATTERMOST_BOT_TOKEN for default).`);
|
|
974
|
-
const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
|
|
975
|
-
if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
|
|
976
|
-
const client = createMattermostClient({
|
|
977
|
-
baseUrl,
|
|
978
|
-
botToken: token,
|
|
979
|
-
allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config),
|
|
980
|
-
assertRequestCurrent: opts.assertDirectAdapterHandoff
|
|
981
|
-
});
|
|
982
|
-
const dmRetryOptions = mergeDmRetryOptions(account.config.dmChannelRetry ? {
|
|
983
|
-
maxRetries: account.config.dmChannelRetry.maxRetries,
|
|
984
|
-
initialDelayMs: account.config.dmChannelRetry.initialDelayMs,
|
|
985
|
-
maxDelayMs: account.config.dmChannelRetry.maxDelayMs,
|
|
986
|
-
timeoutMs: account.config.dmChannelRetry.timeoutMs
|
|
987
|
-
} : void 0, opts.dmRetryOptions);
|
|
988
|
-
let channelId;
|
|
989
|
-
try {
|
|
990
|
-
const trimmedTo = normalizeOptionalString(to) ?? "";
|
|
991
|
-
channelId = await resolveTargetChannelId({
|
|
992
|
-
target: parseMattermostTarget((await resolveMattermostOpaqueTarget({
|
|
993
|
-
input: trimmedTo,
|
|
994
|
-
client
|
|
995
|
-
}))?.to ?? trimmedTo),
|
|
996
|
-
client,
|
|
997
|
-
dmRetryOptions,
|
|
998
|
-
logger: core.logging.shouldLogVerbose() ? logger : void 0
|
|
999
|
-
});
|
|
1000
|
-
} catch (error) {
|
|
1001
|
-
client.assertRequestCurrent?.();
|
|
1002
|
-
throw error;
|
|
1003
|
-
}
|
|
1004
|
-
return {
|
|
1005
|
-
cfg,
|
|
1006
|
-
accountId: account.accountId,
|
|
1007
|
-
client,
|
|
1008
|
-
channelId,
|
|
1009
|
-
mediaMaxBytes: resolveChannelMediaMaxBytes({
|
|
1010
|
-
cfg,
|
|
1011
|
-
accountId: account.accountId,
|
|
1012
|
-
resolveChannelLimitMb: () => account.config.mediaMaxMb
|
|
1013
|
-
})
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
async function sendMessageMattermost(to, text, opts) {
|
|
1017
|
-
const core = getCore();
|
|
1018
|
-
const logger = core.logging.getChildLogger({ module: "mattermost" });
|
|
1019
|
-
const { cfg, accountId, client, channelId, mediaMaxBytes } = await resolveMattermostSendContext(to, opts);
|
|
1020
|
-
client.assertRequestCurrent?.();
|
|
1021
|
-
let props = opts.props;
|
|
1022
|
-
if (!props && Array.isArray(opts.buttons) && opts.buttons.length > 0) {
|
|
1023
|
-
setInteractionSecret(accountId, client.token);
|
|
1024
|
-
props = buildButtonProps({
|
|
1025
|
-
callbackUrl: resolveInteractionCallbackUrl(accountId, {
|
|
1026
|
-
gateway: cfg.gateway,
|
|
1027
|
-
interactions: resolveMattermostAccount({
|
|
1028
|
-
cfg,
|
|
1029
|
-
accountId
|
|
1030
|
-
}).config?.interactions
|
|
1031
|
-
}),
|
|
1032
|
-
accountId,
|
|
1033
|
-
channelId,
|
|
1034
|
-
buttons: opts.buttons,
|
|
1035
|
-
text: opts.attachmentText
|
|
1036
|
-
});
|
|
1037
|
-
}
|
|
1038
|
-
let message = normalizeOptionalString(text) ?? "";
|
|
1039
|
-
let fileIds;
|
|
1040
|
-
let uploadError;
|
|
1041
|
-
const mediaUrl = opts.mediaUrl?.trim();
|
|
1042
|
-
if (mediaUrl) try {
|
|
1043
|
-
const media = await loadOutboundMediaFromUrl(mediaUrl, {
|
|
1044
|
-
maxBytes: mediaMaxBytes,
|
|
1045
|
-
mediaLocalRoots: opts.mediaLocalRoots,
|
|
1046
|
-
mediaReadFile: opts.mediaReadFile,
|
|
1047
|
-
workspaceDir: opts.workspaceDir
|
|
1048
|
-
});
|
|
1049
|
-
fileIds = [(await uploadMattermostFile(client, {
|
|
1050
|
-
channelId,
|
|
1051
|
-
buffer: media.buffer,
|
|
1052
|
-
fileName: media.fileName ?? `upload${extensionForMime(media.contentType) ?? ""}`,
|
|
1053
|
-
contentType: media.contentType ?? void 0
|
|
1054
|
-
})).id];
|
|
1055
|
-
} catch (err) {
|
|
1056
|
-
client.assertRequestCurrent?.();
|
|
1057
|
-
uploadError = err instanceof Error ? err : new Error(String(err));
|
|
1058
|
-
if (opts.requireMediaUpload || mediaMaxBytes !== void 0) throw new Error(`Mattermost media upload failed: ${uploadError.message}`, { cause: err });
|
|
1059
|
-
if (core.logging.shouldLogVerbose()) logger.debug?.(`mattermost send: media upload failed, falling back to URL text: ${String(err)}`);
|
|
1060
|
-
message = normalizeMessage(message, isHttpUrl(mediaUrl) ? mediaUrl : "");
|
|
1061
|
-
}
|
|
1062
|
-
if (message) {
|
|
1063
|
-
const tableMode = resolveMarkdownTableMode({
|
|
1064
|
-
cfg,
|
|
1065
|
-
channel: "mattermost",
|
|
1066
|
-
accountId
|
|
1067
|
-
});
|
|
1068
|
-
message = renderMattermostMarkdown(message, tableMode);
|
|
1069
|
-
}
|
|
1070
|
-
if (!message && (!fileIds || fileIds.length === 0)) {
|
|
1071
|
-
if (uploadError) throw new Error(`Mattermost media upload failed: ${uploadError.message}`, { cause: uploadError });
|
|
1072
|
-
throw new Error("Mattermost message is empty");
|
|
1073
|
-
}
|
|
1074
|
-
client.assertRequestCurrent?.();
|
|
1075
|
-
try {
|
|
1076
|
-
await opts.onPlatformSendDispatch?.();
|
|
1077
|
-
} catch (error) {
|
|
1078
|
-
client.assertRequestCurrent?.();
|
|
1079
|
-
throw error;
|
|
1080
|
-
}
|
|
1081
|
-
const post = await createMattermostPost(client, {
|
|
1082
|
-
channelId,
|
|
1083
|
-
message,
|
|
1084
|
-
rootId: opts.replyToId,
|
|
1085
|
-
fileIds,
|
|
1086
|
-
props
|
|
1087
|
-
});
|
|
1088
|
-
const messageId = post.id;
|
|
1089
|
-
const receipt = createMattermostSendReceipt({
|
|
1090
|
-
messageId,
|
|
1091
|
-
channelId,
|
|
1092
|
-
kind: resolveMattermostReceiptKind({
|
|
1093
|
-
fileIds,
|
|
1094
|
-
buttons: opts.buttons,
|
|
1095
|
-
props
|
|
1096
|
-
}),
|
|
1097
|
-
replyToId: opts.replyToId
|
|
1098
|
-
});
|
|
1099
|
-
const result = {
|
|
1100
|
-
messageId,
|
|
1101
|
-
channelId,
|
|
1102
|
-
receipt,
|
|
1103
|
-
content: post.message ?? message
|
|
1104
|
-
};
|
|
1105
|
-
try {
|
|
1106
|
-
await opts.onDeliveryResult?.(result);
|
|
1107
|
-
recordMattermostOutboundActivity(accountId);
|
|
1108
|
-
} catch (error) {
|
|
1109
|
-
throw createChannelPartialDeliveryError(error, {
|
|
1110
|
-
messageIds: listMessageReceiptPlatformIds(receipt),
|
|
1111
|
-
receipt,
|
|
1112
|
-
visibleReplySent: true,
|
|
1113
|
-
content: result.content
|
|
1114
|
-
});
|
|
1115
|
-
}
|
|
1116
|
-
return result;
|
|
1117
|
-
}
|
|
1118
|
-
//#endregion
|
|
1119
571
|
//#region extensions/mattermost/src/mattermost/slash-http.ts
|
|
1120
572
|
const MAX_BODY_BYTES = 65536;
|
|
1121
573
|
const BODY_READ_TIMEOUT_MS = 5e3;
|
|
@@ -1137,17 +589,7 @@ const SECRET_LOG_KEYS = /* @__PURE__ */ new Set([
|
|
|
1137
589
|
"refresh_token",
|
|
1138
590
|
"token"
|
|
1139
591
|
]);
|
|
1140
|
-
|
|
1141
|
-
* Read the full request body as a string.
|
|
1142
|
-
*/
|
|
1143
|
-
function readBody(req, maxBytes, timeoutMs = BODY_READ_TIMEOUT_MS) {
|
|
1144
|
-
return readRequestBodyWithLimit(req, {
|
|
1145
|
-
maxBytes,
|
|
1146
|
-
timeoutMs,
|
|
1147
|
-
destroyOnLimit: false
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
function sendJsonResponse(res, status, body) {
|
|
592
|
+
function sendSlashCommandResponse(res, status, body) {
|
|
1151
593
|
res.statusCode = status;
|
|
1152
594
|
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1153
595
|
res.end(JSON.stringify(body));
|
|
@@ -1191,9 +633,11 @@ function commandLookupKey(client, registered, accountId) {
|
|
|
1191
633
|
return `${client.apiBaseUrl}:${accountId}:${registered.teamId}:${registered.id}`;
|
|
1192
634
|
}
|
|
1193
635
|
function clearMattermostSlashCommandValidationCacheForAccount(accountId) {
|
|
1194
|
-
for (const
|
|
1195
|
-
|
|
1196
|
-
|
|
636
|
+
for (const cache of [
|
|
637
|
+
commandValidationFailureCache,
|
|
638
|
+
commandLookupInflight,
|
|
639
|
+
commandValidationLookupRateLimit
|
|
640
|
+
]) for (const [key, entry] of cache) if (entry.accountId === accountId) cache.delete(key);
|
|
1197
641
|
}
|
|
1198
642
|
function sweepCommandValidationFailureCache(now = Date.now()) {
|
|
1199
643
|
const validNow = asDateTimestampMs(now);
|
|
@@ -1205,22 +649,11 @@ function sweepCommandValidationFailureCache(now = Date.now()) {
|
|
|
1205
649
|
const expiresAt = asDateTimestampMs(entry.expiresAt);
|
|
1206
650
|
if (expiresAt === void 0 || expiresAt <= validNow) commandValidationFailureCache.delete(key);
|
|
1207
651
|
}
|
|
1208
|
-
|
|
1209
|
-
const oldestKey = commandValidationFailureCache.keys().next().value;
|
|
1210
|
-
if (!oldestKey) break;
|
|
1211
|
-
commandValidationFailureCache.delete(oldestKey);
|
|
1212
|
-
}
|
|
652
|
+
pruneMapToMaxSize(commandValidationFailureCache, COMMAND_VALIDATION_FAILURE_CACHE_MAX_KEYS);
|
|
1213
653
|
}
|
|
1214
654
|
function hasCachedCommandValidationFailure(key, now = Date.now()) {
|
|
1215
655
|
sweepCommandValidationFailureCache(now);
|
|
1216
|
-
|
|
1217
|
-
if (validNow === void 0) return false;
|
|
1218
|
-
const cached = commandValidationFailureCache.get(key);
|
|
1219
|
-
if (!cached) return false;
|
|
1220
|
-
const expiresAt = asDateTimestampMs(cached.expiresAt);
|
|
1221
|
-
if (expiresAt !== void 0 && expiresAt > validNow) return true;
|
|
1222
|
-
commandValidationFailureCache.delete(key);
|
|
1223
|
-
return false;
|
|
656
|
+
return commandValidationFailureCache.has(key);
|
|
1224
657
|
}
|
|
1225
658
|
function cacheCommandValidationFailure(key, accountId) {
|
|
1226
659
|
const now = Date.now();
|
|
@@ -1246,11 +679,7 @@ function sweepCommandValidationLookupRateLimit(now = Date.now()) {
|
|
|
1246
679
|
const updatedAt = asDateTimestampMs(entry.updatedAt);
|
|
1247
680
|
if (updatedAt === void 0 || validNow - updatedAt > staleAfterMs) commandValidationLookupRateLimit.delete(key);
|
|
1248
681
|
}
|
|
1249
|
-
|
|
1250
|
-
const oldestKey = commandValidationLookupRateLimit.keys().next().value;
|
|
1251
|
-
if (!oldestKey) break;
|
|
1252
|
-
commandValidationLookupRateLimit.delete(oldestKey);
|
|
1253
|
-
}
|
|
682
|
+
pruneMapToMaxSize(commandValidationLookupRateLimit, COMMAND_VALIDATION_LOOKUP_RATE_LIMIT_MAX_KEYS);
|
|
1254
683
|
}
|
|
1255
684
|
function reserveCommandValidationLookup(params) {
|
|
1256
685
|
const rawNow = params.now ?? Date.now();
|
|
@@ -1432,12 +861,6 @@ async function authorizeSlashInvocation(params) {
|
|
|
1432
861
|
denyResponse: void 0
|
|
1433
862
|
};
|
|
1434
863
|
}
|
|
1435
|
-
/**
|
|
1436
|
-
* Create the HTTP request handler for Mattermost slash command callbacks.
|
|
1437
|
-
*
|
|
1438
|
-
* This handler is registered as a plugin HTTP route and receives POSTs
|
|
1439
|
-
* from the Mattermost server when a user invokes a registered slash command.
|
|
1440
|
-
*/
|
|
1441
864
|
function createSlashCommandHttpHandler(params) {
|
|
1442
865
|
const { account, cfg, runtime, registeredCommands, triggerMap, log, bodyTimeoutMs } = params;
|
|
1443
866
|
return async (req, res, bufferedBody, onRequestAuthenticated) => {
|
|
@@ -1449,7 +872,11 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1449
872
|
}
|
|
1450
873
|
let body;
|
|
1451
874
|
try {
|
|
1452
|
-
body = bufferedBody ?? await
|
|
875
|
+
body = bufferedBody ?? await readRequestBodyWithLimit(req, {
|
|
876
|
+
maxBytes: MAX_BODY_BYTES,
|
|
877
|
+
timeoutMs: bodyTimeoutMs ?? BODY_READ_TIMEOUT_MS,
|
|
878
|
+
destroyOnLimit: false
|
|
879
|
+
});
|
|
1453
880
|
} catch (error) {
|
|
1454
881
|
if (isRequestBodyLimitError(error, "REQUEST_BODY_TIMEOUT")) {
|
|
1455
882
|
await sendHttpRequestRejection(req, res, 408, "Request body timeout");
|
|
@@ -1461,7 +888,7 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1461
888
|
const contentType = req.headers["content-type"] ?? "";
|
|
1462
889
|
const payload = parseSlashCommandPayload(body, contentType);
|
|
1463
890
|
if (!payload) {
|
|
1464
|
-
|
|
891
|
+
sendSlashCommandResponse(res, 400, {
|
|
1465
892
|
response_type: "ephemeral",
|
|
1466
893
|
text: "Invalid slash command payload."
|
|
1467
894
|
});
|
|
@@ -1472,7 +899,7 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1472
899
|
payload
|
|
1473
900
|
});
|
|
1474
901
|
if (!registeredCommand || !safeEqualSecret(payload.token, registeredCommand.token)) {
|
|
1475
|
-
|
|
902
|
+
sendSlashCommandResponse(res, 401, {
|
|
1476
903
|
response_type: "ephemeral",
|
|
1477
904
|
text: "Unauthorized: invalid command token."
|
|
1478
905
|
});
|
|
@@ -1490,7 +917,7 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1490
917
|
payload,
|
|
1491
918
|
log
|
|
1492
919
|
})) {
|
|
1493
|
-
|
|
920
|
+
sendSlashCommandResponse(res, 401, {
|
|
1494
921
|
response_type: "ephemeral",
|
|
1495
922
|
text: "Unauthorized: invalid command token."
|
|
1496
923
|
});
|
|
@@ -1513,14 +940,14 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1513
940
|
log
|
|
1514
941
|
});
|
|
1515
942
|
if (!auth.ok) {
|
|
1516
|
-
|
|
943
|
+
sendSlashCommandResponse(res, 200, auth.denyResponse ?? {
|
|
1517
944
|
response_type: "ephemeral",
|
|
1518
945
|
text: "Unauthorized."
|
|
1519
946
|
});
|
|
1520
947
|
return;
|
|
1521
948
|
}
|
|
1522
949
|
log?.(`mattermost: slash command /${sanitizeMattermostLogValue(trigger)} from ${sanitizeMattermostLogValue(senderName)} in ${sanitizeMattermostLogValue(channelId)}`);
|
|
1523
|
-
|
|
950
|
+
sendSlashCommandResponse(res, 200, {
|
|
1524
951
|
response_type: "ephemeral",
|
|
1525
952
|
text: "Processing..."
|
|
1526
953
|
});
|
|
@@ -1538,7 +965,6 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1538
965
|
triggerId: payload.trigger_id,
|
|
1539
966
|
kind: auth.kind,
|
|
1540
967
|
chatType: auth.chatType,
|
|
1541
|
-
channelName: auth.channelName,
|
|
1542
968
|
channelDisplay: auth.channelDisplay,
|
|
1543
969
|
roomLabel: auth.roomLabel,
|
|
1544
970
|
commandAuthorized: auth.commandAuthorized,
|
|
@@ -1547,7 +973,8 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1547
973
|
} catch (err) {
|
|
1548
974
|
log?.(`mattermost: slash command handler error: ${sanitizeCommandLookupError(err)}`);
|
|
1549
975
|
try {
|
|
1550
|
-
|
|
976
|
+
const to = `channel:${channelId}`;
|
|
977
|
+
await sendMessageMattermost(to, "Sorry, something went wrong processing that command.", {
|
|
1551
978
|
cfg,
|
|
1552
979
|
accountId: account.accountId
|
|
1553
980
|
});
|
|
@@ -1556,7 +983,7 @@ function createSlashCommandHttpHandler(params) {
|
|
|
1556
983
|
};
|
|
1557
984
|
}
|
|
1558
985
|
async function handleSlashCommandAsync(params) {
|
|
1559
|
-
const { account, cfg, runtime, client, commandText, channelId, senderId, senderName, teamId, kind, chatType,
|
|
986
|
+
const { account, cfg, runtime, client, commandText, channelId, senderId, senderName, teamId, kind, chatType, channelDisplay, roomLabel, commandAuthorized, triggerId, log } = params;
|
|
1560
987
|
const core = getMattermostRuntime();
|
|
1561
988
|
const route = core.channel.routing.resolveAgentRoute({
|
|
1562
989
|
cfg,
|
|
@@ -1585,24 +1012,19 @@ async function handleSlashCommandAsync(params) {
|
|
|
1585
1012
|
});
|
|
1586
1013
|
return;
|
|
1587
1014
|
}
|
|
1588
|
-
const
|
|
1589
|
-
cfg,
|
|
1590
|
-
route,
|
|
1591
|
-
data
|
|
1592
|
-
});
|
|
1593
|
-
const view = pickerEntry.kind === "summary" ? renderMattermostModelSummaryView({
|
|
1594
|
-
ownerUserId: senderId,
|
|
1595
|
-
currentModel
|
|
1596
|
-
}) : pickerEntry.kind === "providers" ? renderMattermostProviderPickerView({
|
|
1597
|
-
ownerUserId: senderId,
|
|
1598
|
-
data,
|
|
1599
|
-
currentModel
|
|
1600
|
-
}) : renderMattermostModelsPickerView({
|
|
1015
|
+
const viewParams = {
|
|
1601
1016
|
ownerUserId: senderId,
|
|
1602
1017
|
data,
|
|
1018
|
+
currentModel: resolveMattermostModelPickerCurrentModel({
|
|
1019
|
+
cfg,
|
|
1020
|
+
route,
|
|
1021
|
+
data
|
|
1022
|
+
})
|
|
1023
|
+
};
|
|
1024
|
+
const view = pickerEntry.kind === "summary" ? renderMattermostModelSummaryView(viewParams) : pickerEntry.kind === "providers" ? renderMattermostProviderPickerView(viewParams) : renderMattermostModelsPickerView({
|
|
1025
|
+
...viewParams,
|
|
1603
1026
|
provider: pickerEntry.provider,
|
|
1604
|
-
page: 1
|
|
1605
|
-
currentModel
|
|
1027
|
+
page: 1
|
|
1606
1028
|
});
|
|
1607
1029
|
await sendMessageMattermost(`channel:${channelId}`, [data.refreshWarning, view.text].filter(Boolean).join("\n\n"), {
|
|
1608
1030
|
cfg,
|
|
@@ -1694,17 +1116,6 @@ async function handleSlashCommandAsync(params) {
|
|
|
1694
1116
|
}
|
|
1695
1117
|
//#endregion
|
|
1696
1118
|
//#region extensions/mattermost/src/mattermost/slash-state.ts
|
|
1697
|
-
/**
|
|
1698
|
-
* Shared state for Mattermost slash commands.
|
|
1699
|
-
*
|
|
1700
|
-
* Bridges the plugin registration phase (HTTP route) with the monitor phase
|
|
1701
|
-
* (command registration with MM API). The HTTP handler needs to know which
|
|
1702
|
-
* tokens are known for fast-path routing, and the monitor needs to store
|
|
1703
|
-
* registered command IDs.
|
|
1704
|
-
*
|
|
1705
|
-
* State is kept per-account so that multi-account deployments don't
|
|
1706
|
-
* overwrite each other's tokens, registered commands, or handlers.
|
|
1707
|
-
*/
|
|
1708
1119
|
const MULTI_ACCOUNT_BODY_MAX_BYTES = 65536;
|
|
1709
1120
|
const MULTI_ACCOUNT_BODY_TIMEOUT_MS = 5e3;
|
|
1710
1121
|
const slashRouteInFlightLimiter = createWebhookInFlightLimiter();
|
|
@@ -1736,9 +1147,9 @@ function resolveSlashRouteInFlightKey(authorization) {
|
|
|
1736
1147
|
for (const state of accountStates.values()) for (const commandToken of state.commandTokens) matched = safeEqualSecret(token, commandToken) || matched;
|
|
1737
1148
|
return matched ? `${SLASH_AUTHENTICATED_IN_FLIGHT_KEY}:${createHash("sha256").update(`${SLASH_AUTHENTICATED_IN_FLIGHT_KEY}:${token}`).digest("hex")}` : SLASH_ROUTE_IN_FLIGHT_KEY;
|
|
1738
1149
|
}
|
|
1739
|
-
function
|
|
1150
|
+
function resolveSlashHandler(source, matchesState) {
|
|
1740
1151
|
const matches = [];
|
|
1741
|
-
for (const [accountId, state] of accountStates) if (state.
|
|
1152
|
+
for (const [accountId, state] of accountStates) if (state.handler && matchesState(state)) matches.push({
|
|
1742
1153
|
accountId,
|
|
1743
1154
|
handler: state.handler
|
|
1744
1155
|
});
|
|
@@ -1748,45 +1159,22 @@ function resolveSlashHandlerForToken(token) {
|
|
|
1748
1159
|
if (!match) return { kind: "none" };
|
|
1749
1160
|
return {
|
|
1750
1161
|
kind: "single",
|
|
1751
|
-
source
|
|
1162
|
+
source,
|
|
1752
1163
|
handler: match.handler,
|
|
1753
1164
|
accountIds: [match.accountId]
|
|
1754
1165
|
};
|
|
1755
1166
|
}
|
|
1756
1167
|
return {
|
|
1757
1168
|
kind: "ambiguous",
|
|
1758
|
-
source
|
|
1169
|
+
source,
|
|
1759
1170
|
accountIds: matches.map((entry) => entry.accountId)
|
|
1760
1171
|
};
|
|
1761
1172
|
}
|
|
1762
1173
|
function resolveSlashHandlerForCommand(params) {
|
|
1763
1174
|
const trigger = normalizeSlashCommandTrigger(params.command);
|
|
1764
1175
|
if (!trigger) return { kind: "none" };
|
|
1765
|
-
|
|
1766
|
-
for (const [accountId, state] of accountStates) if (state.handler && state.registeredCommands.some((cmd) => cmd.teamId === params.teamId && cmd.trigger === trigger)) matches.push({
|
|
1767
|
-
accountId,
|
|
1768
|
-
handler: state.handler
|
|
1769
|
-
});
|
|
1770
|
-
if (matches.length === 0) return { kind: "none" };
|
|
1771
|
-
if (matches.length === 1) {
|
|
1772
|
-
const match = matches[0];
|
|
1773
|
-
if (!match) return { kind: "none" };
|
|
1774
|
-
return {
|
|
1775
|
-
kind: "single",
|
|
1776
|
-
source: "command",
|
|
1777
|
-
handler: match.handler,
|
|
1778
|
-
accountIds: [match.accountId]
|
|
1779
|
-
};
|
|
1780
|
-
}
|
|
1781
|
-
return {
|
|
1782
|
-
kind: "ambiguous",
|
|
1783
|
-
source: "command",
|
|
1784
|
-
accountIds: matches.map((entry) => entry.accountId)
|
|
1785
|
-
};
|
|
1176
|
+
return resolveSlashHandler("command", (state) => state.registeredCommands.some((cmd) => cmd.teamId === params.teamId && cmd.trigger === trigger));
|
|
1786
1177
|
}
|
|
1787
|
-
/**
|
|
1788
|
-
* Get the slash command state for a specific account, or null if not activated.
|
|
1789
|
-
*/
|
|
1790
1178
|
function getSlashCommandState(accountId) {
|
|
1791
1179
|
return accountStates.get(accountId) ?? null;
|
|
1792
1180
|
}
|
|
@@ -1797,7 +1185,6 @@ function getSlashCommandState(accountId) {
|
|
|
1797
1185
|
function activateSlashCommands(params) {
|
|
1798
1186
|
const { account, commandTokens, registeredCommands, triggerMap, api, log } = params;
|
|
1799
1187
|
const accountId = account.accountId;
|
|
1800
|
-
const tokenSet = new Set(commandTokens);
|
|
1801
1188
|
const handler = createSlashCommandHttpHandler({
|
|
1802
1189
|
account,
|
|
1803
1190
|
cfg: api.cfg,
|
|
@@ -1807,35 +1194,20 @@ function activateSlashCommands(params) {
|
|
|
1807
1194
|
log
|
|
1808
1195
|
});
|
|
1809
1196
|
accountStates.set(accountId, {
|
|
1810
|
-
commandTokens:
|
|
1197
|
+
commandTokens: new Set(commandTokens),
|
|
1811
1198
|
registeredCommands,
|
|
1812
|
-
handler
|
|
1813
|
-
account,
|
|
1814
|
-
triggerMap: triggerMap ?? /* @__PURE__ */ new Map()
|
|
1199
|
+
handler
|
|
1815
1200
|
});
|
|
1816
1201
|
log?.(`mattermost: slash commands activated for account ${accountId} (${registeredCommands.length} commands)`);
|
|
1817
1202
|
}
|
|
1818
|
-
/**
|
|
1819
|
-
* Deactivate slash commands for a specific account (on shutdown/disconnect).
|
|
1820
|
-
*/
|
|
1821
1203
|
function deactivateSlashCommands(accountId) {
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
accountStates.delete(accountId);
|
|
1830
|
-
}
|
|
1831
|
-
} else {
|
|
1832
|
-
for (const [stateAccountId, state] of accountStates) {
|
|
1833
|
-
state.commandTokens.clear();
|
|
1834
|
-
state.registeredCommands = [];
|
|
1835
|
-
state.handler = null;
|
|
1836
|
-
clearMattermostSlashCommandValidationCacheForAccount(stateAccountId);
|
|
1837
|
-
}
|
|
1838
|
-
accountStates.clear();
|
|
1204
|
+
for (const [stateAccountId, state] of accountStates) {
|
|
1205
|
+
if (accountId && stateAccountId !== accountId) continue;
|
|
1206
|
+
state.commandTokens.clear();
|
|
1207
|
+
state.registeredCommands = [];
|
|
1208
|
+
state.handler = null;
|
|
1209
|
+
clearMattermostSlashCommandValidationCacheForAccount(stateAccountId);
|
|
1210
|
+
accountStates.delete(stateAccountId);
|
|
1839
1211
|
}
|
|
1840
1212
|
}
|
|
1841
1213
|
/**
|
|
@@ -1867,23 +1239,19 @@ function registerSlashCommandRoute(api) {
|
|
|
1867
1239
|
}
|
|
1868
1240
|
const dispatchRoute = async (req, res, onRequestAuthenticated) => {
|
|
1869
1241
|
if (accountStates.size === 0) {
|
|
1870
|
-
res
|
|
1871
|
-
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1872
|
-
res.end(JSON.stringify({
|
|
1242
|
+
sendSlashCommandResponse(res, 503, {
|
|
1873
1243
|
response_type: "ephemeral",
|
|
1874
1244
|
text: "Slash commands are not yet initialized. Please try again in a moment."
|
|
1875
|
-
})
|
|
1245
|
+
});
|
|
1876
1246
|
return;
|
|
1877
1247
|
}
|
|
1878
1248
|
if (accountStates.size === 1) {
|
|
1879
1249
|
const state = accountStates.values().next().value;
|
|
1880
1250
|
if (!state?.handler) {
|
|
1881
|
-
res
|
|
1882
|
-
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1883
|
-
res.end(JSON.stringify({
|
|
1251
|
+
sendSlashCommandResponse(res, 503, {
|
|
1884
1252
|
response_type: "ephemeral",
|
|
1885
1253
|
text: "Slash commands are not yet initialized. Please try again in a moment."
|
|
1886
|
-
})
|
|
1254
|
+
});
|
|
1887
1255
|
return;
|
|
1888
1256
|
}
|
|
1889
1257
|
await state.handler(req, res, void 0, onRequestAuthenticated);
|
|
@@ -1910,7 +1278,7 @@ function registerSlashCommandRoute(api) {
|
|
|
1910
1278
|
if (ct.includes("application/json")) token = JSON.parse(bodyStr).token ?? null;
|
|
1911
1279
|
else token = new URLSearchParams(bodyStr).get("token");
|
|
1912
1280
|
} catch {}
|
|
1913
|
-
let match = token ?
|
|
1281
|
+
let match = token ? resolveSlashHandler("token", (state) => state.commandTokens.has(token)) : { kind: "none" };
|
|
1914
1282
|
if (match.kind === "none") {
|
|
1915
1283
|
const payload = parseSlashCommandPayload(bodyStr, ct);
|
|
1916
1284
|
if (payload) match = resolveSlashHandlerForCommand({
|
|
@@ -1919,23 +1287,18 @@ function registerSlashCommandRoute(api) {
|
|
|
1919
1287
|
});
|
|
1920
1288
|
}
|
|
1921
1289
|
if (match.kind === "none") {
|
|
1922
|
-
res
|
|
1923
|
-
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1924
|
-
res.end(JSON.stringify({
|
|
1290
|
+
sendSlashCommandResponse(res, 401, {
|
|
1925
1291
|
response_type: "ephemeral",
|
|
1926
1292
|
text: "Unauthorized: invalid command token."
|
|
1927
|
-
})
|
|
1293
|
+
});
|
|
1928
1294
|
return;
|
|
1929
1295
|
}
|
|
1930
1296
|
if (match.kind === "ambiguous") {
|
|
1931
1297
|
api.logger.warn?.(`mattermost: slash callback matched multiple accounts via ${match.source} (${match.accountIds.join(", ")})`);
|
|
1932
|
-
|
|
1933
|
-
res.statusCode = 409;
|
|
1934
|
-
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1935
|
-
res.end(JSON.stringify({
|
|
1298
|
+
sendSlashCommandResponse(res, 409, {
|
|
1936
1299
|
response_type: "ephemeral",
|
|
1937
|
-
text:
|
|
1938
|
-
})
|
|
1300
|
+
text: match.source === "token" ? "Conflict: command token is not unique across accounts." : "Conflict: slash command is not unique across accounts."
|
|
1301
|
+
});
|
|
1939
1302
|
return;
|
|
1940
1303
|
}
|
|
1941
1304
|
await match.handler(req, res, bodyStr, onRequestAuthenticated);
|
|
@@ -1965,4 +1328,4 @@ function registerSlashCommandRoute(api) {
|
|
|
1965
1328
|
});
|
|
1966
1329
|
}
|
|
1967
1330
|
//#endregion
|
|
1968
|
-
export {
|
|
1331
|
+
export { resolveSlashCommandConfig as _, deliverMattermostReplyPayload as a, parseMattermostModelPickerContext as c, resolveMattermostModelPickerCurrentModel as d, DEFAULT_COMMAND_SPECS as f, resolveCallbackUrl as g, registerSlashCommands as h, registerSlashCommandRoute as i, renderMattermostModelsPickerView as l, isSlashCommandsEnabled as m, deactivateSlashCommands as n, joinMattermostVisibleContent as o, cleanupSlashCommands as p, getSlashCommandState as r, buildMattermostAllowedModelRefs as s, activateSlashCommands as t, renderMattermostProviderPickerView as u };
|