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,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;
@@ -0,0 +1,162 @@
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 https = require_chunk.__toESM(require("https"));
7
+ const events = require_chunk.__toESM(require("events"));
8
+
9
+ //#region extensions/instagram/src/connector.ts
10
+ const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "instagram-state.json");
11
+ function igReq(token, method, endpoint, body) {
12
+ return new Promise((resolve, reject) => {
13
+ const payload = body ? JSON.stringify(body) : null;
14
+ const req = https.default.request({
15
+ hostname: "graph.facebook.com",
16
+ port: 443,
17
+ path: `/v18.0${endpoint}`,
18
+ method,
19
+ headers: {
20
+ "Authorization": `Bearer ${token}`,
21
+ ...payload ? {
22
+ "Content-Type": "application/json",
23
+ "Content-Length": Buffer.byteLength(payload)
24
+ } : {}
25
+ }
26
+ }, (res) => {
27
+ let data = "";
28
+ res.on("data", (c) => data += c);
29
+ res.on("end", () => {
30
+ try {
31
+ const r = JSON.parse(data);
32
+ if (r.error) reject(new Error(r.error.message));
33
+ else resolve(r);
34
+ } catch {
35
+ reject(new Error("Invalid JSON"));
36
+ }
37
+ });
38
+ });
39
+ req.on("error", reject);
40
+ if (payload) req.write(payload);
41
+ req.end();
42
+ });
43
+ }
44
+ var InstagramConnector = class extends events.EventEmitter {
45
+ config;
46
+ running = false;
47
+ processedIds = /* @__PURE__ */ new Set();
48
+ constructor(config) {
49
+ super();
50
+ this.config = {
51
+ dmPolicy: "allowlist",
52
+ allowFrom: [],
53
+ approvedPairings: [],
54
+ pendingPairings: {},
55
+ ...config
56
+ };
57
+ }
58
+ async connect() {
59
+ const info = await igReq(this.config.pageAccessToken, "GET", `/${this.config.instagramAccountId}?fields=name,username`);
60
+ await this.loadState();
61
+ this.running = true;
62
+ console.log(chalk.default.green(` 🦅 Instagram: @${info.username || info.name} connected`));
63
+ this.emit("connected", {
64
+ accountId: this.config.instagramAccountId,
65
+ username: info.username
66
+ });
67
+ }
68
+ disconnect() {
69
+ this.running = false;
70
+ }
71
+ verifyWebhook(mode, token, challenge) {
72
+ return mode === "subscribe" && token === this.config.verifyToken ? challenge : null;
73
+ }
74
+ async handleWebhook(body) {
75
+ let payload;
76
+ try {
77
+ payload = JSON.parse(body);
78
+ } catch {
79
+ return;
80
+ }
81
+ for (const entry of payload.entry || []) for (const messaging of entry.messaging || []) {
82
+ if (!messaging.message || messaging.message.is_echo) continue;
83
+ const msgId = messaging.message.mid;
84
+ if (this.processedIds.has(msgId)) continue;
85
+ this.processedIds.add(msgId);
86
+ const senderId = messaging.sender.id;
87
+ const text = messaging.message.text;
88
+ if (!text) continue;
89
+ const allowed = await this.checkDMPolicy(senderId, text);
90
+ if (!allowed) continue;
91
+ this.emit("message", {
92
+ id: msgId,
93
+ channelId: "instagram",
94
+ from: senderId,
95
+ chatId: senderId,
96
+ text,
97
+ timestamp: new Date(messaging.timestamp).toISOString(),
98
+ isDM: true
99
+ });
100
+ }
101
+ }
102
+ async checkDMPolicy(from, text) {
103
+ if (this.config.dmPolicy === "none") return false;
104
+ if (this.config.dmPolicy === "open") return true;
105
+ if (this.config.dmPolicy === "allowlist") {
106
+ if (this.config.allowFrom.includes(from)) return true;
107
+ await this.sendMessage(from, "🦅 HyperClaw: You are not on the allowlist.");
108
+ return false;
109
+ }
110
+ if (this.config.dmPolicy === "pairing") {
111
+ if (this.config.approvedPairings.includes(from)) return true;
112
+ const upper = text.trim().toUpperCase();
113
+ if (this.config.pendingPairings[upper]) {
114
+ this.config.approvedPairings.push(from);
115
+ delete this.config.pendingPairings[upper];
116
+ await this.saveState();
117
+ await this.sendMessage(from, "🦅 Paired! You can now send messages.");
118
+ return true;
119
+ }
120
+ const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
121
+ this.config.pendingPairings[code] = from;
122
+ await this.saveState();
123
+ await this.sendMessage(from, `🦅 HyperClaw Pairing\nCode: ${code}\nApprove: hyperclaw pairing approve instagram ${code}`);
124
+ return false;
125
+ }
126
+ return false;
127
+ }
128
+ async sendMessage(recipientId, text) {
129
+ await igReq(this.config.pageAccessToken, "POST", `/${this.config.instagramAccountId}/messages`, {
130
+ recipient: { id: recipientId },
131
+ message: { text: text.slice(0, 2e3) }
132
+ });
133
+ }
134
+ approvePairing(code) {
135
+ const upper = code.toUpperCase();
136
+ if (!this.config.pendingPairings[upper]) return false;
137
+ this.config.approvedPairings.push(this.config.pendingPairings[upper]);
138
+ delete this.config.pendingPairings[upper];
139
+ this.saveState();
140
+ return true;
141
+ }
142
+ async loadState() {
143
+ try {
144
+ const s = await fs_extra.default.readJson(STATE_FILE);
145
+ if (s.p) this.config.pendingPairings = s.p;
146
+ if (s.a) this.config.approvedPairings = s.a;
147
+ } catch {}
148
+ }
149
+ async saveState() {
150
+ await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
151
+ await fs_extra.default.writeJson(STATE_FILE, {
152
+ p: this.config.pendingPairings,
153
+ a: this.config.approvedPairings
154
+ }, { spaces: 2 });
155
+ }
156
+ isRunning() {
157
+ return this.running;
158
+ }
159
+ };
160
+
161
+ //#endregion
162
+ exports.InstagramConnector = InstagramConnector;