| 1 | // Two-agent loop per clone: |
| 2 | // Scheduler — fires when new email arrives; plans tasks → agent-tasks.json |
| 3 | // Executor — fires every 2 min when pending tasks exist; executes them |
| 4 | // Never more than one scheduler + one executor active at the same time per agent. |
| 5 | const { spawn } = require('child_process'); |
| 6 | const fs = require('fs'); |
| 7 | const path = require('path'); |
| 8 | const cron = require('node-cron'); |
| 9 | const { listAgents, SKILLS_ROOT } = require('./skill-fs'); |
| 10 | const { launchScheduler, launchExecutor } = require('./relay-client'); |
| 11 | const { recordRun } = require('./runs'); |
| 12 | const threadStore = require('./email-thread-store'); |
| 13 | const agentSessions = require('./agent-sessions'); |
| 14 | const taskQueue = require('./task-queue'); |
| 15 | |
| 16 | const COMMAND_PREFIX = '!'; |
| 17 | const HELP_TEXT = `ClonAgent commands — send any of these to manage your agent: |
| 18 | |
| 19 | !help Show this message |
| 20 | !status Agent status |
| 21 | !senders List authorized senders |
| 22 | !add someone@example.com Add an authorized sender |
| 23 | !remove someone@example.com Remove an authorized sender |
| 24 | !pause Pause this agent |
| 25 | !resume Resume this agent |
| 26 | |
| 27 | Any other email (no !) is treated as a request and handled by Claude.`; |
| 28 | |
| 29 | async function detectAndHandleCommand(agent, msg, threadId, script, skillDir) { |
| 30 | const text = ((msg.subject || '') + '\n' + (msg.body || '')).trim(); |
| 31 | const firstLine = text.split('\n').find(l => l.trim()) || ''; |
| 32 | if (!firstLine.startsWith(COMMAND_PREFIX)) return false; |
| 33 | |
| 34 | const [rawCmd, ...args] = firstLine.slice(1).trim().split(/\s+/); |
| 35 | const cmd = rawCmd.toLowerCase(); |
| 36 | const configPath = path.join(skillDir, 'config.json'); |
| 37 | let config = {}; |
| 38 | try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch {} |
| 39 | |
| 40 | let reply = ''; |
| 41 | |
| 42 | if (cmd === 'help') { |
| 43 | reply = HELP_TEXT; |
| 44 | } else if (cmd === 'status') { |
| 45 | const fresh = listAgents().find(a => a.id === agent.id) || agent; |
| 46 | const senders = config.authorizedSenders || []; |
| 47 | reply = `Agent: ${fresh.id}\nStatus: ${fresh.enabled ? '✅ active' : '⏸ paused'}\nAuthorized senders: ${senders.length}\n\nSend !help for all commands.`; |
| 48 | } else if (cmd === 'senders') { |
| 49 | const senders = config.authorizedSenders || []; |
| 50 | reply = senders.length |
| 51 | ? 'Authorized senders:\n' + senders.map(s => ' • ' + (typeof s === 'string' ? s : s.email)).join('\n') |
| 52 | : 'No authorized senders configured yet.'; |
| 53 | } else if (cmd === 'add') { |
| 54 | const email = args[0]; |
| 55 | if (!email || !email.includes('@')) { |
| 56 | reply = '❌ Usage: !add email@example.com'; |
| 57 | } else { |
| 58 | const senders = config.authorizedSenders || []; |
| 59 | if (senders.some(s => (typeof s === 'string' ? s : s.email) === email)) { |
| 60 | reply = `ℹ️ ${email} is already authorized.`; |
| 61 | } else { |
| 62 | config.authorizedSenders = [...senders, email]; |
| 63 | fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); |
| 64 | reply = `✅ Added ${email} as an authorized sender.`; |
| 65 | } |
| 66 | } |
| 67 | } else if (cmd === 'remove') { |
| 68 | const email = args[0]; |
| 69 | if (!email) { |
| 70 | reply = '❌ Usage: !remove email@example.com'; |
| 71 | } else { |
| 72 | const before = (config.authorizedSenders || []).length; |
| 73 | config.authorizedSenders = (config.authorizedSenders || []) |
| 74 | .filter(s => (typeof s === 'string' ? s : s.email) !== email); |
| 75 | if (config.authorizedSenders.length === before) { |
| 76 | reply = `ℹ️ ${email} was not in the list.`; |
| 77 | } else { |
| 78 | fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); |
| 79 | reply = `✅ Removed ${email}.`; |
| 80 | } |
| 81 | } |
| 82 | } else if (cmd === 'pause') { |
| 83 | const { updateAgent } = require('./skill-fs'); |
| 84 | updateAgent(agent.id, { enabled: false }); |
| 85 | reply = '⏸ Agent paused. Send !resume to reactivate it.'; |
| 86 | } else if (cmd === 'resume') { |
| 87 | const { updateAgent } = require('./skill-fs'); |
| 88 | updateAgent(agent.id, { enabled: true }); |
| 89 | reply = '✅ Agent resumed. Checking for emails every minute.'; |
| 90 | } else { |
| 91 | reply = `❓ Unknown command: !${cmd}\n\nSend !help to see available commands.`; |
| 92 | } |
| 93 | |
| 94 | try { |
| 95 | await runPython(skillDir, [script, 'reply', threadId, '--body', reply]); |
| 96 | } catch (e) { |
| 97 | console.error(`[command] reply failed for ${agent.id}: ${e.message}`); |
| 98 | } |
| 99 | return true; |
| 100 | } |
| 101 | |
| 102 | |
| 103 | const PYTHON = process.env.PYTHON_BIN || '/usr/bin/env python3'; |
| 104 | const PUBLIC_URL = (process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com').replace(/\/$/, ''); |
| 105 | |
| 106 | let pollerRunning = false; |
| 107 | let executorRunning = false; |
| 108 | |
| 109 | // ── Email poller (every 1 min) → triggers Scheduler ─────────────────────── |
| 110 | |
| 111 | async function checkAgent(agent) { |
| 112 | const skillDir = path.join(SKILLS_ROOT, agent.id); |
| 113 | const script = agent.mailProvider === 'imap' ? 'mail_client.py' : 'gmail_client.py'; |
| 114 | if (!fs.existsSync(path.join(skillDir, script))) |
| 115 | throw new Error(`${script} not found in ${skillDir}`); |
| 116 | |
| 117 | const unread = await runPython(skillDir, [script, 'list-unread', '--days', '7']); |
| 118 | if (!unread || unread.length === 0) return { agent: agent.id, processed: 0 }; |
| 119 | |
| 120 | // Group by thread |
| 121 | const byThread = new Map(); |
| 122 | for (const m of unread) { |
| 123 | const tid = m.thread_id || m.message_id || m.uid; |
| 124 | if (!byThread.has(tid)) byThread.set(tid, []); |
| 125 | byThread.get(tid).push(m); |
| 126 | } |
| 127 | |
| 128 | // Record incoming emails in the UI task feed |
| 129 | await recordIncomingEmails(agent, byThread, script, skillDir); |
| 130 | |
| 131 | let processed = 0; |
| 132 | for (const [threadId, msgs] of byThread) { |
| 133 | const last = msgs[msgs.length - 1]; |
| 134 | try { |
| 135 | // Check for !commands first — handle them without launching Claude |
| 136 | let fullMsg = last; |
| 137 | try { |
| 138 | const thread = await runPython(skillDir, [script, 'get-thread', threadId]); |
| 139 | const lastMsg = thread?.messages?.[thread.messages.length - 1] || thread; |
| 140 | fullMsg = { ...last, body: lastMsg?.body || '' }; |
| 141 | } catch {} |
| 142 | const wasCommand = await detectAndHandleCommand(agent, fullMsg, threadId, script, skillDir); |
| 143 | if (wasCommand) { |
| 144 | for (const m of msgs) { |
| 145 | if (m.uid) runPython(skillDir, [script, 'mark-read', m.uid]).catch(() => {}); |
| 146 | } |
| 147 | processed++; |
| 148 | continue; |
| 149 | } |
| 150 | |
| 151 | // Trigger scheduler (it will plan tasks; executor picks them up separately) |
| 152 | const launch = await launchScheduler(agent, { |
| 153 | from: last.from, subject: last.subject, threadId, |
| 154 | }); |
| 155 | |
| 156 | if (launch) { |
| 157 | threadStore.rememberSession(agent.id, threadId, launch.sessionId); |
| 158 | fetch(`${PUBLIC_URL}/api/tasks/${encodeURIComponent(threadId)}`, { |
| 159 | method: 'PATCH', headers: { 'Content-Type': 'application/json' }, |
| 160 | body: JSON.stringify({ sessionId: launch.sessionId, status: 'running' }), |
| 161 | }).catch(() => {}); |
| 162 | recordRun({ agentId: agent.id, threadId, sessionId: launch.sessionId, |
| 163 | from: last.from, subject: last.subject, status: 'scheduled', |
| 164 | at: new Date().toISOString() }); |
| 165 | } |
| 166 | |
| 167 | // Mark emails as read so we don't re-trigger the scheduler |
| 168 | for (const m of msgs) { |
| 169 | if (m.uid) runPython(skillDir, [script, 'mark-read', m.uid]).catch(() => {}); |
| 170 | } |
| 171 | processed++; |
| 172 | } catch (err) { |
| 173 | recordRun({ agentId: agent.id, threadId, from: last.from, |
| 174 | subject: last.subject, status: 'error', error: err.message, |
| 175 | at: new Date().toISOString() }); |
| 176 | } |
| 177 | } |
| 178 | return { agent: agent.id, processed }; |
| 179 | } |
| 180 | |
| 181 | // ── Executor tick (every 2 min) → launches Executor if tasks pending ─────── |
| 182 | |
| 183 | async function tickExecutor() { |
| 184 | if (executorRunning) return; |
| 185 | executorRunning = true; |
| 186 | try { |
| 187 | const agents = listAgents().filter(a => a.enabled && a.ready); |
| 188 | for (const agent of agents) { |
| 189 | if (!taskQueue.hasPending(agent.id)) continue; |
| 190 | try { |
| 191 | const launch = await launchExecutor(agent); |
| 192 | if (launch) { |
| 193 | console.log(`[executor] ${agent.id}: launched session=${launch.sessionId}`); |
| 194 | recordRun({ agentId: agent.id, sessionId: launch.sessionId, |
| 195 | status: 'executor-launched', at: new Date().toISOString() }); |
| 196 | } |
| 197 | } catch (err) { |
| 198 | console.error(`[executor] ${agent.id}: ${err.message}`); |
| 199 | } |
| 200 | } |
| 201 | } finally { executorRunning = false; } |
| 202 | } |
| 203 | |
| 204 | // ── Mark scheduler/executor as done when activity reports session end ────── |
| 205 | // Called from activity.js when a session_end or session_error event arrives. |
| 206 | |
| 207 | function onSessionEnd(relaySessionId) { |
| 208 | // Find which agent+role owns this relay session and mark it idle |
| 209 | const all = require('./agent-sessions').get; |
| 210 | // We stored ${role}RelayId in agent-sessions — scan all agents |
| 211 | try { |
| 212 | const data = JSON.parse(fs.readFileSync( |
| 213 | path.resolve(__dirname, '..', 'data', 'agent-sessions.json'), 'utf8')); |
| 214 | for (const [agentId, sess] of Object.entries(data)) { |
| 215 | if (sess.schedulerRelayId === relaySessionId) { |
| 216 | agentSessions.setActive(agentId, 'scheduler', false); |
| 217 | console.log(`[runner] ${agentId}: scheduler done (${relaySessionId})`); |
| 218 | } |
| 219 | if (sess.executorRelayId === relaySessionId) { |
| 220 | agentSessions.setActive(agentId, 'executor', false); |
| 221 | console.log(`[runner] ${agentId}: executor done (${relaySessionId})`); |
| 222 | } |
| 223 | } |
| 224 | } catch { /* ignore */ } |
| 225 | } |
| 226 | |
| 227 | // ── Email recording helper ───────────────────────────────────────────────── |
| 228 | |
| 229 | async function recordIncomingEmails(agent, byThread, script, skillDir) { |
| 230 | for (const [tid, msgs] of byThread) { |
| 231 | for (const m of msgs) { |
| 232 | const idArg = m.thread_id || m.message_id || m.uid; |
| 233 | let body = ''; |
| 234 | try { |
| 235 | const full = await runPython(skillDir, [script, 'get-thread', idArg]); |
| 236 | body = full?.messages?.[full.messages.length - 1]?.body || full?.body || ''; |
| 237 | } catch { /* best-effort */ } |
| 238 | try { |
| 239 | await fetch(`${PUBLIC_URL}/api/tasks`, { |
| 240 | method: 'POST', headers: { 'Content-Type': 'application/json' }, |
| 241 | body: JSON.stringify({ id: tid, agentId: agent.id, from: m.from, |
| 242 | subject: m.subject, status: 'running' }), |
| 243 | }).catch(() => {}); |
| 244 | await fetch(`${PUBLIC_URL}/api/tasks/${encodeURIComponent(tid)}/events`, { |
| 245 | method: 'POST', headers: { 'Content-Type': 'application/json' }, |
| 246 | body: JSON.stringify({ kind: 'email', role: 'user', from: m.from, |
| 247 | sender_role: m.sender_role, subject: m.subject, body, |
| 248 | at: new Date().toISOString() }), |
| 249 | }).catch(() => {}); |
| 250 | } catch { /* best-effort */ } |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | function runPython(cwd, args) { |
| 256 | return new Promise((resolve, reject) => { |
| 257 | const cmd = PYTHON.split(/\s+/); |
| 258 | const proc = spawn(cmd[0], [...cmd.slice(1), ...args], { cwd }); |
| 259 | let out = '', err = ''; |
| 260 | proc.stdout.on('data', d => out += d); |
| 261 | proc.stderr.on('data', d => err += d); |
| 262 | proc.on('close', code => { |
| 263 | if (code !== 0) return reject(new Error(`python exited ${code}: ${err}`)); |
| 264 | try { resolve(JSON.parse(out || '[]')); } |
| 265 | catch (e) { reject(new Error(`bad JSON: ${e.message}`)); } |
| 266 | }); |
| 267 | }); |
| 268 | } |
| 269 | |
| 270 | // ── Cron setup ───────────────────────────────────────────────────────────── |
| 271 | |
| 272 | async function tick() { |
| 273 | if (pollerRunning) return; |
| 274 | pollerRunning = true; |
| 275 | try { |
| 276 | const agents = listAgents().filter(a => a.enabled && a.ready); |
| 277 | if (agents.length) console.log(`[poller] checking ${agents.length} agent(s): ${agents.map(a => a.id).join(', ')}`); |
| 278 | for (const a of agents) { |
| 279 | try { |
| 280 | const r = await checkAgent(a); |
| 281 | if (r.processed) console.log(`[poller] ${a.id}: triggered scheduler for ${r.processed} thread(s)`); |
| 282 | } catch (err) { console.error(`[poller] ${a.id}: ${err.message}`); } |
| 283 | } |
| 284 | } finally { pollerRunning = false; } |
| 285 | } |
| 286 | |
| 287 | function startPoller() { |
| 288 | cron.schedule('* * * * *', tick); // email check: every 1 min |
| 289 | cron.schedule('*/2 * * * *', tickExecutor); // executor: every 2 min |
| 290 | console.log('[poller] started (email: 1min, executor: 2min)'); |
| 291 | } |
| 292 | |
| 293 | module.exports = { startPoller, tick, tickExecutor, checkAgent, onSessionEnd }; |