| 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). |
| 5 | const { spawn } = require('child_process'); |
| 6 | const fs = require('fs'); |
| 7 | const path = require('path'); |
| 8 | const { SKILLS_ROOT } = require('./skill-fs'); |
| 9 | |
| 10 | function 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 = ` |
| 21 | import imaplib, json, os, sys, time |
| 22 | from email.mime.text import MIMEText |
| 23 | from email.utils import formatdate, make_msgid |
| 24 | from pathlib import Path |
| 25 | |
| 26 | skill_dir = Path(os.environ["SKILL_DIR"]) |
| 27 | cfg = json.loads((skill_dir / "config.json").read_text()) |
| 28 | pwd = json.loads((skill_dir / "imap-credentials.json").read_text())["password"] |
| 29 | |
| 30 | from_email = os.environ["FROM_EMAIL"] |
| 31 | from_name = os.environ.get("FROM_NAME", "") |
| 32 | subject = os.environ["SUBJECT"] |
| 33 | body = os.environ["BODY"] |
| 34 | |
| 35 | msg = MIMEText(body, "plain", "utf-8") |
| 36 | msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email |
| 37 | msg["To"] = cfg["botEmail"] |
| 38 | msg["Subject"] = subject |
| 39 | msg["Date"] = formatdate(localtime=True) |
| 40 | msg["Message-ID"] = make_msgid(domain=cfg["botEmail"].split("@", 1)[1]) |
| 41 | |
| 42 | host = cfg.get("imapHost", "localhost") |
| 43 | port = int(cfg.get("imapPort", 993)) |
| 44 | use_ssl = cfg.get("imapSsl", True) |
| 45 | cls = imaplib.IMAP4_SSL if use_ssl else imaplib.IMAP4 |
| 46 | M = cls(host, port) |
| 47 | M.login(cfg["botEmail"], pwd) |
| 48 | typ, _ = M.append("INBOX", None, imaplib.Time2Internaldate(time.time()), msg.as_bytes()) |
| 49 | M.logout() |
| 50 | print(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 | |
| 71 | module.exports = { injectEmail }; |