| 1 | const express = require('express'); |
| 2 | const fs = require('fs'); |
| 3 | const path = require('path'); |
| 4 | const { listAgents, getAgent, createAgent, updateAgent, deleteAgent, |
| 5 | readSkillFile, writeSkillFile, |
| 6 | listVersions, rollbackVersion, |
| 7 | discoverAgents } = require('../lib/skill-fs'); |
| 8 | const { checkAgent } = require('../lib/gmail-poller'); |
| 9 | const users = require('../lib/users'); |
| 10 | const { getPlan } = require('../lib/plans'); |
| 11 | |
| 12 | const SESSIONS_FILE = path.resolve(__dirname, '..', 'data', 'activity-sessions.json'); |
| 13 | const SPEND_CACHE_TTL = 60_000; |
| 14 | const _spendCache = new Map(); // agentId -> { data, expiresAt } |
| 15 | |
| 16 | const router = express.Router(); |
| 17 | |
| 18 | router.get('/', (req, res) => { |
| 19 | // Auto-discover any new skills present on disk so the UI is never out-of-sync |
| 20 | // with `~/.claude/skills/` (e.g. after a fresh deploy that wiped the registry). |
| 21 | try { discoverAgents(); } catch {} |
| 22 | res.json(listAgents()); |
| 23 | }); |
| 24 | |
| 25 | router.post('/discover', (req, res) => { |
| 26 | try { res.json({ added: discoverAgents() }); } |
| 27 | catch (e) { res.status(500).json({ error: e.message }); } |
| 28 | }); |
| 29 | |
| 30 | router.get('/:id', (req, res) => { |
| 31 | const a = getAgent(req.params.id); |
| 32 | if (!a) return res.status(404).json({ error: 'not found' }); |
| 33 | res.json(a); |
| 34 | }); |
| 35 | |
| 36 | router.post('/', async (req, res) => { |
| 37 | // Enforce per-plan agent limit |
| 38 | if (req.session?.user?.sub) { |
| 39 | const u = users.findUser(req.session.user.sub); |
| 40 | const plan = getPlan(u?.plan || 'free'); |
| 41 | const all = listAgents(); |
| 42 | const mine = u ? all.filter(a => !a.ownerId || a.ownerId === u.username) : all; |
| 43 | if (mine.length >= plan.maxAgents) { |
| 44 | return res.status(403).json({ |
| 45 | error: `Your ${plan.name} plan allows ${plan.maxAgents} agent(s). Upgrade to create more.`, |
| 46 | limitReached: true, |
| 47 | plan: plan.id, |
| 48 | }); |
| 49 | } |
| 50 | } |
| 51 | try { |
| 52 | const body = { ...req.body }; |
| 53 | if (req.session?.user?.sub) body.ownerId = req.session.user.sub; |
| 54 | res.status(201).json(await createAgent(body)); |
| 55 | } |
| 56 | catch (e) { res.status(400).json({ error: e.message }); } |
| 57 | }); |
| 58 | |
| 59 | router.patch('/:id', (req, res) => { |
| 60 | try { res.json(updateAgent(req.params.id, req.body)); } |
| 61 | catch (e) { res.status(400).json({ error: e.message }); } |
| 62 | }); |
| 63 | |
| 64 | router.delete('/:id', async (req, res) => { |
| 65 | try { |
| 66 | // By default a delete now wipes everything (skill folder + mailbox). |
| 67 | // Pass ?keep=1 to only remove the registry entry. |
| 68 | const keep = req.query.keep === '1'; |
| 69 | await deleteAgent(req.params.id, { removeSkill: !keep, removeMailbox: !keep }); |
| 70 | res.json({ ok: true }); |
| 71 | } catch (e) { res.status(400).json({ error: e.message }); } |
| 72 | }); |
| 73 | |
| 74 | // Read skill files (SKILL.md, config.json, etc.) |
| 75 | router.get('/:id/files/:file', (req, res) => { |
| 76 | const file = req.params.file; |
| 77 | if (!/^[\w.-]+$/.test(file)) return res.status(400).json({ error: 'bad filename' }); |
| 78 | const content = readSkillFile(req.params.id, file); |
| 79 | if (content == null) return res.status(404).json({ error: 'file not found' }); |
| 80 | res.type('text/plain').send(content); |
| 81 | }); |
| 82 | |
| 83 | router.put('/:id/files/:file', (req, res) => { |
| 84 | const file = req.params.file; |
| 85 | if (!/^[\w.-]+$/.test(file)) return res.status(400).json({ error: 'bad filename' }); |
| 86 | // Forbid writing token/credentials via this endpoint |
| 87 | if (file === 'token.json' || file === 'credentials.json') |
| 88 | return res.status(403).json({ error: 'use the upload endpoint for credentials' }); |
| 89 | try { |
| 90 | writeSkillFile(req.params.id, file, req.body.content || ''); |
| 91 | res.json({ ok: true }); |
| 92 | } catch (e) { res.status(400).json({ error: e.message }); } |
| 93 | }); |
| 94 | |
| 95 | // Versioning |
| 96 | router.get('/:id/versions', (req, res) => { |
| 97 | if (!getAgent(req.params.id)) return res.status(404).json({ error: 'agent not found' }); |
| 98 | res.json(listVersions(req.params.id)); |
| 99 | }); |
| 100 | |
| 101 | router.post('/:id/versions/:n/rollback', (req, res) => { |
| 102 | try { res.json(rollbackVersion(req.params.id, parseInt(req.params.n, 10))); } |
| 103 | catch (e) { res.status(400).json({ error: e.message }); } |
| 104 | }); |
| 105 | |
| 106 | // Manual trigger |
| 107 | router.post('/:id/run', async (req, res) => { |
| 108 | const agent = getAgent(req.params.id); |
| 109 | if (!agent) return res.status(404).json({ error: 'not found' }); |
| 110 | try { res.json(await checkAgent(agent)); } |
| 111 | catch (e) { res.status(500).json({ error: e.message }); } |
| 112 | }); |
| 113 | |
| 114 | // Spending summary for an agent (from activity sessions) — cached 60s |
| 115 | router.get('/:id/spending', async (req, res) => { |
| 116 | if (!getAgent(req.params.id)) return res.status(404).json({ error: 'not found' }); |
| 117 | |
| 118 | const agentId = req.params.id; |
| 119 | const now = Date.now(); |
| 120 | const hit = _spendCache.get(agentId); |
| 121 | if (hit && hit.expiresAt > now) return res.json(hit.data); |
| 122 | |
| 123 | let sessions = []; |
| 124 | try { sessions = JSON.parse(await fs.promises.readFile(SESSIONS_FILE, 'utf8')); } catch {} |
| 125 | |
| 126 | const nowDate = new Date(); |
| 127 | const monthStart = new Date(nowDate.getFullYear(), nowDate.getMonth(), 1).toISOString(); |
| 128 | const dayStart = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate()).toISOString(); |
| 129 | |
| 130 | const mine = sessions.filter(s => (s.agentId || s.agent_id) === agentId && s.cost_usd > 0); |
| 131 | const monthly = mine.filter(s => s.created_at >= monthStart); |
| 132 | const daily = mine.filter(s => s.created_at >= dayStart); |
| 133 | const sum = arr => parseFloat(arr.reduce((t, s) => t + (s.cost_usd || 0), 0).toFixed(4)); |
| 134 | |
| 135 | const data = { |
| 136 | today: sum(daily), |
| 137 | this_month: sum(monthly), |
| 138 | all_time: sum(mine), |
| 139 | runs_month: monthly.length, |
| 140 | runs_today: daily.length, |
| 141 | }; |
| 142 | _spendCache.set(agentId, { data, expiresAt: now + SPEND_CACHE_TTL }); |
| 143 | res.json(data); |
| 144 | }); |
| 145 | |
| 146 | module.exports = router; |