hyperclaw 5.2.7 → 5.2.9

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 (207) hide show
  1. package/dist/a2ui-protocol-DEsfqO7h.js +75 -0
  2. package/dist/agents-routing-Cee7wrfi.js +398 -0
  3. package/dist/agents-routing-ChorJKFL.js +6 -0
  4. package/dist/agents-routing-Cpg20-1e.js +398 -0
  5. package/dist/agents-routing-uNzqjgOr.js +6 -0
  6. package/dist/api-key-validation-DgOBmp8Y.js +64 -0
  7. package/dist/api-key-validation-DydlUth1.js +64 -0
  8. package/dist/api-keys-guide--73Bq0Ey.js +149 -0
  9. package/dist/api-keys-guide-DqRGa4x7.js +149 -0
  10. package/dist/audit-CX5poVMR.js +445 -0
  11. package/dist/audit-Dntx9fG9.js +445 -0
  12. package/dist/banner-B_rR7FPO.js +7 -0
  13. package/dist/banner-Bb7CderS.js +143 -0
  14. package/dist/bounty-tools-BoU1NN5N.js +211 -0
  15. package/dist/bounty-tools-Dn9Yq7V1.js +211 -0
  16. package/dist/browser-tools-CJ9M9o22.js +179 -0
  17. package/dist/browser-tools-CXxWxA1c.js +5 -0
  18. package/dist/chat-C07wF0mM.js +494 -0
  19. package/dist/chat-D1Zc73I5.js +513 -0
  20. package/dist/claw-tasks-BLqd1a0Q.js +80 -0
  21. package/dist/claw-tasks-ChqkHdFs.js +80 -0
  22. package/dist/config-BlLlJ6Er.js +7 -0
  23. package/dist/config-Bzues-G2.js +7 -0
  24. package/dist/config-DGAAJ49A.js +261 -0
  25. package/dist/config-SgDxKyfV.js +261 -0
  26. package/dist/connector-1efnZgQN.js +566 -0
  27. package/dist/connector-B5q1_srT.js +286 -0
  28. package/dist/connector-BMFLJ4fr.js +508 -0
  29. package/dist/connector-BZYv9siY.js +189 -0
  30. package/dist/connector-B_XkXm-j.js +218 -0
  31. package/dist/connector-BkY1I6gf.js +189 -0
  32. package/dist/connector-C2Z3RN1z.js +350 -0
  33. package/dist/connector-C7aYvVzU.js +225 -0
  34. package/dist/connector-CXXYOyHw.js +164 -0
  35. package/dist/connector-Ca1J23HX.js +167 -0
  36. package/dist/connector-Cjqc656I.js +181 -0
  37. package/dist/connector-CluRienN.js +425 -0
  38. package/dist/connector-CuNz2eP-.js +305 -0
  39. package/dist/connector-DHL_oeHy.js +552 -0
  40. package/dist/connector-DJ79rd1L.js +173 -0
  41. package/dist/connector-DcLE6xCZ.js +239 -0
  42. package/dist/connector-DcyQTJnJ.js +162 -0
  43. package/dist/connector-DgyX9qSc.js +192 -0
  44. package/dist/connector-DnDXXZ7L.js +182 -0
  45. package/dist/connector-DqUslg-X.js +213 -0
  46. package/dist/connector-Duc-HmRZ.js +85 -0
  47. package/dist/connector-IV0QFer8.js +498 -0
  48. package/dist/connector-OnsLxE8G.js +194 -0
  49. package/dist/connector-UYu_TS0X.js +204 -0
  50. package/dist/connector-cCA5ffmp.js +340 -0
  51. package/dist/connector-fbNfx4_L.js +568 -0
  52. package/dist/connector-fi2vlwbO.js +276 -0
  53. package/dist/connector-l3LD8IDN.js +419 -0
  54. package/dist/cost-tracker-CgEXyEtz.js +103 -0
  55. package/dist/cost-tracker-DCXDUzBI.js +103 -0
  56. package/dist/credentials-store-1LDtNReY.js +89 -0
  57. package/dist/credentials-store-BFxEJR00.js +7 -0
  58. package/dist/credentials-store-Bmm9e1SS.js +7 -0
  59. package/dist/credentials-store-D8ERbGR2.js +89 -0
  60. package/dist/cron-tasks-1E6wKpTv.js +85 -0
  61. package/dist/cron-tasks-OQbgmenS.js +85 -0
  62. package/dist/daemon-B13UIqvL.js +7 -0
  63. package/dist/daemon-CzOW-1PS.js +421 -0
  64. package/dist/daemon-aVX-WGz1.js +421 -0
  65. package/dist/daemon-iFmVBPXN.js +7 -0
  66. package/dist/delivery-B8YGmrq5.js +4 -0
  67. package/dist/delivery-DWsU6gx-.js +95 -0
  68. package/dist/delivery-Pko6sSkt.js +4 -0
  69. package/dist/delivery-hMHFRZwy.js +95 -0
  70. package/dist/destructive-gate-C2TrWsp2.js +101 -0
  71. package/dist/destructive-gate-bnkroJWG.js +101 -0
  72. package/dist/developer-keys-BWXHaWxY.js +127 -0
  73. package/dist/developer-keys-CzDxVczE.js +8 -0
  74. package/dist/device-auth-store-C1bCwXO2.js +7 -0
  75. package/dist/device-auth-store-DIZTOz4V.js +88 -0
  76. package/dist/doctor-C6nAGdH8.js +233 -0
  77. package/dist/doctor-mgWumA25.js +6 -0
  78. package/dist/engine-BGRTi0fo.js +327 -0
  79. package/dist/engine-BvCEhaUn.js +7 -0
  80. package/dist/engine-ByQ-0sWM.js +7 -0
  81. package/dist/engine-gnMjO743.js +327 -0
  82. package/dist/env-resolve-BdagnXhK.js +151 -0
  83. package/dist/env-resolve-CHxjGo8u.js +151 -0
  84. package/dist/env-resolve-NEtsGacw.js +10 -0
  85. package/dist/env-resolve-pIETNTpQ.js +10 -0
  86. package/dist/extraction-tools-BE6z_Yw5.js +91 -0
  87. package/dist/extraction-tools-CJsdyBST.js +5 -0
  88. package/dist/form_data-B2_0EoWj.js +8657 -0
  89. package/dist/gmail-watch-setup-1RGIHNdu.js +42 -0
  90. package/dist/gmail-watch-setup-Brkj94Sy.js +42 -0
  91. package/dist/health-BMUmUNoe.js +152 -0
  92. package/dist/health-C8n9RH5O.js +6 -0
  93. package/dist/heartbeat-engine-D6oSpgxx.js +89 -0
  94. package/dist/heartbeat-engine-aRbab8a5.js +89 -0
  95. package/dist/hub-BJM2KXLO.js +6 -0
  96. package/dist/hub-Bb_dYECE.js +512 -0
  97. package/dist/hyperclawbot-CgrV46DA.js +516 -0
  98. package/dist/hyperclawbot-DzP_v3iA.js +516 -0
  99. package/dist/inference-BHJFPEKL.js +8 -0
  100. package/dist/inference-CFBkvLpE.js +2854 -0
  101. package/dist/inference-G4MbdErG.js +8 -0
  102. package/dist/inference-vweXyh27.js +2854 -0
  103. package/dist/knowledge-graph-9UNrsiIY.js +134 -0
  104. package/dist/knowledge-graph-yeMPBPP8.js +134 -0
  105. package/dist/loader-BXYJl25e.js +6 -0
  106. package/dist/loader-DIPs649t.js +410 -0
  107. package/dist/loader-Dq_cDlOW.js +6 -0
  108. package/dist/loader-gTdKBwiI.js +410 -0
  109. package/dist/logger-C3ZCDSkc.js +86 -0
  110. package/dist/logger-CG38Idq4.js +86 -0
  111. package/dist/manager--wG9JdFW.js +120 -0
  112. package/dist/manager-BI3izlRG.js +120 -0
  113. package/dist/manager-BNc21xgG.js +6 -0
  114. package/dist/manager-CQ3MWNHY.js +250 -0
  115. package/dist/manager-DWJ7WZcY.js +250 -0
  116. package/dist/manager-DYfzqckn.js +35 -0
  117. package/dist/mcp-CklaYr_6.js +142 -0
  118. package/dist/mcp-SsMEvl28.js +142 -0
  119. package/dist/mcp-loader-9v8eUsNI.js +93 -0
  120. package/dist/mcp-loader-DLrp_oZJ.js +93 -0
  121. package/dist/memory-BCYvdqwo.js +273 -0
  122. package/dist/memory-BGgCBSx1.js +6 -0
  123. package/dist/memory-auto-Bh52cQJP.js +5 -0
  124. package/dist/memory-auto-Bow9u_L7.js +306 -0
  125. package/dist/memory-auto-BupvVwNd.js +306 -0
  126. package/dist/memory-auto-CgBAI8mm.js +5 -0
  127. package/dist/memory-integration-4oGqX6rr.js +91 -0
  128. package/dist/memory-integration-CveUEI3V.js +91 -0
  129. package/dist/moltbook-B3DNdh40.js +81 -0
  130. package/dist/moltbook-xP7VXKlX.js +81 -0
  131. package/dist/node-C4esBfbX.js +226 -0
  132. package/dist/node-urDjajMt.js +226 -0
  133. package/dist/nodes-registry-Cd4eWw80.js +52 -0
  134. package/dist/nodes-registry-DLUZhEMS.js +52 -0
  135. package/dist/oauth-flow-BbLQTzZk.js +148 -0
  136. package/dist/oauth-flow-Bt-LaRHV.js +148 -0
  137. package/dist/oauth-provider-CVTKgj35.js +111 -0
  138. package/dist/oauth-provider-UZyG84s7.js +111 -0
  139. package/dist/observability-BtLyuxcz.js +89 -0
  140. package/dist/observability-lwYm4aoB.js +89 -0
  141. package/dist/onboard-B3drurt-.js +3812 -0
  142. package/dist/onboard-BV5Poocl.js +13 -0
  143. package/dist/onboard-DEwuHrMj.js +14 -0
  144. package/dist/onboard-UiynbNQy.js +3909 -0
  145. package/dist/orchestrator-BXyIgAeH.js +189 -0
  146. package/dist/orchestrator-DMZkAVa5.js +189 -0
  147. package/dist/orchestrator-MLTc4NYu.js +6 -0
  148. package/dist/orchestrator-rVGu7yYr.js +6 -0
  149. package/dist/osint-Bsf6RGPv.js +283 -0
  150. package/dist/osint-chat-Ark94iFc.js +789 -0
  151. package/dist/osint-chat-Hn8qpsC1.js +836 -0
  152. package/dist/osint-f9DeXT6j.js +283 -0
  153. package/dist/pairing-2vAiDBjN.js +6 -0
  154. package/dist/pairing-B4NoBvyE.js +207 -0
  155. package/dist/pc-access-BLnc-DYp.js +858 -0
  156. package/dist/pc-access-CTNtG2LD.js +8 -0
  157. package/dist/pending-approval-C4ZaHHWl.js +22 -0
  158. package/dist/pending-approval-CHUZ_qT6.js +22 -0
  159. package/dist/reminders-store-BixTWL1h.js +58 -0
  160. package/dist/renderer-B1ToXngl.js +228 -0
  161. package/dist/rules-Cqen1Mpt.js +106 -0
  162. package/dist/run-main.js +98 -94
  163. package/dist/runner-B9xANekJ.js +1274 -0
  164. package/dist/runner-Cr1_mwnU.js +1274 -0
  165. package/dist/security--17Fxo5Z.js +4 -0
  166. package/dist/security-B4vH02lO.js +4 -0
  167. package/dist/security-DP1qtJfL.js +90 -0
  168. package/dist/security-HOOGCw5z.js +90 -0
  169. package/dist/server-CRhXiGI9.js +4 -0
  170. package/dist/server-DUDXqJSo.js +1365 -0
  171. package/dist/server-De4H45Ju.js +1365 -0
  172. package/dist/server-ha59nA8a.js +4 -0
  173. package/dist/session-store-7sEPyV16.js +5 -0
  174. package/dist/session-store-Ce2QMSL_.js +141 -0
  175. package/dist/sessions-tools-CWr_pDtp.js +5 -0
  176. package/dist/sessions-tools-DKVu9aIN.js +95 -0
  177. package/dist/skill-loader-DK19Jm4e.js +7 -0
  178. package/dist/skill-loader-Dfs9VNM-.js +160 -0
  179. package/dist/skill-runtime-BRp2D8Jb.js +5 -0
  180. package/dist/skill-runtime-BeKh2rD_.js +5 -0
  181. package/dist/skill-runtime-C8bNwKwz.js +104 -0
  182. package/dist/skill-runtime-CcpC2Zfc.js +104 -0
  183. package/dist/src-B8LzGLSY.js +63 -0
  184. package/dist/src-BxmkZ9RH.js +63 -0
  185. package/dist/src-DUoc6_kn.js +458 -0
  186. package/dist/src-DjTtmSRg.js +20 -0
  187. package/dist/src-n_46LPDi.js +458 -0
  188. package/dist/sub-agent-tools-CldaMfd5.js +39 -0
  189. package/dist/sub-agent-tools-q5JqEze_.js +39 -0
  190. package/dist/tool-policy-DtGf3Ifq.js +189 -0
  191. package/dist/tool-policy-QXF3MMxu.js +189 -0
  192. package/dist/tts-elevenlabs-1zWD3QJw.js +64 -0
  193. package/dist/tts-elevenlabs-y6HGWWDS.js +64 -0
  194. package/dist/update-check-C4te7JmY.js +6 -0
  195. package/dist/update-check-GDue_it1.js +98 -0
  196. package/dist/vision-DV2ubVjr.js +167 -0
  197. package/dist/vision-tools-Cb86uMdh.js +5 -0
  198. package/dist/vision-tools-CbVfyTZT.js +5 -0
  199. package/dist/vision-tools-DieVQp6s.js +51 -0
  200. package/dist/vision-tools-DlnxaZjg.js +51 -0
  201. package/dist/vision-u4kMThdo.js +167 -0
  202. package/dist/voice-transcription-BolTT_HG.js +170 -0
  203. package/dist/voice-transcription-DgON5qaF.js +170 -0
  204. package/dist/website-watch-tools-B8L_NgwT.js +5 -0
  205. package/dist/website-watch-tools-Drm5HjIX.js +176 -0
  206. package/package.json +4 -1
  207. package/static/chat.html +9 -3
@@ -0,0 +1,204 @@
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 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/bluebubbles/src/connector.ts
12
+ const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "bluebubbles-state.json");
13
+ const MAX_CA_CERT_BYTES = 1024 * 1024;
14
+ const ALLOWED_CA_CERT_EXTENSIONS = new Set([
15
+ ".pem",
16
+ ".crt",
17
+ ".cer"
18
+ ]);
19
+ function loadCaCert(caCertPath) {
20
+ if (!caCertPath) return void 0;
21
+ const resolved = path.default.resolve(caCertPath.replace(/^~/, os.default.homedir()));
22
+ const ext = path.default.extname(resolved).toLowerCase();
23
+ if (!ALLOWED_CA_CERT_EXTENSIONS.has(ext)) throw new Error(`Unsupported CA certificate file type: ${ext || "unknown"}`);
24
+ const certificate = fs_extra.default.readFileSync(resolved);
25
+ if (certificate.length === 0) throw new Error("CA certificate file is empty");
26
+ if (certificate.length > MAX_CA_CERT_BYTES) throw new Error(`CA certificate file exceeds ${MAX_CA_CERT_BYTES} bytes`);
27
+ return certificate;
28
+ }
29
+ function bbReq(serverUrl, password, method, endpoint, body, caCertPath) {
30
+ return new Promise((resolve, reject) => {
31
+ const url = new URL(`${serverUrl}/api/v1${endpoint}`);
32
+ url.searchParams.set("password", password);
33
+ const isHttps = url.protocol === "https:";
34
+ const mod = isHttps ? https.default : http.default;
35
+ const payload = body ? JSON.stringify(body) : null;
36
+ const ca = isHttps ? loadCaCert(caCertPath) : void 0;
37
+ const req = mod.request({
38
+ hostname: url.hostname,
39
+ port: url.port || (isHttps ? 443 : 1234),
40
+ path: url.pathname + url.search,
41
+ method,
42
+ headers: payload ? {
43
+ "Content-Type": "application/json",
44
+ "Content-Length": Buffer.byteLength(payload)
45
+ } : {},
46
+ ...ca ? { ca } : {}
47
+ }, (res) => {
48
+ let data = "";
49
+ res.on("data", (c) => data += c);
50
+ res.on("end", () => {
51
+ try {
52
+ const r = JSON.parse(data);
53
+ if (r.status !== 200) reject(new Error(r.error?.message || "BB error"));
54
+ else resolve(r.data);
55
+ } catch {
56
+ reject(new Error("Invalid JSON"));
57
+ }
58
+ });
59
+ });
60
+ req.on("error", reject);
61
+ if (payload) req.write(payload);
62
+ req.end();
63
+ });
64
+ }
65
+ var BlueBubblesConnector = class extends events.EventEmitter {
66
+ config;
67
+ running = false;
68
+ ws = null;
69
+ lastMessageTs = 0;
70
+ insecureTlsWarned = false;
71
+ constructor(config) {
72
+ super();
73
+ this.config = {
74
+ dmPolicy: "allowlist",
75
+ allowFrom: [],
76
+ approvedPairings: [],
77
+ pendingPairings: {},
78
+ ...config
79
+ };
80
+ }
81
+ async connect() {
82
+ if (this.config.allowInsecureSsl && !this.insecureTlsWarned) {
83
+ this.insecureTlsWarned = true;
84
+ console.log(chalk.default.yellow(" ⚠ BlueBubbles: allowInsecureSsl is ignored. Use HTTP locally or configure caCertPath for private HTTPS."));
85
+ }
86
+ const info = await bbReq(this.config.serverUrl, this.config.password, "GET", "/server/info", void 0, this.config.caCertPath);
87
+ await this.loadState();
88
+ this.running = true;
89
+ console.log(chalk.default.green(` 🦅 BlueBubbles (iMessage): ${info?.os_version || "macOS"} server connected`));
90
+ this.emit("connected", { serverInfo: info });
91
+ this.connectWebSocket();
92
+ }
93
+ connectWebSocket() {
94
+ const url = new URL(this.config.serverUrl);
95
+ const wsUrl = `${url.protocol === "https:" ? "wss" : "ws"}://${url.hostname}:${url.port || 1234}`;
96
+ const ca = url.protocol === "https:" ? loadCaCert(this.config.caCertPath) : void 0;
97
+ this.ws = new ws.WebSocket(`${wsUrl}?password=${encodeURIComponent(this.config.password)}`, { ...ca ? { ca } : {} });
98
+ this.ws.on("message", async (data) => {
99
+ try {
100
+ const event = JSON.parse(data.toString());
101
+ if (event.type === "new-message" || event.type === "updated-message") await this.handleMessage(event.data);
102
+ } catch {}
103
+ });
104
+ this.ws.on("close", () => {
105
+ if (this.running) setTimeout(() => this.connectWebSocket(), 5e3);
106
+ });
107
+ this.ws.on("error", () => {});
108
+ setInterval(() => {
109
+ if (this.ws?.readyState === ws.WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "ping" }));
110
+ }, 3e4);
111
+ }
112
+ async handleMessage(msg) {
113
+ if (!msg || msg.isFromMe) return;
114
+ const text = msg.text;
115
+ const from = msg.handle?.address;
116
+ if (!text || !from) return;
117
+ const ts = msg.dateCreated || 0;
118
+ if (ts <= this.lastMessageTs) return;
119
+ this.lastMessageTs = ts;
120
+ await this.saveState();
121
+ const allowed = await this.checkDMPolicy(from, text);
122
+ if (!allowed) return;
123
+ this.emit("message", {
124
+ id: msg.guid,
125
+ channelId: "bluebubbles",
126
+ from,
127
+ chatId: msg.chats?.[0]?.guid || from,
128
+ text,
129
+ timestamp: new Date(ts).toISOString(),
130
+ isDM: !msg.isGroup
131
+ });
132
+ }
133
+ async checkDMPolicy(from, text) {
134
+ if (this.config.dmPolicy === "none") return false;
135
+ if (this.config.dmPolicy === "open") return true;
136
+ if (this.config.dmPolicy === "allowlist") {
137
+ if (this.config.allowFrom.includes(from)) return true;
138
+ await this.sendMessage(from, "🦅 HyperClaw: Not on allowlist.");
139
+ return false;
140
+ }
141
+ if (this.config.dmPolicy === "pairing") {
142
+ if (this.config.approvedPairings.includes(from)) return true;
143
+ const upper = text.trim().toUpperCase();
144
+ if (this.config.pendingPairings[upper]) {
145
+ this.config.approvedPairings.push(from);
146
+ delete this.config.pendingPairings[upper];
147
+ await this.saveState();
148
+ await this.sendMessage(from, "🦅 Paired!");
149
+ this.emit("pairing:approved", {
150
+ userId: from,
151
+ channelId: "bluebubbles"
152
+ });
153
+ return true;
154
+ }
155
+ const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
156
+ this.config.pendingPairings[code] = from;
157
+ await this.saveState();
158
+ await this.sendMessage(from, `🦅 Pairing code: ${code}\nApprove: hyperclaw pairing approve bluebubbles ${code}`);
159
+ return false;
160
+ }
161
+ return false;
162
+ }
163
+ async sendMessage(address, text) {
164
+ await bbReq(this.config.serverUrl, this.config.password, "POST", "/message/text", {
165
+ chatGuid: `iMessage;-;${address}`,
166
+ message: text.slice(0, 65536),
167
+ method: "apple-script"
168
+ }, this.config.caCertPath);
169
+ }
170
+ disconnect() {
171
+ this.running = false;
172
+ this.ws?.close();
173
+ }
174
+ approvePairing(code) {
175
+ const upper = code.toUpperCase();
176
+ if (!this.config.pendingPairings[upper]) return false;
177
+ this.config.approvedPairings.push(this.config.pendingPairings[upper]);
178
+ delete this.config.pendingPairings[upper];
179
+ this.saveState();
180
+ return true;
181
+ }
182
+ async loadState() {
183
+ try {
184
+ const s = await fs_extra.default.readJson(STATE_FILE);
185
+ this.lastMessageTs = s.lastTs || 0;
186
+ if (s.p) this.config.pendingPairings = s.p;
187
+ if (s.a) this.config.approvedPairings = s.a;
188
+ } catch {}
189
+ }
190
+ async saveState() {
191
+ await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
192
+ await fs_extra.default.writeJson(STATE_FILE, {
193
+ lastTs: this.lastMessageTs,
194
+ p: this.config.pendingPairings,
195
+ a: this.config.approvedPairings
196
+ }, { spaces: 2 });
197
+ }
198
+ isRunning() {
199
+ return this.running;
200
+ }
201
+ };
202
+
203
+ //#endregion
204
+ exports.BlueBubblesConnector = BlueBubblesConnector;
@@ -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;