Elffuss BraidHub

kikocis/clonagent public

main · 2.8 KiBRawPermalink
1// Inject a synthetic email into an agent's IMAP inbox so the poller picks it up
2// as a normal "task". Uses the agent's own imap-credentials.json + config.json
3// (only IMAP-based agents are supported; Gmail OAuth agents can't APPEND from
4// outside their OAuth scope cleanly).
5const { spawn } = require('child_process');
6const fs = require('fs');
7const path = require('path');
8const { SKILLS_ROOT } = require('./skill-fs');
9
10function injectEmail({ agentId, fromEmail, fromName, subject, body }) {
11 return new Promise((resolve, reject) => {
12 const skillDir = path.join(SKILLS_ROOT, agentId);
13 if (!fs.existsSync(path.join(skillDir, 'config.json')))
14 return reject(new Error(`agent ${agentId}: no config.json`));
15 if (!fs.existsSync(path.join(skillDir, 'imap-credentials.json')))
16 return reject(new Error(`agent ${agentId}: no imap-credentials.json (only IMAP agents supported)`));
17
18 // Pass values via env to avoid quoting/escaping issues with arbitrary user
19 // input in the python source string.
20 const script = `
21import imaplib, json, os, sys, time
22from email.mime.text import MIMEText
23from email.utils import formatdate, make_msgid
24from pathlib import Path
25
26skill_dir = Path(os.environ["SKILL_DIR"])
27cfg = json.loads((skill_dir / "config.json").read_text())
28pwd = json.loads((skill_dir / "imap-credentials.json").read_text())["password"]
29
30from_email = os.environ["FROM_EMAIL"]
31from_name = os.environ.get("FROM_NAME", "")
32subject = os.environ["SUBJECT"]
33body = os.environ["BODY"]
34
35msg = MIMEText(body, "plain", "utf-8")
36msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email
37msg["To"] = cfg["botEmail"]
38msg["Subject"] = subject
39msg["Date"] = formatdate(localtime=True)
40msg["Message-ID"] = make_msgid(domain=cfg["botEmail"].split("@", 1)[1])
41
42host = cfg.get("imapHost", "localhost")
43port = int(cfg.get("imapPort", 993))
44use_ssl = cfg.get("imapSsl", True)
45cls = imaplib.IMAP4_SSL if use_ssl else imaplib.IMAP4
46M = cls(host, port)
47M.login(cfg["botEmail"], pwd)
48typ, _ = M.append("INBOX", None, imaplib.Time2Internaldate(time.time()), msg.as_bytes())
49M.logout()
50print(json.dumps({"ok": typ == "OK", "message_id": msg["Message-ID"], "to": cfg["botEmail"]}))
51`;
52 const env = {
53 ...process.env,
54 SKILL_DIR: skillDir,
55 FROM_EMAIL: fromEmail,
56 FROM_NAME: fromName || '',
57 SUBJECT: subject || '(sin asunto)',
58 BODY: body || '',
59 };
60 const proc = spawn('python3', ['-c', script], { env });
61 let out = '', err = '';
62 proc.stdout.on('data', d => out += d);
63 proc.stderr.on('data', d => err += d);
64 proc.on('close', code => {
65 if (code !== 0) return reject(new Error(`inject ${code}: ${err.trim() || out.trim()}`));
66 try { resolve(JSON.parse(out.trim())); } catch (e) { reject(new Error(`bad inject output: ${out.slice(0, 200)}`)); }
67 });
68 });
69}
70
71module.exports = { injectEmail };