hyperclaw 5.2.8 → 5.3.0
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/a2ui-protocol-DEsfqO7h.js +75 -0
- package/dist/agents-routing-ChorJKFL.js +6 -0
- package/dist/agents-routing-Cpg20-1e.js +398 -0
- package/dist/api-key-validation-DgOBmp8Y.js +64 -0
- package/dist/api-keys-guide--73Bq0Ey.js +149 -0
- package/dist/audit-Dntx9fG9.js +445 -0
- package/dist/banner-B_rR7FPO.js +7 -0
- package/dist/banner-Bb7CderS.js +143 -0
- package/dist/banner-BbUkjcoX.js +7 -0
- package/dist/banner-DupxNjxh.js +143 -0
- package/dist/bounty-tools-Dn9Yq7V1.js +211 -0
- package/dist/browser-tools-CJ9M9o22.js +179 -0
- package/dist/browser-tools-CXxWxA1c.js +5 -0
- package/dist/chat-D1Zc73I5.js +513 -0
- package/dist/chat-TGA-UO46.js +536 -0
- package/dist/claw-tasks-ChqkHdFs.js +80 -0
- package/dist/config-Bzues-G2.js +7 -0
- package/dist/config-DGAAJ49A.js +261 -0
- package/dist/connector-1efnZgQN.js +566 -0
- package/dist/connector-B5q1_srT.js +286 -0
- package/dist/connector-BMFLJ4fr.js +508 -0
- package/dist/connector-BZYv9siY.js +189 -0
- package/dist/connector-B_XkXm-j.js +218 -0
- package/dist/connector-BkY1I6gf.js +189 -0
- package/dist/connector-C2Z3RN1z.js +350 -0
- package/dist/connector-C7aYvVzU.js +225 -0
- package/dist/connector-CXXYOyHw.js +164 -0
- package/dist/connector-Ca1J23HX.js +167 -0
- package/dist/connector-Cjqc656I.js +181 -0
- package/dist/connector-CluRienN.js +425 -0
- package/dist/connector-CuNz2eP-.js +305 -0
- package/dist/connector-DHL_oeHy.js +552 -0
- package/dist/connector-DJ79rd1L.js +173 -0
- package/dist/connector-DcLE6xCZ.js +239 -0
- package/dist/connector-DcyQTJnJ.js +162 -0
- package/dist/connector-DgyX9qSc.js +192 -0
- package/dist/connector-DnDXXZ7L.js +182 -0
- package/dist/connector-DqUslg-X.js +213 -0
- package/dist/connector-Duc-HmRZ.js +85 -0
- package/dist/connector-IV0QFer8.js +498 -0
- package/dist/connector-OnsLxE8G.js +194 -0
- package/dist/connector-UYu_TS0X.js +204 -0
- package/dist/connector-cCA5ffmp.js +340 -0
- package/dist/connector-fbNfx4_L.js +568 -0
- package/dist/connector-fi2vlwbO.js +276 -0
- package/dist/connector-l3LD8IDN.js +419 -0
- package/dist/cost-tracker-DCXDUzBI.js +103 -0
- package/dist/credentials-store-Bmm9e1SS.js +7 -0
- package/dist/credentials-store-D8ERbGR2.js +89 -0
- package/dist/cron-tasks-OQbgmenS.js +85 -0
- package/dist/daemon-BgT541y-.js +421 -0
- package/dist/daemon-aVX-WGz1.js +421 -0
- package/dist/daemon-iFmVBPXN.js +7 -0
- package/dist/daemon-iM7U3tDr.js +7 -0
- package/dist/delivery-Pko6sSkt.js +4 -0
- package/dist/delivery-hMHFRZwy.js +95 -0
- package/dist/destructive-gate-C2TrWsp2.js +101 -0
- package/dist/developer-keys-BWXHaWxY.js +127 -0
- package/dist/developer-keys-CzDxVczE.js +8 -0
- package/dist/device-auth-store-C1bCwXO2.js +7 -0
- package/dist/device-auth-store-DIZTOz4V.js +88 -0
- package/dist/doctor-C6nAGdH8.js +233 -0
- package/dist/doctor-mgWumA25.js +6 -0
- package/dist/engine-BGRTi0fo.js +327 -0
- package/dist/engine-BrDEACit.js +327 -0
- package/dist/engine-BvCEhaUn.js +7 -0
- package/dist/engine-DrsMsoLZ.js +7 -0
- package/dist/env-resolve-CHxjGo8u.js +151 -0
- package/dist/env-resolve-pIETNTpQ.js +10 -0
- package/dist/extraction-tools-BE6z_Yw5.js +91 -0
- package/dist/extraction-tools-CJsdyBST.js +5 -0
- package/dist/form_data-B2_0EoWj.js +8657 -0
- package/dist/gmail-watch-setup-1RGIHNdu.js +42 -0
- package/dist/health-BMUmUNoe.js +152 -0
- package/dist/health-C8n9RH5O.js +6 -0
- package/dist/heartbeat-engine-aRbab8a5.js +89 -0
- package/dist/hub-BJM2KXLO.js +6 -0
- package/dist/hub-Bb_dYECE.js +512 -0
- package/dist/hyperclawbot-CZ4DjvO-.js +516 -0
- package/dist/hyperclawbot-CgrV46DA.js +516 -0
- package/dist/inference-CFBkvLpE.js +2854 -0
- package/dist/inference-G4MbdErG.js +8 -0
- package/dist/knowledge-graph-9UNrsiIY.js +134 -0
- package/dist/loader-DIPs649t.js +410 -0
- package/dist/loader-Dq_cDlOW.js +6 -0
- package/dist/logger-CG38Idq4.js +86 -0
- package/dist/manager--wG9JdFW.js +120 -0
- package/dist/manager-BNc21xgG.js +6 -0
- package/dist/manager-DWJ7WZcY.js +250 -0
- package/dist/manager-DYfzqckn.js +35 -0
- package/dist/mcp-SsMEvl28.js +142 -0
- package/dist/mcp-loader-CVhiejBN.js +93 -0
- package/dist/mcp-loader-DLrp_oZJ.js +93 -0
- package/dist/memory-BCYvdqwo.js +273 -0
- package/dist/memory-BGgCBSx1.js +6 -0
- package/dist/memory-auto-Bh52cQJP.js +5 -0
- package/dist/memory-auto-BupvVwNd.js +306 -0
- package/dist/memory-integration-4oGqX6rr.js +91 -0
- package/dist/moltbook-B3DNdh40.js +81 -0
- package/dist/node-C4esBfbX.js +226 -0
- package/dist/nodes-registry-DLUZhEMS.js +52 -0
- package/dist/oauth-flow-BbLQTzZk.js +148 -0
- package/dist/oauth-provider-UZyG84s7.js +111 -0
- package/dist/observability-BtLyuxcz.js +89 -0
- package/dist/onboard-B3drurt-.js +3812 -0
- package/dist/onboard-CSJuvkMN.js +14 -0
- package/dist/onboard-DEwuHrMj.js +14 -0
- package/dist/onboard-eIxjVYKi.js +3812 -0
- package/dist/orchestrator-BXyIgAeH.js +189 -0
- package/dist/orchestrator-Cgj-8BbJ.js +189 -0
- package/dist/orchestrator-MLTc4NYu.js +6 -0
- package/dist/orchestrator-PLHfNTD6.js +6 -0
- package/dist/osint-Bsf6RGPv.js +283 -0
- package/dist/osint-CMyamX3_.js +283 -0
- package/dist/osint-chat-Ark94iFc.js +789 -0
- package/dist/osint-chat-D_6Fb27C.js +789 -0
- package/dist/pairing-2vAiDBjN.js +6 -0
- package/dist/pairing-B4NoBvyE.js +207 -0
- package/dist/pc-access-BLnc-DYp.js +858 -0
- package/dist/pc-access-CTNtG2LD.js +8 -0
- package/dist/pending-approval-C4ZaHHWl.js +22 -0
- package/dist/reminders-store-BixTWL1h.js +58 -0
- package/dist/renderer-B1ToXngl.js +228 -0
- package/dist/rules-Cqen1Mpt.js +106 -0
- package/dist/run-main.js +101 -95
- package/dist/runner-Cr1_mwnU.js +1274 -0
- package/dist/security-B4vH02lO.js +4 -0
- package/dist/security-HOOGCw5z.js +90 -0
- package/dist/server-B9rMYJwV.js +4 -0
- package/dist/server-CRhXiGI9.js +4 -0
- package/dist/server-DMC1wOsc.js +1365 -0
- package/dist/server-De4H45Ju.js +1365 -0
- package/dist/session-store-7sEPyV16.js +5 -0
- package/dist/session-store-Ce2QMSL_.js +141 -0
- package/dist/sessions-tools-CWr_pDtp.js +5 -0
- package/dist/sessions-tools-DKVu9aIN.js +95 -0
- package/dist/skill-loader-DK19Jm4e.js +7 -0
- package/dist/skill-loader-Dfs9VNM-.js +160 -0
- package/dist/skill-runtime-BeKh2rD_.js +5 -0
- package/dist/skill-runtime-CcpC2Zfc.js +104 -0
- package/dist/skill-runtime-CzsUymMA.js +104 -0
- package/dist/skill-runtime-DAP0Gs_7.js +5 -0
- package/dist/src-BxmkZ9RH.js +63 -0
- package/dist/src-CvJOtJlj.js +458 -0
- package/dist/src-DjTtmSRg.js +20 -0
- package/dist/src-cowbRb9x.js +63 -0
- package/dist/src-n_46LPDi.js +458 -0
- package/dist/sub-agent-tools-CIA8mqjv.js +39 -0
- package/dist/sub-agent-tools-q5JqEze_.js +39 -0
- package/dist/tool-policy-QXF3MMxu.js +189 -0
- package/dist/tts-elevenlabs-y6HGWWDS.js +64 -0
- package/dist/update-check-C4te7JmY.js +6 -0
- package/dist/update-check-GDue_it1.js +98 -0
- package/dist/vision-tools-CbVfyTZT.js +5 -0
- package/dist/vision-tools-DieVQp6s.js +51 -0
- package/dist/vision-u4kMThdo.js +167 -0
- package/dist/voice-transcription-DgON5qaF.js +170 -0
- package/dist/website-watch-tools-B8L_NgwT.js +5 -0
- package/dist/website-watch-tools-Drm5HjIX.js +176 -0
- package/package.json +1 -1
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-jS-bbMI5.js');
|
|
2
|
+
const chalk = require_chunk.__toESM(require("chalk"));
|
|
3
|
+
const fs_extra = require_chunk.__toESM(require("fs-extra"));
|
|
4
|
+
const path = require_chunk.__toESM(require("path"));
|
|
5
|
+
const os = require_chunk.__toESM(require("os"));
|
|
6
|
+
const crypto = require_chunk.__toESM(require("crypto"));
|
|
7
|
+
const ws = require_chunk.__toESM(require("ws"));
|
|
8
|
+
const http = require_chunk.__toESM(require("http"));
|
|
9
|
+
const https = require_chunk.__toESM(require("https"));
|
|
10
|
+
const events = require_chunk.__toESM(require("events"));
|
|
11
|
+
|
|
12
|
+
//#region extensions/mattermost/src/connector.ts
|
|
13
|
+
const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "mattermost-state.json");
|
|
14
|
+
const HMAC_INTERACTIONS_KEY = "openclaw-mattermost-interactions";
|
|
15
|
+
const WS_RECONNECT_DELAY_MS = 5e3;
|
|
16
|
+
const UNSAFE_KEYS = new Set([
|
|
17
|
+
"__proto__",
|
|
18
|
+
"prototype",
|
|
19
|
+
"constructor",
|
|
20
|
+
"__defineGetter__",
|
|
21
|
+
"__defineSetter__",
|
|
22
|
+
"__lookupGetter__",
|
|
23
|
+
"__lookupSetter__",
|
|
24
|
+
"hasOwnProperty",
|
|
25
|
+
"valueOf",
|
|
26
|
+
"toString",
|
|
27
|
+
"toJSON"
|
|
28
|
+
]);
|
|
29
|
+
function createSafeRecord() {
|
|
30
|
+
return Object.create(null);
|
|
31
|
+
}
|
|
32
|
+
function isSafeKey(key) {
|
|
33
|
+
if (!key || typeof key !== "string") return false;
|
|
34
|
+
if (UNSAFE_KEYS.has(key) || key.includes("__") || key.includes(".")) return false;
|
|
35
|
+
return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(key);
|
|
36
|
+
}
|
|
37
|
+
function sanitizeForLog(value) {
|
|
38
|
+
return String(value ?? "").replace(/[\r\n\t]+/g, " ").slice(0, 200);
|
|
39
|
+
}
|
|
40
|
+
function sanitizeAccountId(id) {
|
|
41
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error(`Mattermost: invalid account id "${sanitizeForLog(id)}"`);
|
|
42
|
+
return id;
|
|
43
|
+
}
|
|
44
|
+
async function mmApi(baseUrl, token, method, apiPath, body) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
47
|
+
const fullPath = apiPath.startsWith("/") ? apiPath : `/${apiPath}`;
|
|
48
|
+
const url = new URL(fullPath, base);
|
|
49
|
+
const payload = body ? JSON.stringify(body) : null;
|
|
50
|
+
const client = url.protocol === "https:" ? https.default : http.default;
|
|
51
|
+
const req = client.request({
|
|
52
|
+
hostname: url.hostname,
|
|
53
|
+
port: url.port || (url.protocol === "https:" ? 443 : 80),
|
|
54
|
+
path: url.pathname + (url.search || ""),
|
|
55
|
+
method,
|
|
56
|
+
headers: {
|
|
57
|
+
Authorization: `Bearer ${token}`,
|
|
58
|
+
...payload ? {
|
|
59
|
+
"Content-Type": "application/json",
|
|
60
|
+
"Content-Length": Buffer.byteLength(payload)
|
|
61
|
+
} : {}
|
|
62
|
+
}
|
|
63
|
+
}, (res) => {
|
|
64
|
+
let data = "";
|
|
65
|
+
res.on("data", (c) => data += c);
|
|
66
|
+
res.on("end", () => {
|
|
67
|
+
try {
|
|
68
|
+
const r = data ? JSON.parse(data) : {};
|
|
69
|
+
const ok = res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300;
|
|
70
|
+
if (ok) resolve(r);
|
|
71
|
+
else reject(new Error(r.message || r.error || `HTTP ${res.statusCode}`));
|
|
72
|
+
} catch (e) {
|
|
73
|
+
reject(e || new Error("Parse error"));
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
req.on("error", reject);
|
|
78
|
+
if (payload) req.write(payload);
|
|
79
|
+
req.end();
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function deriveInteractionSecret(botToken) {
|
|
83
|
+
return crypto.default.createHmac("sha256", HMAC_INTERACTIONS_KEY).update(botToken).digest("hex");
|
|
84
|
+
}
|
|
85
|
+
function signContext(ctx, secret) {
|
|
86
|
+
const sortedKeys = Object.keys(ctx).filter(isSafeKey).sort();
|
|
87
|
+
const payload = createSafeRecord();
|
|
88
|
+
for (const k of sortedKeys) payload[k] = ctx[k];
|
|
89
|
+
const serialized = JSON.stringify(payload);
|
|
90
|
+
return crypto.default.createHmac("sha256", secret).update(serialized).digest("hex");
|
|
91
|
+
}
|
|
92
|
+
function verifyInteraction(context, secret) {
|
|
93
|
+
const token = context["_token"];
|
|
94
|
+
if (typeof token !== "string") return false;
|
|
95
|
+
const { _token: _,...rest } = context;
|
|
96
|
+
return signContext(rest, secret) === token;
|
|
97
|
+
}
|
|
98
|
+
function resolveAccount(id, raw, state) {
|
|
99
|
+
const safeId = sanitizeAccountId(id);
|
|
100
|
+
const botToken = raw.botToken || raw.token || process.env["MATTERMOST_BOT_TOKEN"] || "";
|
|
101
|
+
const baseUrl = raw.baseUrl || raw.serverUrl || process.env["MATTERMOST_URL"] || "";
|
|
102
|
+
return {
|
|
103
|
+
id: safeId,
|
|
104
|
+
name: raw.name ?? id,
|
|
105
|
+
botToken,
|
|
106
|
+
baseUrl: baseUrl.replace(/\/$/, ""),
|
|
107
|
+
dmPolicy: raw.dmPolicy ?? "pairing",
|
|
108
|
+
allowFrom: raw.allowFrom ?? [],
|
|
109
|
+
groupPolicy: raw.groupPolicy ?? "allowlist",
|
|
110
|
+
groupAllowFrom: raw.groupAllowFrom ?? [],
|
|
111
|
+
dangerouslyAllowNameMatching: raw.dangerouslyAllowNameMatching ?? false,
|
|
112
|
+
chatmode: raw.chatmode ?? "oncall",
|
|
113
|
+
oncharPrefixes: raw.oncharPrefixes ?? [">"],
|
|
114
|
+
requireMention: raw.requireMention ?? true,
|
|
115
|
+
commands: raw.commands ?? { native: false },
|
|
116
|
+
capabilities: raw.capabilities ?? [],
|
|
117
|
+
actions: {
|
|
118
|
+
reactions: true,
|
|
119
|
+
...raw.actions
|
|
120
|
+
},
|
|
121
|
+
interactions: raw.interactions ?? {},
|
|
122
|
+
approvedPairings: state.approved,
|
|
123
|
+
pendingPairings: state.pending
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
var SingleAccountConnector = class extends events.EventEmitter {
|
|
127
|
+
acc;
|
|
128
|
+
ws = null;
|
|
129
|
+
wsSeq = 1;
|
|
130
|
+
reconnecting = false;
|
|
131
|
+
botUserId = "";
|
|
132
|
+
constructor(acc) {
|
|
133
|
+
super();
|
|
134
|
+
this.acc = acc;
|
|
135
|
+
}
|
|
136
|
+
async connect() {
|
|
137
|
+
const me = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", "/api/v4/users/me");
|
|
138
|
+
this.botUserId = me.id;
|
|
139
|
+
console.log(chalk.default.green(` 🦅 Mattermost[${sanitizeForLog(this.acc.id)}]: connected as @${sanitizeForLog(me.username)} → ${sanitizeForLog(this.acc.baseUrl)}`));
|
|
140
|
+
this._startWebSocket();
|
|
141
|
+
this.emit("connected", {
|
|
142
|
+
accountId: this.acc.id,
|
|
143
|
+
baseUrl: this.acc.baseUrl,
|
|
144
|
+
botUserId: this.botUserId
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
disconnect() {
|
|
148
|
+
this.reconnecting = false;
|
|
149
|
+
this.ws?.close();
|
|
150
|
+
this.ws = null;
|
|
151
|
+
}
|
|
152
|
+
_startWebSocket() {
|
|
153
|
+
const wsUrl = this.acc.baseUrl.replace(/^http/, "ws") + "/api/v4/websocket";
|
|
154
|
+
const ws$1 = new ws.default(wsUrl);
|
|
155
|
+
this.ws = ws$1;
|
|
156
|
+
ws$1.on("open", () => {
|
|
157
|
+
this.wsSeq = 1;
|
|
158
|
+
ws$1.send(JSON.stringify({
|
|
159
|
+
seq: this.wsSeq++,
|
|
160
|
+
action: "authentication_challenge",
|
|
161
|
+
data: { token: this.acc.botToken }
|
|
162
|
+
}));
|
|
163
|
+
});
|
|
164
|
+
ws$1.on("message", (raw) => {
|
|
165
|
+
try {
|
|
166
|
+
const ev = JSON.parse(raw.toString());
|
|
167
|
+
if (ev.event === "posted") this._onPostedEvent(ev);
|
|
168
|
+
if (ev.event === "reaction_added" || ev.event === "reaction_removed") this.emit("reaction", {
|
|
169
|
+
accountId: this.acc.id,
|
|
170
|
+
event: ev.event,
|
|
171
|
+
data: ev.data
|
|
172
|
+
});
|
|
173
|
+
} catch {}
|
|
174
|
+
});
|
|
175
|
+
ws$1.on("close", () => {
|
|
176
|
+
if (!this.reconnecting) return;
|
|
177
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${sanitizeForLog(this.acc.id)}]: WS closed, reconnecting...`));
|
|
178
|
+
setTimeout(() => this._startWebSocket(), WS_RECONNECT_DELAY_MS);
|
|
179
|
+
});
|
|
180
|
+
ws$1.on("error", (err) => {
|
|
181
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${sanitizeForLog(this.acc.id)}]: WS error: ${sanitizeForLog(err.message)}`));
|
|
182
|
+
});
|
|
183
|
+
this.reconnecting = true;
|
|
184
|
+
}
|
|
185
|
+
_onPostedEvent(ev) {
|
|
186
|
+
let post;
|
|
187
|
+
try {
|
|
188
|
+
post = typeof ev.data?.post === "string" ? JSON.parse(ev.data.post) : ev.data?.post;
|
|
189
|
+
} catch {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (!post) return;
|
|
193
|
+
if (post.user_id === this.botUserId) return;
|
|
194
|
+
const channelType = ev.data?.channel_type ?? "";
|
|
195
|
+
const isDM = channelType === "D";
|
|
196
|
+
const text = (post.message || "").trim();
|
|
197
|
+
const from = post.user_id;
|
|
198
|
+
const channelId = post.channel_id;
|
|
199
|
+
const senderName = ev.data?.sender_name ?? "";
|
|
200
|
+
if (!text) return;
|
|
201
|
+
if (isDM) this._routeDM(from, channelId, text, senderName, post.id);
|
|
202
|
+
else this._routeChannel(from, channelId, text, senderName, post.id);
|
|
203
|
+
}
|
|
204
|
+
async _routeDM(userId, channelId, text, senderName, postId) {
|
|
205
|
+
const acc = this.acc;
|
|
206
|
+
if (acc.dmPolicy === "none") return;
|
|
207
|
+
if (acc.dmPolicy === "open") {
|
|
208
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (acc.dmPolicy === "allowlist") {
|
|
212
|
+
if (!acc.allowFrom.includes(userId)) {
|
|
213
|
+
console.log(chalk.default.gray(` mattermost[${sanitizeForLog(acc.id)}]: drop DM from ${sanitizeForLog(userId)} (dmPolicy=allowlist)`));
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (acc.dmPolicy === "pairing") {
|
|
220
|
+
if (acc.approvedPairings.includes(userId)) {
|
|
221
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const raw = text.trim().toUpperCase();
|
|
225
|
+
const upper = /^[A-Z0-9]{4,12}$/.test(raw) ? raw : "";
|
|
226
|
+
if (upper && acc.pendingPairings[upper]) {
|
|
227
|
+
acc.approvedPairings.push(userId);
|
|
228
|
+
delete acc.pendingPairings[upper];
|
|
229
|
+
await this._saveState();
|
|
230
|
+
await this.sendMessage(channelId, "🦅 Paired!");
|
|
231
|
+
this.emit("pairing:approved", {
|
|
232
|
+
accountId: acc.id,
|
|
233
|
+
userId,
|
|
234
|
+
channelId
|
|
235
|
+
});
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
|
|
239
|
+
acc.pendingPairings[code] = userId;
|
|
240
|
+
await this._saveState();
|
|
241
|
+
await this.sendMessage(channelId, `🦅 Pairing code: \`${code}\`\nApprove: hyperclaw pairing approve mattermost ${code}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
_routeChannel(userId, channelId, text, senderName, postId) {
|
|
245
|
+
const acc = this.acc;
|
|
246
|
+
if (acc.groupPolicy === "allowlist") {
|
|
247
|
+
const combined = [...acc.groupAllowFrom, ...acc.allowFrom];
|
|
248
|
+
if (combined.length > 0) {
|
|
249
|
+
const match = combined.some((p) => {
|
|
250
|
+
if (p === "*") return true;
|
|
251
|
+
if (acc.dangerouslyAllowNameMatching) {
|
|
252
|
+
const name = senderName.replace(/^@/, "");
|
|
253
|
+
return name === p || userId === p;
|
|
254
|
+
}
|
|
255
|
+
return userId === p;
|
|
256
|
+
});
|
|
257
|
+
if (!match) {
|
|
258
|
+
console.log(chalk.default.gray(` mattermost[${sanitizeForLog(acc.id)}]: drop group sender ${sanitizeForLog(userId)} (policy=allowlist)`));
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const botMentionPatterns = [
|
|
264
|
+
`@${this.botUserId}`,
|
|
265
|
+
`@hyperclaw`,
|
|
266
|
+
`@${acc.name?.toLowerCase()}`
|
|
267
|
+
];
|
|
268
|
+
const isMentioned = botMentionPatterns.some((p) => text.toLowerCase().includes(p.toLowerCase()));
|
|
269
|
+
if (acc.chatmode === "oncall" || acc.chatmode !== "onmessage" && acc.requireMention) {
|
|
270
|
+
if (!isMentioned) {
|
|
271
|
+
console.log(chalk.default.gray(` mattermost[${sanitizeForLog(acc.id)}]: drop channel ${sanitizeForLog(channelId)} (missing-mention, chatmode=oncall)`));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
} else if (acc.chatmode === "onchar") {
|
|
275
|
+
const hasPrefix = acc.oncharPrefixes.some((p) => text.startsWith(p));
|
|
276
|
+
if (!hasPrefix && !isMentioned) {
|
|
277
|
+
console.log(chalk.default.gray(` mattermost[${sanitizeForLog(acc.id)}]: drop channel ${sanitizeForLog(channelId)} (no prefix/mention, chatmode=onchar)`));
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
this._emit(userId, channelId, text, senderName, postId, false);
|
|
282
|
+
}
|
|
283
|
+
_emit(from, chatId, text, senderName, postId, isDM) {
|
|
284
|
+
this.emit("message", {
|
|
285
|
+
accountId: this.acc.id,
|
|
286
|
+
id: postId,
|
|
287
|
+
from,
|
|
288
|
+
chatId,
|
|
289
|
+
text,
|
|
290
|
+
senderName,
|
|
291
|
+
isDM,
|
|
292
|
+
channelId: "mattermost"
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
async handleWebhook(body, webhookToken) {
|
|
296
|
+
const params = createSafeRecord();
|
|
297
|
+
const trimmed = (body || "").trim();
|
|
298
|
+
if (trimmed.startsWith("{")) try {
|
|
299
|
+
const raw = JSON.parse(trimmed);
|
|
300
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
|
|
301
|
+
for (const [k, v] of Object.entries(raw)) if (isSafeKey(k)) params[k] = typeof v === "string" ? v : String(v ?? "");
|
|
302
|
+
} catch {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
else for (const pair of body.split("&")) {
|
|
306
|
+
const eq = pair.indexOf("=");
|
|
307
|
+
const k = eq >= 0 ? decodeURIComponent(pair.slice(0, eq).replace(/\+/g, " ")) : decodeURIComponent(pair.replace(/\+/g, " "));
|
|
308
|
+
const v = eq >= 0 ? decodeURIComponent((pair.slice(eq + 1) || "").replace(/\+/g, " ")) : "";
|
|
309
|
+
if (isSafeKey(k)) params[k] = v;
|
|
310
|
+
}
|
|
311
|
+
if (params.token !== webhookToken) {
|
|
312
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${sanitizeForLog(this.acc.id)}]: invalid webhook token`));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const channelId = params.channel_id;
|
|
316
|
+
const userId = params.user_id;
|
|
317
|
+
const senderName = params.user_name || "";
|
|
318
|
+
let text = (params.text || "").trim();
|
|
319
|
+
const triggerWord = params.trigger_word || "";
|
|
320
|
+
if (triggerWord && text.startsWith(triggerWord)) text = text.slice(triggerWord.length).trim();
|
|
321
|
+
if (!channelId || !userId || !text) return;
|
|
322
|
+
this._routeChannel(userId, channelId, text, senderName, params.post_id || `${channelId}-${Date.now()}`);
|
|
323
|
+
}
|
|
324
|
+
async handleSlashCommand(payload, expectedToken) {
|
|
325
|
+
const safePayload = createSafeRecord();
|
|
326
|
+
for (const [k, v] of Object.entries(payload)) if (isSafeKey(k)) safePayload[k] = String(v ?? "");
|
|
327
|
+
if (safePayload.token !== expectedToken) {
|
|
328
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${sanitizeForLog(this.acc.id)}]: slash command token mismatch`));
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
const text = (safePayload.text || "").trim();
|
|
332
|
+
const userId = safePayload.user_id || "";
|
|
333
|
+
const channelId = safePayload.channel_id || "";
|
|
334
|
+
const commandName = safePayload.command || "";
|
|
335
|
+
this.emit("slash_command", {
|
|
336
|
+
accountId: this.acc.id,
|
|
337
|
+
command: commandName,
|
|
338
|
+
text,
|
|
339
|
+
userId,
|
|
340
|
+
channelId,
|
|
341
|
+
senderName: safePayload.user_name || "",
|
|
342
|
+
responseUrl: safePayload.response_url || ""
|
|
343
|
+
});
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
/** Register all native slash commands via Mattermost REST API. */
|
|
347
|
+
async registerSlashCommands(teamId, commands) {
|
|
348
|
+
const acc = this.acc;
|
|
349
|
+
if (!acc.commands.native || acc.commands.native === "auto") return;
|
|
350
|
+
const callbackUrl = acc.commands.callbackUrl || `http://localhost:18789${acc.commands.callbackPath ?? "/api/channels/mattermost/command"}`;
|
|
351
|
+
for (const cmd of commands) try {
|
|
352
|
+
await mmApi(acc.baseUrl, acc.botToken, "POST", "/api/v4/commands", {
|
|
353
|
+
team_id: teamId,
|
|
354
|
+
trigger: cmd.trigger.replace(/^\//, ""),
|
|
355
|
+
method: "P",
|
|
356
|
+
title: cmd.description,
|
|
357
|
+
description: cmd.description,
|
|
358
|
+
url: callbackUrl,
|
|
359
|
+
username: acc.name ?? "hyperclaw-bot",
|
|
360
|
+
auto_complete: true,
|
|
361
|
+
auto_complete_hint: "[prompt]",
|
|
362
|
+
auto_complete_desc: cmd.description
|
|
363
|
+
});
|
|
364
|
+
console.log(chalk.default.gray(` mattermost[${sanitizeForLog(acc.id)}]: registered /${sanitizeForLog(cmd.trigger)}`));
|
|
365
|
+
} catch (e) {
|
|
366
|
+
console.log(chalk.default.yellow(` ⚠ mattermost[${sanitizeForLog(acc.id)}]: failed to register /${sanitizeForLog(cmd.trigger)}: ${sanitizeForLog(e.message)}`));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
handleInteraction(context) {
|
|
370
|
+
const secret = deriveInteractionSecret(this.acc.botToken);
|
|
371
|
+
if (!verifyInteraction(context, secret)) return {
|
|
372
|
+
ok: false,
|
|
373
|
+
error: "invalid _token"
|
|
374
|
+
};
|
|
375
|
+
if (!context["action_id"]) return {
|
|
376
|
+
ok: false,
|
|
377
|
+
error: "missing action_id in context"
|
|
378
|
+
};
|
|
379
|
+
this.emit("interaction", {
|
|
380
|
+
accountId: this.acc.id,
|
|
381
|
+
context
|
|
382
|
+
});
|
|
383
|
+
return { ok: true };
|
|
384
|
+
}
|
|
385
|
+
async addReaction(postId, emoji) {
|
|
386
|
+
if (!this.acc.actions.reactions) return;
|
|
387
|
+
const name = emoji.replace(/:/g, "");
|
|
388
|
+
await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/reactions", {
|
|
389
|
+
user_id: this.botUserId,
|
|
390
|
+
post_id: postId,
|
|
391
|
+
emoji_name: name
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
async removeReaction(postId, emoji) {
|
|
395
|
+
if (!this.acc.actions.reactions) return;
|
|
396
|
+
const name = emoji.replace(/:/g, "");
|
|
397
|
+
await mmApi(this.acc.baseUrl, this.acc.botToken, "DELETE", `/api/v4/users/${this.botUserId}/posts/${postId}/reactions/${name}`);
|
|
398
|
+
}
|
|
399
|
+
async sendMessage(channelId, text, attachments) {
|
|
400
|
+
const chunks = text.match(/.{1,4000}/gs) || [text];
|
|
401
|
+
let lastPost;
|
|
402
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
403
|
+
const body = {
|
|
404
|
+
channel_id: channelId,
|
|
405
|
+
message: chunks[i].slice(0, 16383)
|
|
406
|
+
};
|
|
407
|
+
if (i === chunks.length - 1 && attachments?.length) body.props = { attachments };
|
|
408
|
+
lastPost = await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/posts", body);
|
|
409
|
+
}
|
|
410
|
+
return lastPost;
|
|
411
|
+
}
|
|
412
|
+
async resolveTarget(target) {
|
|
413
|
+
if (target.startsWith("channel:")) return {
|
|
414
|
+
type: "channel",
|
|
415
|
+
id: target.slice(8)
|
|
416
|
+
};
|
|
417
|
+
if (target.startsWith("user:")) {
|
|
418
|
+
const ch = await this._getDmChannel(target.slice(5));
|
|
419
|
+
return {
|
|
420
|
+
type: "dm",
|
|
421
|
+
id: ch
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
if (target.startsWith("@")) {
|
|
425
|
+
const users = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", `/api/v4/users?in_team=&per_page=200&page=0`);
|
|
426
|
+
const username = target.slice(1).toLowerCase();
|
|
427
|
+
const found = Array.isArray(users) ? users.find((u) => u.username?.toLowerCase() === username) : null;
|
|
428
|
+
if (!found) throw new Error(`Mattermost: user ${target} not found`);
|
|
429
|
+
const ch = await this._getDmChannel(found.id);
|
|
430
|
+
return {
|
|
431
|
+
type: "dm",
|
|
432
|
+
id: ch
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
if (target.startsWith("#")) {
|
|
436
|
+
const name = target.slice(1);
|
|
437
|
+
const ch = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", `/api/v4/channels/name/${name}`);
|
|
438
|
+
return {
|
|
439
|
+
type: "channel",
|
|
440
|
+
id: ch.id
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
type: "channel",
|
|
445
|
+
id: target
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
async _getDmChannel(userId) {
|
|
449
|
+
const ch = await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/channels/direct", [this.botUserId, userId]);
|
|
450
|
+
return ch.id;
|
|
451
|
+
}
|
|
452
|
+
approvePairing(code) {
|
|
453
|
+
const upper = code.toUpperCase();
|
|
454
|
+
if (!this.acc.pendingPairings[upper]) return false;
|
|
455
|
+
this.acc.approvedPairings.push(this.acc.pendingPairings[upper]);
|
|
456
|
+
delete this.acc.pendingPairings[upper];
|
|
457
|
+
this._saveState();
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
listPendingPairings() {
|
|
461
|
+
return { ...this.acc.pendingPairings };
|
|
462
|
+
}
|
|
463
|
+
async _saveState() {
|
|
464
|
+
await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
|
|
465
|
+
const safeId = sanitizeAccountId(this.acc.id);
|
|
466
|
+
let state = createSafeRecord();
|
|
467
|
+
try {
|
|
468
|
+
state = await fs_extra.default.readJson(STATE_FILE);
|
|
469
|
+
} catch {}
|
|
470
|
+
state[safeId] = {
|
|
471
|
+
approvedPairings: this.acc.approvedPairings,
|
|
472
|
+
pendingPairings: this.acc.pendingPairings
|
|
473
|
+
};
|
|
474
|
+
await fs_extra.default.writeJson(STATE_FILE, state, { spaces: 2 });
|
|
475
|
+
}
|
|
476
|
+
async loadState() {
|
|
477
|
+
try {
|
|
478
|
+
const state = await fs_extra.default.readJson(STATE_FILE);
|
|
479
|
+
const s = state?.[sanitizeAccountId(this.acc.id)];
|
|
480
|
+
if (s?.approvedPairings) this.acc.approvedPairings = s.approvedPairings;
|
|
481
|
+
if (s?.pendingPairings) this.acc.pendingPairings = s.pendingPairings;
|
|
482
|
+
} catch {}
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
var MattermostConnector = class extends events.EventEmitter {
|
|
486
|
+
accounts = /* @__PURE__ */ new Map();
|
|
487
|
+
rawConfig;
|
|
488
|
+
constructor(config) {
|
|
489
|
+
super();
|
|
490
|
+
this.rawConfig = config;
|
|
491
|
+
}
|
|
492
|
+
async connect() {
|
|
493
|
+
const cfg = this.rawConfig;
|
|
494
|
+
const accountDefs = cfg.accounts ?? { default: cfg };
|
|
495
|
+
for (const [id, rawAcc] of Object.entries(accountDefs)) {
|
|
496
|
+
const merged = {
|
|
497
|
+
...cfg,
|
|
498
|
+
...rawAcc
|
|
499
|
+
};
|
|
500
|
+
const state = {
|
|
501
|
+
approved: cfg.approvedPairings ?? [],
|
|
502
|
+
pending: cfg.pendingPairings ?? {}
|
|
503
|
+
};
|
|
504
|
+
const acc = resolveAccount(id, merged, state);
|
|
505
|
+
if (!acc.botToken || !acc.baseUrl) {
|
|
506
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${sanitizeForLog(id)}]: missing botToken or baseUrl — skipping`));
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
const conn = new SingleAccountConnector(acc);
|
|
510
|
+
await conn.loadState();
|
|
511
|
+
conn.on("message", (msg) => this.emit("message", msg));
|
|
512
|
+
conn.on("connected", (info) => this.emit("connected", info));
|
|
513
|
+
conn.on("pairing:approved", (info) => this.emit("pairing:approved", info));
|
|
514
|
+
conn.on("interaction", (info) => this.emit("interaction", info));
|
|
515
|
+
conn.on("reaction", (info) => this.emit("reaction", info));
|
|
516
|
+
conn.on("slash_command", (info) => this.emit("slash_command", info));
|
|
517
|
+
await conn.connect();
|
|
518
|
+
this.accounts.set(acc.id, conn);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
disconnect() {
|
|
522
|
+
for (const conn of this.accounts.values()) conn.disconnect();
|
|
523
|
+
this.accounts.clear();
|
|
524
|
+
}
|
|
525
|
+
_acc(accountId = "default") {
|
|
526
|
+
const conn = this.accounts.get(accountId);
|
|
527
|
+
if (!conn) throw new Error(`Mattermost: account '${accountId}' not found`);
|
|
528
|
+
return conn;
|
|
529
|
+
}
|
|
530
|
+
async sendMessage(channelId, text, attachments, accountId) {
|
|
531
|
+
return this._acc(accountId).sendMessage(channelId, text, attachments);
|
|
532
|
+
}
|
|
533
|
+
async addReaction(postId, emoji, accountId) {
|
|
534
|
+
return this._acc(accountId).addReaction(postId, emoji);
|
|
535
|
+
}
|
|
536
|
+
async removeReaction(postId, emoji, accountId) {
|
|
537
|
+
return this._acc(accountId).removeReaction(postId, emoji);
|
|
538
|
+
}
|
|
539
|
+
async resolveTarget(target, accountId) {
|
|
540
|
+
return this._acc(accountId).resolveTarget(target);
|
|
541
|
+
}
|
|
542
|
+
handleInteraction(context, accountId) {
|
|
543
|
+
return this._acc(accountId).handleInteraction(context);
|
|
544
|
+
}
|
|
545
|
+
async handleWebhook(body, webhookToken, accountId) {
|
|
546
|
+
return this._acc(accountId).handleWebhook(body, webhookToken);
|
|
547
|
+
}
|
|
548
|
+
async handleSlashCommand(payload, expectedToken, accountId) {
|
|
549
|
+
return this._acc(accountId).handleSlashCommand(payload, expectedToken);
|
|
550
|
+
}
|
|
551
|
+
approvePairing(code, accountId) {
|
|
552
|
+
return this._acc(accountId).approvePairing(code);
|
|
553
|
+
}
|
|
554
|
+
listPendingPairings(accountId) {
|
|
555
|
+
return this._acc(accountId).listPendingPairings();
|
|
556
|
+
}
|
|
557
|
+
getAccountIds() {
|
|
558
|
+
return Array.from(this.accounts.keys());
|
|
559
|
+
}
|
|
560
|
+
isRunning() {
|
|
561
|
+
return this.accounts.size > 0;
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
//#endregion
|
|
566
|
+
exports.MattermostConnector = MattermostConnector;
|