hyperclaw 4.0.2 → 5.0.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.
Files changed (134) hide show
  1. package/README.md +54 -3
  2. package/dist/a2ui-protocol-CfBI44-Q.js +75 -0
  3. package/dist/agents-routing-ChHiZp36.js +327 -0
  4. package/dist/agents-routing-ChqZ6l2S.js +4 -0
  5. package/dist/api-keys-guide-BCcOl0Q7.js +149 -0
  6. package/dist/audit-BaIiyWFu.js +441 -0
  7. package/dist/bounty-tools-DWudyZie.js +211 -0
  8. package/dist/browser-tools-BsTeGMnX.js +5 -0
  9. package/dist/browser-tools-D8_rLe2p.js +179 -0
  10. package/dist/claw-tasks-CgTsiNE8.js +80 -0
  11. package/dist/connector-5N0-X_xs.js +194 -0
  12. package/dist/connector-B3v0qcXg.js +425 -0
  13. package/dist/connector-B8R3iBY1.js +280 -0
  14. package/dist/connector-BAM-08NN.js +189 -0
  15. package/dist/connector-BC8FIVu4.js +181 -0
  16. package/dist/connector-BDmwwaVc.js +213 -0
  17. package/dist/connector-BGjbBy69.js +225 -0
  18. package/dist/connector-BO2SRzfG.js +218 -0
  19. package/dist/connector-BfXky0L3.js +167 -0
  20. package/dist/connector-BiiSJpx3.js +192 -0
  21. package/dist/connector-BnDmIhIu.js +85 -0
  22. package/dist/connector-C1HSoUyk.js +189 -0
  23. package/dist/connector-CKQHZOXg.js +568 -0
  24. package/dist/connector-CRl-iidy.js +239 -0
  25. package/dist/connector-Ci9glMD-.js +340 -0
  26. package/dist/connector-CjtZIEDj.js +181 -0
  27. package/dist/connector-Ck6JtOsX.js +531 -0
  28. package/dist/connector-D8Kelee0.js +286 -0
  29. package/dist/connector-DAnRJ0oP.js +162 -0
  30. package/dist/connector-DXTp5PE8.js +508 -0
  31. package/dist/connector-Dih6dUPP.js +173 -0
  32. package/dist/connector-DqTH_tPX.js +182 -0
  33. package/dist/connector-DrnEiiyP.js +419 -0
  34. package/dist/connector-DtR5GGTX.js +167 -0
  35. package/dist/connector-Tky_qS_K.js +350 -0
  36. package/dist/connector-ZSc3oTTy.js +305 -0
  37. package/dist/connector-sW5yhU1m.js +498 -0
  38. package/dist/connector-u3ICd3Ic.js +552 -0
  39. package/dist/cost-tracker-DD9wtWsr.js +103 -0
  40. package/dist/credentials-store-C6ir0Dae.js +4 -0
  41. package/dist/credentials-store-H13LqOwJ.js +77 -0
  42. package/dist/cron-tasks-Bli7Kzd2.js +82 -0
  43. package/dist/daemon-Bg4GtCmc.js +318 -0
  44. package/dist/daemon-DhmwY8k4.js +5 -0
  45. package/dist/delivery-BmIYy9VQ.js +4 -0
  46. package/dist/delivery-pWUPBp1F.js +95 -0
  47. package/dist/destructive-gate-D6vWOdEl.js +101 -0
  48. package/dist/developer-keys-CPWT7Q6S.js +8 -0
  49. package/dist/developer-keys-DrrcUqFa.js +127 -0
  50. package/dist/doctor-BvCe8BBk.js +230 -0
  51. package/dist/doctor-CxyPLYsJ.js +6 -0
  52. package/dist/engine-CEDSqXfw.js +256 -0
  53. package/dist/engine-Da4JMNpI.js +7 -0
  54. package/dist/env-resolve-CiXbWYwe.js +10 -0
  55. package/dist/env-resolve-CmGWhWXJ.js +115 -0
  56. package/dist/extraction-tools-HOZstZ0y.js +91 -0
  57. package/dist/extraction-tools-m4lmAv7l.js +5 -0
  58. package/dist/form_data-Cz040rio.js +8657 -0
  59. package/dist/gmail-watch-setup-Du7DVV7S.js +40 -0
  60. package/dist/health-B-asI__D.js +6 -0
  61. package/dist/health-Ds2YlpTB.js +152 -0
  62. package/dist/heartbeat-engine-BYT5ayQH.js +83 -0
  63. package/dist/hub-D0XwdjM-.js +515 -0
  64. package/dist/hub-LiD5Iztb.js +6 -0
  65. package/dist/hyperclawbot-zvczQgKx.js +505 -0
  66. package/dist/inference-BKVkBREb.js +6 -0
  67. package/dist/inference-DCXH4Q3x.js +922 -0
  68. package/dist/knowledge-graph-iBG76fvm.js +131 -0
  69. package/dist/loader-CC45xGpC.js +4 -0
  70. package/dist/loader-CnEdOyjT.js +400 -0
  71. package/dist/logger-ybOp7VOC.js +83 -0
  72. package/dist/manager-03ipO9R0.js +105 -0
  73. package/dist/manager-BpDfbDjg.js +117 -0
  74. package/dist/manager-Bxl0sqlh.js +4 -0
  75. package/dist/manager-CrVDn6eN.js +6 -0
  76. package/dist/manager-FCgF1plu.js +218 -0
  77. package/dist/manager-rgCsaWT1.js +40 -0
  78. package/dist/mcp-CfoSU4Uz.js +139 -0
  79. package/dist/mcp-loader-DkRBsLpk.js +94 -0
  80. package/dist/memory-BlHL7JCO.js +4 -0
  81. package/dist/memory-DsS_eFvJ.js +270 -0
  82. package/dist/memory-auto-BkvtSFUw.js +5 -0
  83. package/dist/memory-auto-Bnz_-1wP.js +306 -0
  84. package/dist/memory-integration-cSYkZyEo.js +91 -0
  85. package/dist/moltbook-BtLDZTfM.js +81 -0
  86. package/dist/node-Dw2Gi-cP.js +222 -0
  87. package/dist/nodes-registry-B8dmrlLv.js +52 -0
  88. package/dist/oauth-flow-DQPvMHRH.js +150 -0
  89. package/dist/oauth-provider-Uo4Nib_c.js +110 -0
  90. package/dist/observability-BV-Yx0V9.js +89 -0
  91. package/dist/onboard-0WoDxbv_.js +10 -0
  92. package/dist/onboard-BXNXCQp4.js +4070 -0
  93. package/dist/orchestrator-DmnEvMaL.js +189 -0
  94. package/dist/orchestrator-RI3bpqqc.js +6 -0
  95. package/dist/pairing-6iM27aD8.js +196 -0
  96. package/dist/pairing-dGoiGepK.js +4 -0
  97. package/dist/pc-access-CgCsYrpt.js +8 -0
  98. package/dist/pc-access-_iH2aorG.js +819 -0
  99. package/dist/pending-approval-CUXjysAo.js +22 -0
  100. package/dist/reminders-store-Drjed_-h.js +58 -0
  101. package/dist/renderer-BVQrd0_g.js +225 -0
  102. package/dist/rules-BE4GV6cV.js +103 -0
  103. package/dist/run-main.js +1607 -443
  104. package/dist/runner-DatMMYYE.js +1271 -0
  105. package/dist/sdk/index.js +2 -2
  106. package/dist/sdk/index.mjs +2 -2
  107. package/dist/security-BqNyT4ID.js +4 -0
  108. package/dist/security-tpgqPWWH.js +73 -0
  109. package/dist/server-D4wVHiX9.js +4 -0
  110. package/dist/server-Dh3JlBFB.js +1255 -0
  111. package/dist/session-store-BUiPz0Vv.js +5 -0
  112. package/dist/session-store-is4B6qmD.js +113 -0
  113. package/dist/sessions-tools-CbUTFe4i.js +5 -0
  114. package/dist/sessions-tools-CeqD7iil.js +95 -0
  115. package/dist/skill-loader-BaNLVmJy.js +7 -0
  116. package/dist/skill-loader-HgpF6Vqs.js +159 -0
  117. package/dist/skill-runtime-CJN24QPW.js +102 -0
  118. package/dist/skill-runtime-w1ig_lcw.js +5 -0
  119. package/dist/src-BxPHKO5x.js +63 -0
  120. package/dist/src-DIc-L2IG.js +20 -0
  121. package/dist/src-g_rNx5rh.js +458 -0
  122. package/dist/sub-agent-tools-CHQoHz9c.js +39 -0
  123. package/dist/theme-DcxwcUgZ.js +180 -0
  124. package/dist/theme-cx0fkgWC.js +8 -0
  125. package/dist/tool-policy-CNT-mF2Z.js +189 -0
  126. package/dist/tts-elevenlabs-BRosZv-f.js +61 -0
  127. package/dist/update-check-C2Dz85wJ.js +81 -0
  128. package/dist/vision-BMmiIKy7.js +121 -0
  129. package/dist/vision-tools-DVuYc17I.js +51 -0
  130. package/dist/vision-tools-U3YC4L-g.js +5 -0
  131. package/dist/voice-transcription-B555DbWR.js +138 -0
  132. package/dist/website-watch-tools-DFMrJU-R.js +139 -0
  133. package/dist/website-watch-tools-Du3W5sN7.js +5 -0
  134. package/package.json +1 -1
@@ -0,0 +1,239 @@
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 ws = require_chunk.__toESM(require("ws"));
7
+ const events = require_chunk.__toESM(require("events"));
8
+
9
+ //#region extensions/twitch/src/connector.ts
10
+ const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "twitch-state.json");
11
+ const TWITCH_IRC_WS = "wss://irc-ws.chat.twitch.tv:443";
12
+ var TwitchConnector = class extends events.EventEmitter {
13
+ config;
14
+ ws = null;
15
+ running = false;
16
+ reconnectDelay = 1e3;
17
+ pingInterval = null;
18
+ constructor(config) {
19
+ super();
20
+ this.config = {
21
+ commandPrefix: "!",
22
+ whispers: true,
23
+ dmPolicy: "pairing",
24
+ allowFrom: [],
25
+ approvedPairings: [],
26
+ pendingPairings: {},
27
+ modsBypass: true,
28
+ ...config
29
+ };
30
+ }
31
+ async connect() {
32
+ await this.loadState();
33
+ await this.doConnect();
34
+ }
35
+ doConnect() {
36
+ return new Promise((resolve, reject) => {
37
+ const ws$1 = new ws.WebSocket(TWITCH_IRC_WS);
38
+ this.ws = ws$1;
39
+ ws$1.once("open", () => {
40
+ ws$1.send("CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands");
41
+ ws$1.send(`PASS ${this.config.oauthToken}`);
42
+ ws$1.send(`NICK ${this.config.username}`);
43
+ for (const ch of this.config.channels) ws$1.send(`JOIN #${ch.replace(/^#/, "").toLowerCase()}`);
44
+ this.running = true;
45
+ this.reconnectDelay = 1e3;
46
+ this.pingInterval = setInterval(() => ws$1.send("PING :tmi.twitch.tv"), 6e4);
47
+ console.log(chalk.default.green(` 🦅 Twitch: connected as ${this.config.username}, joined ${this.config.channels.join(", ")}`));
48
+ this.emit("connected", { username: this.config.username });
49
+ resolve();
50
+ });
51
+ ws$1.on("message", async (raw) => {
52
+ const lines = raw.toString().split("\r\n").filter(Boolean);
53
+ for (const line of lines) await this.handleLine(line);
54
+ });
55
+ ws$1.on("close", () => {
56
+ if (this.pingInterval) {
57
+ clearInterval(this.pingInterval);
58
+ this.pingInterval = null;
59
+ }
60
+ if (this.running) {
61
+ console.log(chalk.default.yellow(` ⚠ Twitch: disconnected, reconnecting in ${this.reconnectDelay}ms`));
62
+ setTimeout(() => {
63
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
64
+ this.doConnect();
65
+ }, this.reconnectDelay);
66
+ }
67
+ });
68
+ ws$1.on("error", (err) => {
69
+ console.log(chalk.default.yellow(` ⚠ Twitch: ${err.message}`));
70
+ if (!this.running) reject(err);
71
+ });
72
+ });
73
+ }
74
+ disconnect() {
75
+ this.running = false;
76
+ if (this.pingInterval) {
77
+ clearInterval(this.pingInterval);
78
+ this.pingInterval = null;
79
+ }
80
+ this.ws?.close();
81
+ this.ws = null;
82
+ }
83
+ async handleLine(line) {
84
+ if (line === "PING :tmi.twitch.tv") {
85
+ this.ws?.send("PONG :tmi.twitch.tv");
86
+ return;
87
+ }
88
+ const tags = this.parseTags(line);
89
+ const parsed = this.parseIRC(line);
90
+ if (!parsed) return;
91
+ const { command, prefix, params, trailing } = parsed;
92
+ const username = prefix?.split("!")[0]?.toLowerCase() || "";
93
+ if (username === this.config.username.toLowerCase()) return;
94
+ if (command === "PRIVMSG") {
95
+ const channel = params[0];
96
+ const text = trailing || "";
97
+ const isWhisper = false;
98
+ if (this.config.commandPrefix && !text.startsWith(this.config.commandPrefix) && !isWhisper) return;
99
+ const body = this.config.commandPrefix ? text.slice(this.config.commandPrefix.length).trim() : text;
100
+ if (!body) return;
101
+ const isMod = tags["mod"] === "1" || tags["badges"]?.includes("broadcaster");
102
+ const allowed = await this.checkPolicy(username, channel, body, isMod);
103
+ if (!allowed) return;
104
+ this.emit("message", {
105
+ id: tags["id"] || `twitch-${Date.now()}`,
106
+ channelId: "twitch",
107
+ from: username,
108
+ displayName: tags["display-name"] || username,
109
+ chatId: channel,
110
+ text: body,
111
+ timestamp: tags["tmi-sent-ts"] ? new Date(Number(tags["tmi-sent-ts"])).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
112
+ isDM: false,
113
+ isMod
114
+ });
115
+ return;
116
+ }
117
+ if (command === "WHISPER" && this.config.whispers) {
118
+ const text = trailing || "";
119
+ if (!text) return;
120
+ const allowed = await this.checkPolicy(username, "whisper", text, false);
121
+ if (!allowed) return;
122
+ this.emit("message", {
123
+ id: `twitch-whisper-${Date.now()}`,
124
+ channelId: "twitch",
125
+ from: username,
126
+ displayName: tags["display-name"] || username,
127
+ chatId: `whisper:${username}`,
128
+ text,
129
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
130
+ isDM: true,
131
+ isMod: false
132
+ });
133
+ }
134
+ }
135
+ async checkPolicy(username, chatId, text, isMod) {
136
+ if (this.config.dmPolicy === "none") return false;
137
+ if (this.config.dmPolicy === "open") return true;
138
+ if (this.config.modsBypass && isMod) return true;
139
+ if (this.config.dmPolicy === "allowlist") {
140
+ if (this.config.allowFrom.includes(username)) return true;
141
+ await this.sendChat(chatId, `@${username} You are not on the allowlist.`);
142
+ return false;
143
+ }
144
+ if (this.config.dmPolicy === "pairing") {
145
+ if (this.config.approvedPairings.includes(username)) return true;
146
+ const upper = text.trim().toUpperCase();
147
+ if (this.config.pendingPairings[upper]) {
148
+ this.config.approvedPairings.push(username);
149
+ delete this.config.pendingPairings[upper];
150
+ await this.saveState();
151
+ await this.sendChat(chatId, `@${username} Paired! You can now talk to the assistant.`);
152
+ return true;
153
+ }
154
+ const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
155
+ this.config.pendingPairings[code] = username;
156
+ await this.saveState();
157
+ await this.sendChat(chatId, `@${username} Pairing required. Code: ${code} — approve: hyperclaw pairing approve twitch ${code}`);
158
+ return false;
159
+ }
160
+ return false;
161
+ }
162
+ async sendChat(channel, text) {
163
+ if (!this.ws || this.ws.readyState !== ws.WebSocket.OPEN) return;
164
+ const ch = channel.startsWith("#") ? channel : `#${channel}`;
165
+ const chunks = text.match(/.{1,490}/g) || [text];
166
+ for (const chunk of chunks) {
167
+ this.ws.send(`PRIVMSG ${ch} :${chunk}`);
168
+ await new Promise((r) => setTimeout(r, 150));
169
+ }
170
+ }
171
+ async sendWhisper(username, text) {
172
+ if (!this.ws || this.ws.readyState !== ws.WebSocket.OPEN) return;
173
+ const ch = `#${this.config.channels[0]?.replace(/^#/, "") || this.config.username}`;
174
+ this.ws.send(`PRIVMSG ${ch} :/w ${username} ${text}`);
175
+ }
176
+ approvePairing(code) {
177
+ const upper = code.toUpperCase();
178
+ if (!this.config.pendingPairings[upper]) return false;
179
+ this.config.approvedPairings.push(this.config.pendingPairings[upper]);
180
+ delete this.config.pendingPairings[upper];
181
+ this.saveState();
182
+ return true;
183
+ }
184
+ parseTags(line) {
185
+ if (!line.startsWith("@")) return {};
186
+ const tagStr = line.slice(1, line.indexOf(" "));
187
+ const tags = {};
188
+ for (const part of tagStr.split(";")) {
189
+ const [k, v] = part.split("=");
190
+ if (k) tags[k] = v || "";
191
+ }
192
+ return tags;
193
+ }
194
+ parseIRC(line) {
195
+ let rest = line.startsWith("@") ? line.slice(line.indexOf(" ") + 1) : line;
196
+ let prefix;
197
+ if (rest.startsWith(":")) {
198
+ const spaceIdx = rest.indexOf(" ");
199
+ prefix = rest.slice(1, spaceIdx);
200
+ rest = rest.slice(spaceIdx + 1);
201
+ }
202
+ const trailingIdx = rest.indexOf(" :");
203
+ let trailing;
204
+ if (trailingIdx !== -1) {
205
+ trailing = rest.slice(trailingIdx + 2);
206
+ rest = rest.slice(0, trailingIdx);
207
+ }
208
+ const parts = rest.trim().split(" ");
209
+ const command = parts[0];
210
+ const params = parts.slice(1).filter(Boolean);
211
+ if (!command) return null;
212
+ return {
213
+ command,
214
+ prefix,
215
+ params,
216
+ trailing
217
+ };
218
+ }
219
+ async loadState() {
220
+ try {
221
+ const s = await fs_extra.default.readJson(STATE_FILE);
222
+ if (s.p) this.config.pendingPairings = s.p;
223
+ if (s.a) this.config.approvedPairings = s.a;
224
+ } catch {}
225
+ }
226
+ async saveState() {
227
+ await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
228
+ await fs_extra.default.writeJson(STATE_FILE, {
229
+ p: this.config.pendingPairings,
230
+ a: this.config.approvedPairings
231
+ }, { spaces: 2 });
232
+ }
233
+ isRunning() {
234
+ return this.running;
235
+ }
236
+ };
237
+
238
+ //#endregion
239
+ exports.TwitchConnector = TwitchConnector;
@@ -0,0 +1,340 @@
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 http = require_chunk.__toESM(require("http"));
8
+ const https = require_chunk.__toESM(require("https"));
9
+ const events = require_chunk.__toESM(require("events"));
10
+
11
+ //#region extensions/nextcloud/src/connector.ts
12
+ const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "nextcloud-talk-state.json");
13
+ const DEFAULT_PORT = 8788;
14
+ const DEFAULT_HOST = "0.0.0.0";
15
+ const DEFAULT_PATH = "/nextcloud-talk-webhook";
16
+ const DEFAULT_CHUNK = 32e3;
17
+ function ocsReq(baseUrl, user, password, method, apiPath, body) {
18
+ return new Promise((resolve, reject) => {
19
+ const url = new URL(`${baseUrl}/ocs/v2.php/apps/spreed/api/v4${apiPath}`);
20
+ const isHttps = url.protocol === "https:";
21
+ const mod = isHttps ? https.default : http.default;
22
+ const auth = Buffer.from(`${user}:${password}`).toString("base64");
23
+ const payload = body ? JSON.stringify(body) : null;
24
+ const req = mod.request({
25
+ hostname: url.hostname,
26
+ port: url.port || (isHttps ? 443 : 80),
27
+ path: url.pathname + url.search,
28
+ method,
29
+ headers: {
30
+ Authorization: `Basic ${auth}`,
31
+ "OCS-APIRequest": "true",
32
+ Accept: "application/json",
33
+ ...payload ? {
34
+ "Content-Type": "application/json",
35
+ "Content-Length": Buffer.byteLength(payload)
36
+ } : {}
37
+ }
38
+ }, (res) => {
39
+ let data = "";
40
+ res.on("data", (c) => data += c);
41
+ res.on("end", () => {
42
+ try {
43
+ const parsed = JSON.parse(data);
44
+ const ocs = parsed?.ocs;
45
+ if (ocs?.meta?.statuscode >= 400) reject(new Error(ocs.meta.message || "OCS error"));
46
+ else resolve(ocs?.data ?? parsed);
47
+ } catch {
48
+ reject(new Error("Nextcloud: invalid JSON"));
49
+ }
50
+ });
51
+ });
52
+ req.on("error", reject);
53
+ if (payload) req.write(payload);
54
+ req.end();
55
+ });
56
+ }
57
+ /** Send a message via the Talk bot API (X-Nextcloud-Talk-Bot-Secret auth). */
58
+ function botSend(baseUrl, secret, token, message, referenceId) {
59
+ return new Promise((resolve, reject) => {
60
+ const url = new URL(`${baseUrl}/ocs/v2.php/apps/spreed/api/v1/bot/${token}/message`);
61
+ const isHttps = url.protocol === "https:";
62
+ const mod = isHttps ? https.default : http.default;
63
+ const payload = JSON.stringify({
64
+ message,
65
+ referenceId: referenceId || crypto.default.randomBytes(8).toString("hex")
66
+ });
67
+ const req = mod.request({
68
+ hostname: url.hostname,
69
+ port: url.port || (isHttps ? 443 : 80),
70
+ path: url.pathname,
71
+ method: "POST",
72
+ headers: {
73
+ "X-Nextcloud-Talk-Bot-Secret": secret,
74
+ "OCS-APIRequest": "true",
75
+ "Content-Type": "application/json",
76
+ "Content-Length": Buffer.byteLength(payload)
77
+ }
78
+ }, (res) => {
79
+ let data = "";
80
+ res.on("data", (c) => data += c);
81
+ res.on("end", () => {
82
+ try {
83
+ resolve(JSON.parse(data));
84
+ } catch {
85
+ resolve({});
86
+ }
87
+ });
88
+ });
89
+ req.on("error", reject);
90
+ req.write(payload);
91
+ req.end();
92
+ });
93
+ }
94
+ function chunkText(text, limit, mode) {
95
+ if (mode === "newline") {
96
+ const paras = text.split(/\n\n+/);
97
+ const chunks$1 = [];
98
+ let cur = "";
99
+ for (const p of paras) if ((cur + "\n\n" + p).length > limit && cur) {
100
+ chunks$1.push(cur.trim());
101
+ cur = p;
102
+ } else cur = cur ? cur + "\n\n" + p : p;
103
+ if (cur) chunks$1.push(cur.trim());
104
+ return chunks$1.filter(Boolean);
105
+ }
106
+ const chunks = [];
107
+ for (let i = 0; i < text.length; i += limit) chunks.push(text.slice(i, i + limit));
108
+ return chunks.length ? chunks : [""];
109
+ }
110
+ var NextcloudTalkConnector = class extends events.EventEmitter {
111
+ config;
112
+ server = null;
113
+ running = false;
114
+ resolvedSecret = "";
115
+ resolvedApiPassword = "";
116
+ /** Cache: room token → isDM (room.type === 1) */
117
+ roomTypeCache = /* @__PURE__ */ new Map();
118
+ constructor(config) {
119
+ super();
120
+ this.config = {
121
+ dmPolicy: "pairing",
122
+ allowFrom: [],
123
+ groupPolicy: "allowlist",
124
+ groupAllowFrom: [],
125
+ rooms: {},
126
+ approvedPairings: [],
127
+ pendingPairings: {},
128
+ ...config
129
+ };
130
+ }
131
+ async resolveCredentials() {
132
+ this.resolvedSecret = this.config.botSecret || (this.config.botSecretFile ? (await fs_extra.default.readFile(this.config.botSecretFile, "utf8")).trim() : "");
133
+ if (!this.resolvedSecret) throw new Error("nextcloud-talk: botSecret or botSecretFile is required");
134
+ this.resolvedApiPassword = this.config.apiPassword || (this.config.apiPasswordFile ? (await fs_extra.default.readFile(this.config.apiPasswordFile, "utf8")).trim() : "");
135
+ }
136
+ async connect() {
137
+ await this.resolveCredentials();
138
+ await this.loadState();
139
+ this.running = true;
140
+ await this.startWebhookServer();
141
+ const port = this.config.webhookPort ?? DEFAULT_PORT;
142
+ const wPath = this.config.webhookPath ?? DEFAULT_PATH;
143
+ const publicUrl = this.config.webhookPublicUrl || `http://localhost:${port}${wPath}`;
144
+ console.log(chalk.default.green(` ☁️ Nextcloud Talk: webhook listening at ${publicUrl}`));
145
+ this.emit("connected", { webhookUrl: publicUrl });
146
+ }
147
+ disconnect() {
148
+ this.running = false;
149
+ this.server?.close();
150
+ this.server = null;
151
+ }
152
+ startWebhookServer() {
153
+ return new Promise((resolve, reject) => {
154
+ this.server = http.default.createServer((req, res) => {
155
+ const wPath = this.config.webhookPath ?? DEFAULT_PATH;
156
+ if (req.url !== wPath || req.method !== "POST") {
157
+ res.writeHead(404);
158
+ res.end();
159
+ return;
160
+ }
161
+ let body = "";
162
+ req.on("data", (c) => body += c.toString());
163
+ req.on("end", () => {
164
+ const random = req.headers["x-nextcloud-talk-random"];
165
+ const sig = req.headers["x-nextcloud-talk-signature"];
166
+ if (!this.verifySignature(random || "", body, sig || "")) {
167
+ console.log(chalk.default.yellow(" ⚠ Nextcloud Talk: invalid webhook signature"));
168
+ res.writeHead(401);
169
+ res.end();
170
+ return;
171
+ }
172
+ res.writeHead(200);
173
+ res.end();
174
+ this.handlePayload(body).catch((e) => console.error(`[nextcloud-talk] handler error: ${e.message}`));
175
+ });
176
+ });
177
+ const port = this.config.webhookPort ?? DEFAULT_PORT;
178
+ const host = this.config.webhookHost ?? DEFAULT_HOST;
179
+ this.server.listen(port, host, () => resolve());
180
+ this.server.on("error", reject);
181
+ });
182
+ }
183
+ verifySignature(random, body, signature) {
184
+ if (!this.resolvedSecret) return false;
185
+ const expected = crypto.default.createHmac("sha256", this.resolvedSecret).update(random + body).digest("hex");
186
+ try {
187
+ return crypto.default.timingSafeEqual(Buffer.from(signature.toLowerCase()), Buffer.from(expected.toLowerCase()));
188
+ } catch {
189
+ return false;
190
+ }
191
+ }
192
+ async handlePayload(raw) {
193
+ let payload;
194
+ try {
195
+ payload = JSON.parse(raw);
196
+ } catch {
197
+ return;
198
+ }
199
+ const objectType = payload?.object?.type || "";
200
+ const actorId = payload?.actor?.id || "";
201
+ const actorName = payload?.actor?.name || actorId;
202
+ const token = payload?.target?.id || "";
203
+ if (!token || !actorId) return;
204
+ switch (objectType) {
205
+ case "chat-message": {
206
+ const msgContent = payload.object?.content;
207
+ const text = (typeof msgContent === "object" ? msgContent?.message : msgContent) || payload.object?.name || "";
208
+ if (!text) return;
209
+ await this.routeMessage(token, actorId, actorName, text);
210
+ break;
211
+ }
212
+ case "reaction": {
213
+ const emoji = payload.object?.name || payload.object?.content || "";
214
+ const reactedId = String(payload.object?.id || "");
215
+ if (!emoji) return;
216
+ const text = `[reaction:${emoji}:${reactedId}]`;
217
+ await this.routeMessage(token, actorId, actorName, text);
218
+ break;
219
+ }
220
+ default: break;
221
+ }
222
+ }
223
+ async routeMessage(token, userId, displayName, text) {
224
+ const isDM = await this.detectDM(token);
225
+ if (isDM) {
226
+ const allowed = await this.checkDMPolicy(userId, text, token);
227
+ if (!allowed) return;
228
+ } else if (!this.checkGroupPolicy(token, userId, text)) return;
229
+ this.emit("message", {
230
+ channelId: "nextcloud-talk",
231
+ chatId: token,
232
+ from: userId,
233
+ displayName,
234
+ text,
235
+ isDM
236
+ });
237
+ }
238
+ /** Look up whether a room token is a DM (type=1). Caches results. */
239
+ async detectDM(token) {
240
+ if (this.roomTypeCache.has(token)) return this.roomTypeCache.get(token);
241
+ if (!this.config.apiUser || !this.resolvedApiPassword) {
242
+ this.roomTypeCache.set(token, false);
243
+ return false;
244
+ }
245
+ try {
246
+ const room = await ocsReq(this.config.baseUrl, this.config.apiUser, this.resolvedApiPassword, "GET", `/room/${token}`);
247
+ const isDM = room?.type === 1;
248
+ this.roomTypeCache.set(token, isDM);
249
+ return isDM;
250
+ } catch {
251
+ this.roomTypeCache.set(token, false);
252
+ return false;
253
+ }
254
+ }
255
+ async checkDMPolicy(userId, text, token) {
256
+ switch (this.config.dmPolicy) {
257
+ case "disabled": return false;
258
+ case "open": return true;
259
+ case "allowlist":
260
+ if (this.config.allowFrom.includes(userId) || this.config.allowFrom.includes("*")) return true;
261
+ await this.sendMessage(token, "HyperClaw: Not on allowlist.");
262
+ return false;
263
+ case "pairing": {
264
+ if (this.config.approvedPairings.includes(userId)) return true;
265
+ const upper = text.trim().toUpperCase().match(/[A-Z0-9]{6}/)?.[0];
266
+ if (upper && this.config.pendingPairings[upper]) {
267
+ this.config.approvedPairings.push(userId);
268
+ delete this.config.pendingPairings[upper];
269
+ await this.saveState();
270
+ await this.sendMessage(token, "Paired!");
271
+ this.emit("pairing:approved", {
272
+ userId,
273
+ channelId: "nextcloud-talk"
274
+ });
275
+ return true;
276
+ }
277
+ const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
278
+ this.config.pendingPairings[code] = userId;
279
+ await this.saveState();
280
+ await this.sendMessage(token, `Pairing code: ${code}\nApprove: hyperclaw pairing approve nextcloud-talk ${code}`);
281
+ return false;
282
+ }
283
+ }
284
+ return false;
285
+ }
286
+ checkGroupPolicy(token, userId, text) {
287
+ const policy = this.config.groupPolicy;
288
+ if (policy === "disabled") return false;
289
+ const roomCfg = this.config.rooms[token];
290
+ if (policy === "open") {
291
+ if (roomCfg?.allowFrom?.length && !roomCfg.allowFrom.includes(userId)) return false;
292
+ const global$1 = this.config.groupAllowFrom;
293
+ if (global$1.length && !global$1.includes(userId)) return false;
294
+ return true;
295
+ }
296
+ if (!roomCfg) return false;
297
+ const global = this.config.groupAllowFrom;
298
+ if (global.length && !global.includes(userId)) return false;
299
+ if (roomCfg.allowFrom?.length && !roomCfg.allowFrom.includes(userId)) return false;
300
+ if (roomCfg.requireMention !== false) {
301
+ if (!text.includes("@HyperClaw") && !text.startsWith("!")) return false;
302
+ }
303
+ return true;
304
+ }
305
+ async sendMessage(token, text) {
306
+ const limit = this.config.textChunkLimit ?? DEFAULT_CHUNK;
307
+ const mode = this.config.chunkMode ?? "length";
308
+ const chunks = chunkText(text, limit, mode);
309
+ for (const chunk of chunks) if (this.config.apiUser && this.resolvedApiPassword) await ocsReq(this.config.baseUrl, this.config.apiUser, this.resolvedApiPassword, "POST", `/chat/${token}`, { message: chunk });
310
+ else await botSend(this.config.baseUrl, this.resolvedSecret, token, chunk);
311
+ }
312
+ approvePairing(code) {
313
+ const upper = code.toUpperCase();
314
+ if (!this.config.pendingPairings[upper]) return false;
315
+ this.config.approvedPairings.push(this.config.pendingPairings[upper]);
316
+ delete this.config.pendingPairings[upper];
317
+ this.saveState();
318
+ return true;
319
+ }
320
+ async loadState() {
321
+ try {
322
+ const s = await fs_extra.default.readJson(STATE_FILE);
323
+ if (s.p) this.config.pendingPairings = s.p;
324
+ if (s.a) this.config.approvedPairings = s.a;
325
+ } catch {}
326
+ }
327
+ async saveState() {
328
+ await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
329
+ await fs_extra.default.writeJson(STATE_FILE, {
330
+ p: this.config.pendingPairings,
331
+ a: this.config.approvedPairings
332
+ }, { spaces: 2 });
333
+ }
334
+ isRunning() {
335
+ return this.running;
336
+ }
337
+ };
338
+
339
+ //#endregion
340
+ exports.NextcloudTalkConnector = NextcloudTalkConnector;