hyperclaw 5.0.1 → 5.0.2
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/LICENSE +2 -1
- package/README.md +247 -32
- package/dist/a2ui-protocol-Gzm29Gaw.js +75 -0
- package/dist/agents-routing-Biy5ew4a.js +4 -0
- package/dist/agents-routing-CL3HQNoM.js +327 -0
- package/dist/api-keys-guide-ChbThbPj.js +149 -0
- package/dist/audit-NPIMmOSq.js +441 -0
- package/dist/bounty-tools-BUqUKjt0.js +211 -0
- package/dist/browser-tools-CxJY6pAn.js +5 -0
- package/dist/browser-tools-JZ9ji6AW.js +179 -0
- package/dist/chat-qVuqhlPu.js +258 -0
- package/dist/claw-tasks-B-8RRMdq.js +80 -0
- package/dist/connector-1x1rCBHz.js +162 -0
- package/dist/connector-B4jeCULG.js +305 -0
- package/dist/connector-B7qngfkT.js +286 -0
- package/dist/connector-B8BK0GBo.js +531 -0
- package/dist/connector-BE9eJs8-.js +182 -0
- package/dist/connector-BEe-DTGQ.js +189 -0
- package/dist/connector-BU7p5ZgB.js +167 -0
- package/dist/connector-BUzzq7Ij.js +568 -0
- package/dist/connector-BpDqLgnW.js +419 -0
- package/dist/connector-BpW88ut2.js +189 -0
- package/dist/connector-Bxv-gy8U.js +167 -0
- package/dist/connector-Bz14zcJv.js +213 -0
- package/dist/connector-C1zP5-5q.js +85 -0
- package/dist/connector-CAcpcovF.js +498 -0
- package/dist/connector-CJgVjS58.js +181 -0
- package/dist/connector-Cf53D6qV.js +425 -0
- package/dist/connector-CyHmlbNz.js +508 -0
- package/dist/connector-D22mJGVu.js +340 -0
- package/dist/connector-D6RtMmlL.js +225 -0
- package/dist/connector-D9EnT8A4.js +280 -0
- package/dist/connector-DNDwIh37.js +239 -0
- package/dist/connector-Di27MeO4.js +350 -0
- package/dist/connector-Do0BPiHt.js +194 -0
- package/dist/connector-DvLwOfJy.js +192 -0
- package/dist/connector-DvU83NSq.js +181 -0
- package/dist/connector-DxskpDc_.js +173 -0
- package/dist/connector-byy3eISx.js +552 -0
- package/dist/connector-vV89hsyd.js +218 -0
- package/dist/cost-tracker-fnaj_6M9.js +103 -0
- package/dist/credentials-store-BxijEirw.js +77 -0
- package/dist/credentials-store-CPkVO6-z.js +4 -0
- package/dist/cron-tasks-L0mz1yyU.js +82 -0
- package/dist/daemon-CNyunwkR.js +5 -0
- package/dist/daemon-CindY8OK.js +318 -0
- package/dist/delivery-DgiZcJBp.js +4 -0
- package/dist/delivery-otAU4alM.js +95 -0
- package/dist/destructive-gate-CA0DtA5K.js +101 -0
- package/dist/developer-keys-Cnd1kswV.js +127 -0
- package/dist/developer-keys-DENo3ZA6.js +8 -0
- package/dist/doctor-Dgjoc3DG.js +230 -0
- package/dist/doctor-RwsOhtAl.js +6 -0
- package/dist/engine-D_VeoZHw.js +305 -0
- package/dist/engine-JjRnhlsE.js +7 -0
- package/dist/env-resolve-BFJXWl94.js +115 -0
- package/dist/env-resolve-bDYssfih.js +10 -0
- package/dist/extraction-tools-DbxnxIco.js +5 -0
- package/dist/extraction-tools-Dg7AHS35.js +91 -0
- package/dist/form_data-CGAy4HE0.js +8657 -0
- package/dist/gmail-watch-setup-C3uSWznp.js +40 -0
- package/dist/health-DUjluWHQ.js +6 -0
- package/dist/health-DVfkpUQW.js +152 -0
- package/dist/heartbeat-engine-CrgL4mrP.js +83 -0
- package/dist/hub-BO6bj8Yj.js +515 -0
- package/dist/hub-Bu52YZqW.js +6 -0
- package/dist/hyperclawbot-BrcoYLOp.js +505 -0
- package/dist/inference-DHR82Gh7.js +6 -0
- package/dist/inference-DhA8jpfH.js +2692 -0
- package/dist/knowledge-graph-BrYpSgxW.js +131 -0
- package/dist/loader-9JqY6Nlq.js +4 -0
- package/dist/loader-Cjdd1kw4.js +400 -0
- package/dist/logger-DCT2l9GV.js +83 -0
- package/dist/manager-3cq3DydI.js +4 -0
- package/dist/manager-BUrFrPuq.js +117 -0
- package/dist/manager-Bi9UYyVR.js +105 -0
- package/dist/manager-Biz9ixWJ.js +40 -0
- package/dist/manager-CBUHJiY7.js +6 -0
- package/dist/manager-CVLLaKmq.js +218 -0
- package/dist/mcp-CUoTCMw-.js +139 -0
- package/dist/mcp-loader-BIz-450x.js +94 -0
- package/dist/memory-OL77OMOr.js +270 -0
- package/dist/memory-auto-D-L2q21G.js +306 -0
- package/dist/memory-auto-DTcy5VBy.js +5 -0
- package/dist/memory-gUi4VaIf.js +4 -0
- package/dist/memory-integration-B8RSN4pr.js +91 -0
- package/dist/moltbook-B-40gQOL.js +81 -0
- package/dist/node-TWxRm84k.js +222 -0
- package/dist/nodes-registry-DKRtsbNg.js +52 -0
- package/dist/oauth-flow-JCfporKq.js +150 -0
- package/dist/oauth-provider-4R0EJlsT.js +110 -0
- package/dist/observability-CDZmeHfa.js +89 -0
- package/dist/onboard-BVOtKQdh.js +3641 -0
- package/dist/onboard-CGNIw27w.js +11 -0
- package/dist/orchestrator-CcKx1Ovk.js +189 -0
- package/dist/orchestrator-DcFfDLTX.js +6 -0
- package/dist/osint-B6BZKQAD.js +277 -0
- package/dist/pairing-B6RArWhD.js +196 -0
- package/dist/pairing-BsQ08DLq.js +4 -0
- package/dist/pc-access-B0KocJNe.js +819 -0
- package/dist/pc-access-DkzmugZ7.js +8 -0
- package/dist/pending-approval-C_HkX1QL.js +22 -0
- package/dist/providers-DxiamZSL.js +5 -0
- package/dist/providers-Dy15rDb7.js +657 -0
- package/dist/reminders-store-CzUY0zYx.js +58 -0
- package/dist/renderer-ANNfXsHn.js +225 -0
- package/dist/rules-BSQwwAYC.js +103 -0
- package/dist/run-main.js +112 -117
- package/dist/runner-BHRSOPEU.js +1271 -0
- package/dist/security--oQObeJO.js +4 -0
- package/dist/security-wBOg0TA8.js +73 -0
- package/dist/server-CbTTpB5m.js +1255 -0
- package/dist/server-DP_bPzvI.js +4 -0
- package/dist/session-store-B09r5HgB.js +5 -0
- package/dist/session-store-DCTQIVur.js +113 -0
- package/dist/sessions-tools-BdlN6Pb6.js +95 -0
- package/dist/sessions-tools-JVLDKSJ_.js +5 -0
- package/dist/skill-loader-B5oeliGu.js +7 -0
- package/dist/skill-loader-Wf3brNOj.js +160 -0
- package/dist/skill-runtime-BGlvly2s.js +102 -0
- package/dist/skill-runtime-DhL2T76p.js +5 -0
- package/dist/src-BbPa6Q8p.js +63 -0
- package/dist/src-BeXtfkK2.js +458 -0
- package/dist/src-CGQjRI4N.js +20 -0
- package/dist/sub-agent-tools-CmE345s_.js +39 -0
- package/dist/theme-D0smfC_l.js +8 -0
- package/dist/theme-DajRRZbA.js +180 -0
- package/dist/tool-policy-DgNqFWYn.js +189 -0
- package/dist/tts-elevenlabs-JeFaGNJU.js +61 -0
- package/dist/update-check-BVEqHhFY.js +83 -0
- package/dist/vision-fky3elEo.js +121 -0
- package/dist/vision-tools-C8B3776g.js +5 -0
- package/dist/vision-tools-dwn9p4el.js +51 -0
- package/dist/voice-transcription-B6RtplmN.js +138 -0
- package/dist/website-watch-tools-B-jRAeTe.js +139 -0
- package/dist/website-watch-tools-BC9xAL67.js +5 -0
- package/package.json +1 -1
|
@@ -0,0 +1,305 @@
|
|
|
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 http = require_chunk.__toESM(require("http"));
|
|
7
|
+
const https = require_chunk.__toESM(require("https"));
|
|
8
|
+
const events = require_chunk.__toESM(require("events"));
|
|
9
|
+
|
|
10
|
+
//#region extensions/synology-chat/src/connector.ts
|
|
11
|
+
function resolveAllowedIds(raw, envVal) {
|
|
12
|
+
if (Array.isArray(raw) && raw.length) return raw;
|
|
13
|
+
if (typeof raw === "string" && raw.trim()) return raw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
14
|
+
if (envVal) return envVal.split(",").map((s) => s.trim()).filter(Boolean);
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
function resolveAccount(id, raw, state) {
|
|
18
|
+
const token = raw.token || process.env["SYNOLOGY_CHAT_TOKEN"] || "";
|
|
19
|
+
const incomingUrl = raw.incomingUrl || process.env["SYNOLOGY_CHAT_INCOMING_URL"] || "";
|
|
20
|
+
const allowedUserIds = resolveAllowedIds(raw.allowedUserIds, process.env["SYNOLOGY_ALLOWED_USER_IDS"]);
|
|
21
|
+
const rateLimitPerMinute = raw.rateLimitPerMinute ?? (process.env["SYNOLOGY_RATE_LIMIT"] ? parseInt(process.env["SYNOLOGY_RATE_LIMIT"], 10) : 30);
|
|
22
|
+
return {
|
|
23
|
+
id,
|
|
24
|
+
name: raw.name ?? process.env["OPENCLAW_BOT_NAME"] ?? id,
|
|
25
|
+
token,
|
|
26
|
+
incomingUrl,
|
|
27
|
+
webhookPath: raw.webhookPath ?? "/webhook/synology",
|
|
28
|
+
dmPolicy: raw.dmPolicy ?? "allowlist",
|
|
29
|
+
allowedUserIds,
|
|
30
|
+
rateLimitPerMinute,
|
|
31
|
+
allowInsecureSsl: raw.allowInsecureSsl ?? false,
|
|
32
|
+
approvedPairings: state.approved,
|
|
33
|
+
pendingPairings: state.pending
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
var RateLimiter = class {
|
|
37
|
+
windows = /* @__PURE__ */ new Map();
|
|
38
|
+
constructor(limitPerMinute) {
|
|
39
|
+
this.limitPerMinute = limitPerMinute;
|
|
40
|
+
}
|
|
41
|
+
allow(senderId) {
|
|
42
|
+
if (this.limitPerMinute <= 0) return true;
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
const cutoff = now - 6e4;
|
|
45
|
+
const timestamps = (this.windows.get(senderId) ?? []).filter((t) => t > cutoff);
|
|
46
|
+
if (timestamps.length >= this.limitPerMinute) return false;
|
|
47
|
+
timestamps.push(now);
|
|
48
|
+
this.windows.set(senderId, timestamps);
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
function postToSynology(incomingUrl, text, userId, allowInsecureSsl = false) {
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const u = new URL(incomingUrl);
|
|
55
|
+
const isHttps = u.protocol === "https:";
|
|
56
|
+
const mod = isHttps ? https.default : http.default;
|
|
57
|
+
const payloadObj = { text };
|
|
58
|
+
if (userId) payloadObj.user_ids = [parseInt(userId, 10)].filter((n) => !isNaN(n));
|
|
59
|
+
const encoded = `payload=${encodeURIComponent(JSON.stringify(payloadObj))}`;
|
|
60
|
+
const options = {
|
|
61
|
+
hostname: u.hostname,
|
|
62
|
+
port: u.port || (isHttps ? 443 : 80),
|
|
63
|
+
path: u.pathname + u.search,
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: {
|
|
66
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
67
|
+
"Content-Length": Buffer.byteLength(encoded)
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
if (isHttps && allowInsecureSsl) options.rejectUnauthorized = false;
|
|
71
|
+
const req = (isHttps ? https.default : http.default).request(options, (res) => {
|
|
72
|
+
res.resume();
|
|
73
|
+
res.on("end", resolve);
|
|
74
|
+
});
|
|
75
|
+
req.on("error", reject);
|
|
76
|
+
req.write(encoded);
|
|
77
|
+
req.end();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const STATE_DIR = path.default.join(os.default.homedir(), ".hyperclaw");
|
|
81
|
+
var SingleAccountConnector = class extends events.EventEmitter {
|
|
82
|
+
acc;
|
|
83
|
+
rateLimiter;
|
|
84
|
+
constructor(acc) {
|
|
85
|
+
super();
|
|
86
|
+
this.acc = acc;
|
|
87
|
+
this.rateLimiter = new RateLimiter(acc.rateLimitPerMinute);
|
|
88
|
+
}
|
|
89
|
+
validate() {
|
|
90
|
+
const { dmPolicy, allowedUserIds, token, incomingUrl } = this.acc;
|
|
91
|
+
if (!token) throw new Error(`Synology Chat[${this.acc.id}]: 'token' is required (set SYNOLOGY_CHAT_TOKEN or config)`);
|
|
92
|
+
if (!incomingUrl) throw new Error(`Synology Chat[${this.acc.id}]: 'incomingUrl' is required`);
|
|
93
|
+
if (dmPolicy === "allowlist" && allowedUserIds.length === 0) throw new Error(`Synology Chat[${this.acc.id}]: dmPolicy="allowlist" requires at least one allowedUserId. Use dmPolicy="open" to allow all senders.`);
|
|
94
|
+
}
|
|
95
|
+
async handleWebhook(body) {
|
|
96
|
+
let params;
|
|
97
|
+
try {
|
|
98
|
+
params = new URLSearchParams(body);
|
|
99
|
+
} catch {
|
|
100
|
+
return {
|
|
101
|
+
status: 400,
|
|
102
|
+
body: "Bad Request"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const inboundToken = params.get("token");
|
|
106
|
+
if (inboundToken !== this.acc.token) {
|
|
107
|
+
console.log(chalk.default.yellow(` ⚠ Synology Chat[${this.acc.id}]: invalid token`));
|
|
108
|
+
return {
|
|
109
|
+
status: 403,
|
|
110
|
+
body: "Forbidden"
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const text = (params.get("text") ?? "").trim();
|
|
114
|
+
const userId = params.get("user_id") ?? "";
|
|
115
|
+
const username = params.get("username") ?? userId;
|
|
116
|
+
const channelId = params.get("channel_id") ?? "";
|
|
117
|
+
const timestamp = params.get("timestamp") ?? String(Date.now());
|
|
118
|
+
if (!text || !userId) return {
|
|
119
|
+
status: 200,
|
|
120
|
+
body: "{}"
|
|
121
|
+
};
|
|
122
|
+
if (!this.rateLimiter.allow(userId)) {
|
|
123
|
+
console.log(chalk.default.gray(` synology-chat[${this.acc.id}]: rate-limited sender ${userId}`));
|
|
124
|
+
return {
|
|
125
|
+
status: 429,
|
|
126
|
+
body: "Too Many Requests"
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
const allowed = await this._checkPolicy(userId, channelId, text);
|
|
130
|
+
if (!allowed) return {
|
|
131
|
+
status: 200,
|
|
132
|
+
body: "{}"
|
|
133
|
+
};
|
|
134
|
+
const msg = {
|
|
135
|
+
accountId: this.acc.id,
|
|
136
|
+
id: `syno-${timestamp}-${Math.random().toString(36).slice(2, 7)}`,
|
|
137
|
+
from: username,
|
|
138
|
+
userId,
|
|
139
|
+
chatId: userId,
|
|
140
|
+
text,
|
|
141
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
142
|
+
};
|
|
143
|
+
this.emit("message", msg);
|
|
144
|
+
return {
|
|
145
|
+
status: 200,
|
|
146
|
+
body: "{}"
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
async _checkPolicy(userId, channelId, text) {
|
|
150
|
+
const acc = this.acc;
|
|
151
|
+
if (acc.dmPolicy === "disabled") return false;
|
|
152
|
+
if (acc.dmPolicy === "open") return true;
|
|
153
|
+
if (acc.dmPolicy === "allowlist") {
|
|
154
|
+
if (acc.allowedUserIds.includes(userId)) return true;
|
|
155
|
+
console.log(chalk.default.gray(` synology-chat[${acc.id}]: drop sender ${userId} (dmPolicy=allowlist)`));
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
if (acc.dmPolicy === "pairing") {
|
|
159
|
+
if (acc.approvedPairings.includes(userId)) return true;
|
|
160
|
+
const upper = text.trim().toUpperCase();
|
|
161
|
+
if (acc.pendingPairings[upper] === userId) {
|
|
162
|
+
acc.approvedPairings.push(userId);
|
|
163
|
+
delete acc.pendingPairings[upper];
|
|
164
|
+
await this._saveState();
|
|
165
|
+
await this.sendMessage(userId, "🦅 Paired! You can now send messages to the assistant.");
|
|
166
|
+
this.emit("pairing:approved", {
|
|
167
|
+
accountId: acc.id,
|
|
168
|
+
userId
|
|
169
|
+
});
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
|
|
173
|
+
acc.pendingPairings[code] = userId;
|
|
174
|
+
await this._saveState();
|
|
175
|
+
await this.sendMessage(userId, `🦅 Pairing required. Your code: \`${code}\`\nApprove: hyperclaw pairing approve synology-chat ${code}`);
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
async sendMessage(userId, text) {
|
|
181
|
+
try {
|
|
182
|
+
await postToSynology(this.acc.incomingUrl, text, userId, this.acc.allowInsecureSsl);
|
|
183
|
+
} catch (e) {
|
|
184
|
+
console.log(chalk.default.yellow(` ⚠ Synology Chat[${this.acc.id}] send error: ${e.message}`));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Resolve outbound target. Accepts: numeric ID, "synology-chat:<id>", "user:<id>" */
|
|
188
|
+
resolveTarget(target) {
|
|
189
|
+
if (target.startsWith("synology-chat:")) return target.slice(14);
|
|
190
|
+
if (target.startsWith("user:")) return target.slice(5);
|
|
191
|
+
return target;
|
|
192
|
+
}
|
|
193
|
+
approvePairing(code) {
|
|
194
|
+
const upper = code.toUpperCase();
|
|
195
|
+
if (!this.acc.pendingPairings[upper]) return false;
|
|
196
|
+
this.acc.approvedPairings.push(this.acc.pendingPairings[upper]);
|
|
197
|
+
delete this.acc.pendingPairings[upper];
|
|
198
|
+
this._saveState();
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
listPendingPairings() {
|
|
202
|
+
return { ...this.acc.pendingPairings };
|
|
203
|
+
}
|
|
204
|
+
_stateFile() {
|
|
205
|
+
return path.default.join(STATE_DIR, `synology-chat-state-${this.acc.id}.json`);
|
|
206
|
+
}
|
|
207
|
+
async loadState() {
|
|
208
|
+
try {
|
|
209
|
+
const s = await fs_extra.default.readJson(this._stateFile());
|
|
210
|
+
if (Array.isArray(s.approvedPairings)) this.acc.approvedPairings = s.approvedPairings;
|
|
211
|
+
if (s.pendingPairings && typeof s.pendingPairings === "object") this.acc.pendingPairings = s.pendingPairings;
|
|
212
|
+
} catch {}
|
|
213
|
+
}
|
|
214
|
+
async _saveState() {
|
|
215
|
+
await fs_extra.default.ensureDir(STATE_DIR);
|
|
216
|
+
await fs_extra.default.writeJson(this._stateFile(), {
|
|
217
|
+
approvedPairings: this.acc.approvedPairings,
|
|
218
|
+
pendingPairings: this.acc.pendingPairings
|
|
219
|
+
}, { spaces: 2 });
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
var SynologyChatConnector = class extends events.EventEmitter {
|
|
223
|
+
accounts = /* @__PURE__ */ new Map();
|
|
224
|
+
/** webhookPath → accountId index for fast routing */
|
|
225
|
+
pathIndex = /* @__PURE__ */ new Map();
|
|
226
|
+
rawConfig;
|
|
227
|
+
constructor(config) {
|
|
228
|
+
super();
|
|
229
|
+
this.rawConfig = config;
|
|
230
|
+
}
|
|
231
|
+
async connect() {
|
|
232
|
+
const cfg = this.rawConfig;
|
|
233
|
+
const accountDefs = cfg.accounts ?? { default: cfg };
|
|
234
|
+
for (const [id, rawAcc] of Object.entries(accountDefs)) {
|
|
235
|
+
const merged = {
|
|
236
|
+
...cfg,
|
|
237
|
+
...rawAcc
|
|
238
|
+
};
|
|
239
|
+
const state = {
|
|
240
|
+
approved: cfg.approvedPairings ?? [],
|
|
241
|
+
pending: cfg.pendingPairings ?? {}
|
|
242
|
+
};
|
|
243
|
+
const acc = resolveAccount(id, merged, state);
|
|
244
|
+
const conn = new SingleAccountConnector(acc);
|
|
245
|
+
try {
|
|
246
|
+
conn.validate();
|
|
247
|
+
} catch (e) {
|
|
248
|
+
console.log(chalk.default.red(` ✗ ${e.message} — account skipped`));
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
await conn.loadState();
|
|
252
|
+
conn.on("message", (msg) => this.emit("message", msg));
|
|
253
|
+
conn.on("pairing:approved", (info) => this.emit("pairing:approved", info));
|
|
254
|
+
this.accounts.set(id, conn);
|
|
255
|
+
this.pathIndex.set(acc.webhookPath, id);
|
|
256
|
+
console.log(chalk.default.green(` 🦅 Synology Chat[${id}]: ready — inbound path ${acc.webhookPath}`));
|
|
257
|
+
}
|
|
258
|
+
this.emit("connected", { accountIds: Array.from(this.accounts.keys()) });
|
|
259
|
+
}
|
|
260
|
+
disconnect() {
|
|
261
|
+
this.accounts.clear();
|
|
262
|
+
this.pathIndex.clear();
|
|
263
|
+
}
|
|
264
|
+
/** Called by the gateway's HTTP server for inbound POST requests. */
|
|
265
|
+
async handleWebhook(requestPath, body) {
|
|
266
|
+
const accountId = this.pathIndex.get(requestPath);
|
|
267
|
+
if (!accountId) return {
|
|
268
|
+
status: 404,
|
|
269
|
+
body: "Not Found"
|
|
270
|
+
};
|
|
271
|
+
return this._acc(accountId).handleWebhook(body);
|
|
272
|
+
}
|
|
273
|
+
/** Returns all registered webhook paths (for gateway route registration). */
|
|
274
|
+
getWebhookPaths() {
|
|
275
|
+
return Array.from(this.pathIndex.keys());
|
|
276
|
+
}
|
|
277
|
+
_acc(accountId = "default") {
|
|
278
|
+
const conn = this.accounts.get(accountId);
|
|
279
|
+
if (!conn) throw new Error(`Synology Chat: account '${accountId}' not found`);
|
|
280
|
+
return conn;
|
|
281
|
+
}
|
|
282
|
+
async sendMessage(userId, text, accountId) {
|
|
283
|
+
const conn = this._acc(accountId);
|
|
284
|
+
const resolved = conn.resolveTarget(userId);
|
|
285
|
+
return conn.sendMessage(resolved, text);
|
|
286
|
+
}
|
|
287
|
+
resolveTarget(target, accountId) {
|
|
288
|
+
return this._acc(accountId).resolveTarget(target);
|
|
289
|
+
}
|
|
290
|
+
approvePairing(code, accountId) {
|
|
291
|
+
return this._acc(accountId).approvePairing(code);
|
|
292
|
+
}
|
|
293
|
+
listPendingPairings(accountId) {
|
|
294
|
+
return this._acc(accountId).listPendingPairings();
|
|
295
|
+
}
|
|
296
|
+
getAccountIds() {
|
|
297
|
+
return Array.from(this.accounts.keys());
|
|
298
|
+
}
|
|
299
|
+
isRunning() {
|
|
300
|
+
return this.accounts.size > 0;
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
//#endregion
|
|
305
|
+
exports.SynologyChatConnector = SynologyChatConnector;
|
|
@@ -0,0 +1,286 @@
|
|
|
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 net = require_chunk.__toESM(require("net"));
|
|
7
|
+
const events = require_chunk.__toESM(require("events"));
|
|
8
|
+
const tls = require_chunk.__toESM(require("tls"));
|
|
9
|
+
|
|
10
|
+
//#region extensions/email/src/connector.ts
|
|
11
|
+
const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "email-state.json");
|
|
12
|
+
var IMAPClient = class {
|
|
13
|
+
sock = null;
|
|
14
|
+
buffer = "";
|
|
15
|
+
tag = 0;
|
|
16
|
+
pendingCallbacks = /* @__PURE__ */ new Map();
|
|
17
|
+
async connect(host, port, username, password) {
|
|
18
|
+
await new Promise((resolve, reject) => {
|
|
19
|
+
this.sock = tls.default.connect({
|
|
20
|
+
host,
|
|
21
|
+
port,
|
|
22
|
+
rejectUnauthorized: true
|
|
23
|
+
}, () => resolve());
|
|
24
|
+
this.sock.on("error", reject);
|
|
25
|
+
this.sock.on("data", (chunk) => {
|
|
26
|
+
this.buffer += chunk.toString();
|
|
27
|
+
this.processBuffer();
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
await this.waitForUntagged("OK");
|
|
31
|
+
await this.command(`LOGIN "${this.escapeQuoted(username)}" "${this.escapeQuoted(password)}"`);
|
|
32
|
+
}
|
|
33
|
+
disconnect() {
|
|
34
|
+
this.sock?.end();
|
|
35
|
+
this.sock = null;
|
|
36
|
+
}
|
|
37
|
+
async selectFolder(folder) {
|
|
38
|
+
const resp = await this.command(`SELECT "${folder}"`);
|
|
39
|
+
const existsMatch = resp.match(/\* (\d+) EXISTS/);
|
|
40
|
+
const unseenMatch = resp.match(/UNSEEN (\d+)/);
|
|
41
|
+
return {
|
|
42
|
+
exists: existsMatch ? parseInt(existsMatch[1]) : 0,
|
|
43
|
+
unseen: unseenMatch ? parseInt(unseenMatch[1]) : 0
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
async searchUnseen() {
|
|
47
|
+
const resp = await this.command("SEARCH UNSEEN");
|
|
48
|
+
const match = resp.match(/\* SEARCH ([\d ]+)/);
|
|
49
|
+
if (!match || !match[1].trim()) return [];
|
|
50
|
+
return match[1].trim().split(" ").map(Number).filter(Boolean);
|
|
51
|
+
}
|
|
52
|
+
async fetchEmail(uid) {
|
|
53
|
+
const resp = await this.command(`FETCH ${uid} (RFC822.HEADER BODY[TEXT])`);
|
|
54
|
+
const fromMatch = resp.match(/^From:\s*(.+)$/im);
|
|
55
|
+
const subjectMatch = resp.match(/^Subject:\s*(.+)$/im);
|
|
56
|
+
const msgIdMatch = resp.match(/^Message-ID:\s*(.+)$/im);
|
|
57
|
+
const bodyMatch = resp.match(/BODY\[TEXT\] \{(\d+)\}([\s\S]+?)(?:\* \d+ FETCH|\w+ OK)/);
|
|
58
|
+
if (!fromMatch) return null;
|
|
59
|
+
const body = bodyMatch ? decodeQP(bodyMatch[2].trim()) : "";
|
|
60
|
+
return {
|
|
61
|
+
from: fromMatch[1].trim(),
|
|
62
|
+
subject: decodeHeader(subjectMatch ? subjectMatch[1].trim() : "(no subject)"),
|
|
63
|
+
body: body.slice(0, 4e3),
|
|
64
|
+
messageId: msgIdMatch ? msgIdMatch[1].trim() : ""
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async markSeen(uid) {
|
|
68
|
+
await this.command(`STORE ${uid} +FLAGS (\\Seen)`);
|
|
69
|
+
}
|
|
70
|
+
async command(cmd) {
|
|
71
|
+
const tag = `HC${++this.tag}`;
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
this.pendingCallbacks.set(tag, resolve);
|
|
74
|
+
this.sock?.write(`${tag} ${cmd}\r\n`);
|
|
75
|
+
setTimeout(() => {
|
|
76
|
+
this.pendingCallbacks.delete(tag);
|
|
77
|
+
reject(new Error(`IMAP timeout: ${tag} ${cmd.slice(0, 30)}`));
|
|
78
|
+
}, 15e3);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async waitForUntagged(keyword) {
|
|
82
|
+
await new Promise((resolve) => {
|
|
83
|
+
const check = () => {
|
|
84
|
+
if (this.buffer.includes(`* ${keyword}`) || this.buffer.includes(`OK ${keyword}`)) resolve();
|
|
85
|
+
else setTimeout(check, 100);
|
|
86
|
+
};
|
|
87
|
+
setTimeout(check, 100);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
processBuffer() {
|
|
91
|
+
const lines = this.buffer.split("\r\n");
|
|
92
|
+
this.buffer = lines.pop() || "";
|
|
93
|
+
for (const line of lines) {
|
|
94
|
+
const tagMatch = line.match(/^(HC\d+) (OK|NO|BAD)/);
|
|
95
|
+
if (tagMatch) {
|
|
96
|
+
const cb = this.pendingCallbacks.get(tagMatch[1]);
|
|
97
|
+
if (cb) {
|
|
98
|
+
this.pendingCallbacks.delete(tagMatch[1]);
|
|
99
|
+
cb(this.buffer + line);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
escapeQuoted(s) {
|
|
105
|
+
return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
var SMTPClient = class {
|
|
109
|
+
async send(config, to, subject, body) {
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
const sock = net.default.createConnection(config.smtpPort, config.smtpHost);
|
|
112
|
+
let buf = "";
|
|
113
|
+
let tlsSock = null;
|
|
114
|
+
let upgraded = false;
|
|
115
|
+
let authenticated = false;
|
|
116
|
+
const write = (s) => {
|
|
117
|
+
const target = tlsSock || sock;
|
|
118
|
+
target.write(s + "\r\n");
|
|
119
|
+
};
|
|
120
|
+
const onData = (chunk) => {
|
|
121
|
+
buf += chunk.toString();
|
|
122
|
+
const lines = buf.split("\r\n");
|
|
123
|
+
buf = lines.pop() || "";
|
|
124
|
+
for (const line of lines) {
|
|
125
|
+
const code = parseInt(line.slice(0, 3));
|
|
126
|
+
if (line.startsWith("220") && !upgraded) write(`EHLO hyperclaw.ai`);
|
|
127
|
+
else if (line.includes("250") && line.includes("STARTTLS") && !upgraded) write("STARTTLS");
|
|
128
|
+
else if (line.startsWith("220") && !upgraded) {
|
|
129
|
+
upgraded = true;
|
|
130
|
+
tlsSock = tls.default.connect({
|
|
131
|
+
socket: sock,
|
|
132
|
+
servername: config.smtpHost
|
|
133
|
+
});
|
|
134
|
+
tlsSock.on("data", onData);
|
|
135
|
+
tlsSock.on("error", reject);
|
|
136
|
+
write(`EHLO hyperclaw.ai`);
|
|
137
|
+
} else if (line.startsWith("250") && upgraded && !authenticated) write(`AUTH LOGIN`);
|
|
138
|
+
else if (line.startsWith("334") && !authenticated) {
|
|
139
|
+
const b64user = Buffer.from(config.username).toString("base64");
|
|
140
|
+
const b64pass = Buffer.from(config.password).toString("base64");
|
|
141
|
+
if (line.includes("VXNlcm5hbWU")) write(b64user);
|
|
142
|
+
else {
|
|
143
|
+
write(b64pass);
|
|
144
|
+
authenticated = true;
|
|
145
|
+
}
|
|
146
|
+
} else if (line.startsWith("235")) write(`MAIL FROM:<${config.username}>`);
|
|
147
|
+
else if (line.startsWith("250") && authenticated) if (buf.includes("RCPT") || !buf) write(`RCPT TO:<${to}>`);
|
|
148
|
+
else write(`DATA`);
|
|
149
|
+
else if (line.startsWith("354")) {
|
|
150
|
+
const date = (/* @__PURE__ */ new Date()).toUTCString();
|
|
151
|
+
const msg = `From: ${config.username}\r\nTo: ${to}\r\nSubject: ${subject}\r\nDate: ${date}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n` + body + "\r\n.";
|
|
152
|
+
write(msg);
|
|
153
|
+
} else if (line.startsWith("250") && buf.includes(".")) write("QUIT");
|
|
154
|
+
else if (line.startsWith("221")) {
|
|
155
|
+
sock.destroy();
|
|
156
|
+
resolve();
|
|
157
|
+
} else if (code >= 400) {
|
|
158
|
+
sock.destroy();
|
|
159
|
+
reject(new Error(`SMTP error: ${line}`));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
sock.on("data", onData);
|
|
164
|
+
sock.on("error", reject);
|
|
165
|
+
sock.setTimeout(15e3, () => {
|
|
166
|
+
sock.destroy();
|
|
167
|
+
reject(new Error("SMTP timeout"));
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
function decodeQP(text) {
|
|
173
|
+
return text.replace(/=\r\n/g, "").replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
174
|
+
}
|
|
175
|
+
function decodeHeader(text) {
|
|
176
|
+
return text.replace(/=\?UTF-8\?[BQ]\?([^?]+)\?=/gi, (_, enc) => {
|
|
177
|
+
try {
|
|
178
|
+
return Buffer.from(enc, "base64").toString("utf8");
|
|
179
|
+
} catch {
|
|
180
|
+
return enc;
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
function extractEmail(from) {
|
|
185
|
+
const match = from.match(/<([^>]+)>/) || from.match(/[\w.+-]+@[\w-]+\.[a-z]{2,}/i);
|
|
186
|
+
return match ? match[1] || match[0] : from;
|
|
187
|
+
}
|
|
188
|
+
var EmailConnector = class extends events.EventEmitter {
|
|
189
|
+
config;
|
|
190
|
+
pollTimer = null;
|
|
191
|
+
running = false;
|
|
192
|
+
lastSeenUid = 0;
|
|
193
|
+
smtp = new SMTPClient();
|
|
194
|
+
constructor(config) {
|
|
195
|
+
super();
|
|
196
|
+
this.config = {
|
|
197
|
+
imapPort: 993,
|
|
198
|
+
smtpPort: 587,
|
|
199
|
+
pollIntervalMs: 3e4,
|
|
200
|
+
inboxFolder: "INBOX",
|
|
201
|
+
markAsRead: true,
|
|
202
|
+
subjectPrefix: "",
|
|
203
|
+
fromAllowlist: [],
|
|
204
|
+
...config
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
async connect() {
|
|
208
|
+
await this.loadState();
|
|
209
|
+
const imap = new IMAPClient();
|
|
210
|
+
await imap.connect(this.config.imapHost, this.config.imapPort, this.config.username, this.config.password);
|
|
211
|
+
const { exists } = await imap.selectFolder(this.config.inboxFolder);
|
|
212
|
+
imap.disconnect();
|
|
213
|
+
console.log(chalk.default.green(` 🦅 Email: ${this.config.username} — ${exists} messages in inbox`));
|
|
214
|
+
this.running = true;
|
|
215
|
+
this.emit("connected", { username: this.config.username });
|
|
216
|
+
this.startPolling();
|
|
217
|
+
}
|
|
218
|
+
disconnect() {
|
|
219
|
+
this.running = false;
|
|
220
|
+
if (this.pollTimer) clearInterval(this.pollTimer);
|
|
221
|
+
}
|
|
222
|
+
startPolling() {
|
|
223
|
+
this.poll();
|
|
224
|
+
this.pollTimer = setInterval(() => this.poll(), this.config.pollIntervalMs);
|
|
225
|
+
}
|
|
226
|
+
/** Trigger immediate poll (e.g. from Gmail Pub/Sub webhook) */
|
|
227
|
+
triggerPoll() {
|
|
228
|
+
if (this.running) this.poll();
|
|
229
|
+
}
|
|
230
|
+
async poll() {
|
|
231
|
+
if (!this.running) return;
|
|
232
|
+
const imap = new IMAPClient();
|
|
233
|
+
try {
|
|
234
|
+
await imap.connect(this.config.imapHost, this.config.imapPort, this.config.username, this.config.password);
|
|
235
|
+
await imap.selectFolder(this.config.inboxFolder);
|
|
236
|
+
const unseenUids = await imap.searchUnseen();
|
|
237
|
+
const newUids = unseenUids.filter((uid) => uid > this.lastSeenUid);
|
|
238
|
+
for (const uid of newUids) {
|
|
239
|
+
const email = await imap.fetchEmail(uid);
|
|
240
|
+
if (!email) continue;
|
|
241
|
+
const fromAddr = extractEmail(email.from);
|
|
242
|
+
if (this.config.subjectPrefix && !email.subject.startsWith(this.config.subjectPrefix)) continue;
|
|
243
|
+
if (this.config.fromAllowlist.length > 0 && !this.config.fromAllowlist.includes(fromAddr)) continue;
|
|
244
|
+
if (this.config.markAsRead) await imap.markSeen(uid);
|
|
245
|
+
this.lastSeenUid = Math.max(this.lastSeenUid, uid);
|
|
246
|
+
await this.saveState();
|
|
247
|
+
this.emit("message", {
|
|
248
|
+
id: email.messageId || String(uid),
|
|
249
|
+
channelId: "email",
|
|
250
|
+
from: fromAddr,
|
|
251
|
+
chatId: fromAddr,
|
|
252
|
+
text: `Subject: ${email.subject}\n\n${email.body}`,
|
|
253
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
254
|
+
isDM: true
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
} catch (err) {
|
|
258
|
+
if (this.running) console.log(chalk.default.yellow(` ⚠ Email poll error: ${err.message}`));
|
|
259
|
+
} finally {
|
|
260
|
+
imap.disconnect();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async sendMessage(to, text, subject) {
|
|
264
|
+
await this.smtp.send(this.config, to, subject || `🦅 HyperClaw`, text);
|
|
265
|
+
}
|
|
266
|
+
async reply(to, originalSubject, text) {
|
|
267
|
+
const replySubject = originalSubject.startsWith("Re: ") ? originalSubject : `Re: ${originalSubject}`;
|
|
268
|
+
await this.sendMessage(to, text, replySubject);
|
|
269
|
+
}
|
|
270
|
+
async loadState() {
|
|
271
|
+
try {
|
|
272
|
+
const s = await fs_extra.default.readJson(STATE_FILE);
|
|
273
|
+
this.lastSeenUid = s.lastSeenUid || 0;
|
|
274
|
+
} catch {}
|
|
275
|
+
}
|
|
276
|
+
async saveState() {
|
|
277
|
+
await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
|
|
278
|
+
await fs_extra.default.writeJson(STATE_FILE, { lastSeenUid: this.lastSeenUid }, { spaces: 2 });
|
|
279
|
+
}
|
|
280
|
+
isRunning() {
|
|
281
|
+
return this.running;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
//#endregion
|
|
286
|
+
exports.EmailConnector = EmailConnector;
|