| 1 | // Tasks = the public name for the email threads each agent processes. |
| 2 | // Creating a task injects a synthetic email into the agent's IMAP inbox so |
| 3 | // the poller picks it up as if it had arrived from outside. |
| 4 | const express = require('express'); |
| 5 | const path = require('path'); |
| 6 | const fs = require('fs'); |
| 7 | const { listAgents, getAgent, SKILLS_ROOT } = require('../lib/skill-fs'); |
| 8 | const { injectEmail } = require('../lib/task-injector'); |
| 9 | const { checkAgent } = require('../lib/gmail-poller'); |
| 10 | |
| 11 | const router = express.Router(); |
| 12 | |
| 13 | // File-level access to the threads store so we can upsert directly. |
| 14 | const THREADS_FILE = path.resolve(__dirname, '..', 'data', 'threads.json'); |
| 15 | function readThreads() { |
| 16 | try { return JSON.parse(fs.readFileSync(THREADS_FILE, 'utf8')); } |
| 17 | catch { return []; } |
| 18 | } |
| 19 | function writeThreads(list) { |
| 20 | fs.mkdirSync(path.dirname(THREADS_FILE), { recursive: true }); |
| 21 | fs.writeFileSync(THREADS_FILE, JSON.stringify(list.slice(0, 500), null, 2)); |
| 22 | } |
| 23 | |
| 24 | // GET /api/tasks → reuse the threads store (already keyed per agent) |
| 25 | const threadsRouter = require('./threads'); |
| 26 | router.use('/', threadsRouter); // delegate /, /:id, /stream, etc. |
| 27 | |
| 28 | // Override creation: a task = an email injected into an agent's INBOX. |
| 29 | router.post('/create', async (req, res) => { |
| 30 | const { agentId, fromEmail, fromName, subject, body } = req.body || {}; |
| 31 | if (!agentId || !subject) return res.status(400).json({ error: 'agentId and subject required' }); |
| 32 | const agent = getAgent(agentId); |
| 33 | if (!agent) return res.status(404).json({ error: 'agent not found' }); |
| 34 | |
| 35 | // The from address must be in the agent's authorized senders (any role) — |
| 36 | // otherwise the agent would skip it on next poll anyway. |
| 37 | const senders = (agent.authorizedSenders || []).map(s => (s.email || s).toLowerCase()); |
| 38 | let from = (fromEmail || '').toLowerCase(); |
| 39 | if (!from) { |
| 40 | // Default to the calling user's email if it's authorized |
| 41 | const me = req.session?.user?.email?.toLowerCase(); |
| 42 | if (me && senders.includes(me)) from = me; |
| 43 | else if (senders.length === 1) from = senders[0]; |
| 44 | else return res.status(400).json({ error: 'fromEmail required (authorized sender)' }); |
| 45 | } |
| 46 | if (!senders.includes(from)) |
| 47 | return res.status(403).json({ error: `from ${from} is not in authorizedSenders` }); |
| 48 | |
| 49 | if (agent.mailProvider !== 'imap') |
| 50 | return res.status(400).json({ error: 'task creation only supported on IMAP agents' }); |
| 51 | |
| 52 | try { |
| 53 | const result = await injectEmail({ |
| 54 | agentId, |
| 55 | fromEmail: from, |
| 56 | fromName: fromName || req.session?.user?.name || '', |
| 57 | subject, |
| 58 | body: body || '', |
| 59 | }); |
| 60 | // Eagerly register a thread entry so the UI shows it immediately, even |
| 61 | // before the agent has processed the email. |
| 62 | const all = readThreads(); |
| 63 | const now = new Date().toISOString(); |
| 64 | const thread = { |
| 65 | id: result.message_id, |
| 66 | agentId, |
| 67 | from, |
| 68 | subject, |
| 69 | status: 'queued', |
| 70 | createdAt: now, |
| 71 | updatedAt: now, |
| 72 | events: [{ |
| 73 | kind: 'email', |
| 74 | role: 'user', |
| 75 | from, |
| 76 | to: result.to, |
| 77 | subject, |
| 78 | body: body || '', |
| 79 | at: now, |
| 80 | }], |
| 81 | }; |
| 82 | all.unshift(thread); |
| 83 | writeThreads(all); |
| 84 | // Kick the poller right away so the user sees movement |
| 85 | checkAgent(agent).catch(() => {}); |
| 86 | res.json({ ok: true, threadId: thread.id, ...result }); |
| 87 | } catch (e) { |
| 88 | res.status(500).json({ error: e.message }); |
| 89 | } |
| 90 | }); |
| 91 | |
| 92 | module.exports = router; |