| 1 | // Chat endpoint with proper tool-calling loop. Persists conversations per user. |
| 2 | const express = require('express'); |
| 3 | const { chat } = require('../lib/claude-client'); |
| 4 | const { createAgent, updateAgent, getAgent, listAgents } = require('../lib/skill-fs'); |
| 5 | const { addServer, removeServer } = require('../lib/mcp-fs'); |
| 6 | const { listRegistry } = require('../lib/mcp-registry'); |
| 7 | const mailServer = require('../lib/mail-server'); |
| 8 | const sessions = require('../lib/chat-store'); |
| 9 | const gitea = require('../lib/gitea-client'); |
| 10 | const pg = require('../lib/postgres-client'); |
| 11 | const taskInjector = require('../lib/task-injector'); |
| 12 | const { checkAgent } = require('../lib/gmail-poller'); |
| 13 | const fs = require('fs'); |
| 14 | const path = require('path'); |
| 15 | const os = require('os'); |
| 16 | |
| 17 | const router = express.Router(); |
| 18 | |
| 19 | // ─── Sessions list / get / delete / rename ─────────────────────────────── |
| 20 | router.get('/sessions', (req, res) => { |
| 21 | res.json(sessions.listSessions(req.session.user?.sub || 'anon')); |
| 22 | }); |
| 23 | router.get('/sessions/:id', (req, res) => { |
| 24 | const s = sessions.getSession(req.params.id, req.session.user?.sub || 'anon'); |
| 25 | if (!s) return res.status(404).json({ error: 'session not found' }); |
| 26 | res.json(s); |
| 27 | }); |
| 28 | router.delete('/sessions/:id', (req, res) => { |
| 29 | sessions.deleteSession(req.params.id, req.session.user?.sub || 'anon'); |
| 30 | res.json({ ok: true }); |
| 31 | }); |
| 32 | router.patch('/sessions/:id', (req, res) => { |
| 33 | const { title } = req.body || {}; |
| 34 | const updated = sessions.renameSession(req.params.id, req.session.user?.sub || 'anon', title); |
| 35 | if (!updated) return res.status(404).json({ error: 'session not found' }); |
| 36 | res.json(updated); |
| 37 | }); |
| 38 | |
| 39 | const SYSTEM_PROMPT = `Eres "ClonAgent Builder", un asistente que ayuda al usuario a crear, editar y |
| 40 | operar agentes que procesan correo electrónico (clones de premeti-email-triage). |
| 41 | |
| 42 | Schema de un agente: |
| 43 | - id (string, lowercase-kebab) REQUERIDO al crear |
| 44 | - name (string) REQUERIDO al crear |
| 45 | - description (string) opcional |
| 46 | - botEmail (string) opcional (auto en IMAP) |
| 47 | - authorizedSenders (array de {email, role}) REQUERIDO al crear (≥1) |
| 48 | - projectPath / deployHost / deployUser / deployDir opcional |
| 49 | - sshKey opcional |
| 50 | - mailProvider ("gmail" | "imap") default "imap" si mailserver activo |
| 51 | - pollMinutes (number) default 1 |
| 52 | - extraContext (string) opcional |
| 53 | |
| 54 | Si el usuario menciona un agente sin decirte su id exacto ("el agente de btc", |
| 55 | "haz que arranque el de mia"), llama PRIMERO a 'list_agents' para resolverlo. |
| 56 | NUNCA inventes ids. |
| 57 | |
| 58 | Si el usuario dice "haz que funcione X" / "que arranque X" / "actívalo": |
| 59 | - enabled=false → llama 'update_agent' con enabled:true |
| 60 | - enabled=true → propón 'create_task' con un mensaje de arranque |
| 61 | - ready=false → dile qué credencial le falta |
| 62 | |
| 63 | Cuando el usuario quiera crear un agente nuevo, primero pregunta si: |
| 64 | (a) Es para un proyecto existente — pídele ruta del repo + deploy host |
| 65 | (b) Es para un proyecto nuevo — ofrece crear repo en Gitea built-in |
| 66 | ('gitea_create_repo'), provisionar Postgres ('provision_database'), etc. |
| 67 | |
| 68 | Por defecto cada agente nuevo lleva su propio buzón en bot.utopiaia.com. |
| 69 | NO llames 'provision_mailbox' a mano: 'save_agent' lo crea automáticamente. |
| 70 | |
| 71 | Equipas al agente con MCP servers (github, slack, jira, postgres, k8s…) con |
| 72 | 'add_mcp_server'/'remove_mcp_server'/'list_mcp_registry'. |
| 73 | |
| 74 | Reglas: |
| 75 | - Sé breve. UNA pregunta a la vez. |
| 76 | - Confirma antes de crear/borrar. |
| 77 | - Si tienes dudas, pregunta — no inventes. |
| 78 | - Después de ejecutar tools, RESUME al usuario lo que se hizo en lenguaje natural.`; |
| 79 | |
| 80 | const TOOLS = [ |
| 81 | { type: 'function', function: { name: 'list_agents', description: 'Lista todos los agentes existentes con id, name, botEmail, enabled, ready, mailProvider, authorizedSenders.', parameters: { type: 'object', properties: {} } } }, |
| 82 | { type: 'function', function: { name: 'save_agent', description: 'Crea un nuevo ClonAgent. Auto-provisiona mailbox IMAP si mailserver activo.', |
| 83 | parameters: { type: 'object', properties: { |
| 84 | id: { type: 'string', pattern: '^[a-z0-9-]+$' }, name: { type: 'string' }, description: { type: 'string' }, botEmail: { type: 'string' }, |
| 85 | authorizedSenders: { type: 'array', items: { type: 'object', properties: { email: { type: 'string' }, role: { type: 'string', enum: ['owner', 'cocreator', 'reader'] } }, required: ['email'] } }, |
| 86 | projectPath: { type: 'string' }, deployHost: { type: 'string' }, deployUser: { type: 'string' }, deployDir: { type: 'string' }, sshKey: { type: 'string' }, |
| 87 | pollMinutes: { type: 'number' }, extraContext: { type: 'string' }, |
| 88 | mailProvider: { type: 'string', enum: ['gmail', 'imap'] }, |
| 89 | }, required: ['id', 'name', 'authorizedSenders'] } } }, |
| 90 | { type: 'function', function: { name: 'update_agent', description: 'Actualiza un agente existente (config, enabled, senders…).', |
| 91 | parameters: { type: 'object', properties: { |
| 92 | id: { type: 'string' }, name: { type: 'string' }, description: { type: 'string' }, |
| 93 | authorizedSenders: { type: 'array', items: { type: 'object' } }, |
| 94 | projectPath: { type: 'string' }, deployHost: { type: 'string' }, deployUser: { type: 'string' }, deployDir: { type: 'string' }, sshKey: { type: 'string' }, |
| 95 | pollMinutes: { type: 'number' }, extraContext: { type: 'string' }, enabled: { type: 'boolean' }, |
| 96 | }, required: ['id'] } } }, |
| 97 | { type: 'function', function: { name: 'create_task', description: 'Manda una tarea (= email) al inbox del agente. El agente la procesa en su próximo tick.', |
| 98 | parameters: { type: 'object', properties: { |
| 99 | agentId: { type: 'string' }, subject: { type: 'string' }, body: { type: 'string' }, |
| 100 | fromEmail: { type: 'string', description: 'autorizado en el agente; default: email del usuario actual' }, |
| 101 | }, required: ['agentId', 'subject', 'body'] } } }, |
| 102 | { type: 'function', function: { name: 'list_mcp_registry', description: 'Lista los MCP servers disponibles para añadir.', parameters: { type: 'object', properties: {} } } }, |
| 103 | { type: 'function', function: { name: 'add_mcp_server', description: 'Añade un MCP server al agente. values son env vars del registry entry.', |
| 104 | parameters: { type: 'object', properties: { agentId: { type: 'string' }, name: { type: 'string' }, values: { type: 'object' } }, required: ['agentId', 'name', 'values'] } } }, |
| 105 | { type: 'function', function: { name: 'remove_mcp_server', description: 'Quita un MCP server del agente.', |
| 106 | parameters: { type: 'object', properties: { agentId: { type: 'string' }, name: { type: 'string' } }, required: ['agentId', 'name'] } } }, |
| 107 | { type: 'function', function: { name: 'gitea_list_repos', description: 'Lista repos del Gitea built-in.', parameters: { type: 'object', properties: {} } } }, |
| 108 | { type: 'function', function: { name: 'gitea_create_repo', description: 'Crea un repo nuevo en Gitea built-in.', |
| 109 | parameters: { type: 'object', properties: { name: { type: 'string' }, owner: { type: 'string' }, description: { type: 'string' }, private: { type: 'boolean' } }, required: ['name'] } } }, |
| 110 | { type: 'function', function: { name: 'check_repo', description: 'Comprueba si un path local existe o si una URL git responde.', |
| 111 | parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } } }, |
| 112 | { type: 'function', function: { name: 'provision_database', description: 'Crea una BD PostgreSQL nueva en el postgres built-in.', |
| 113 | parameters: { type: 'object', properties: { db: { type: 'string' }, user: { type: 'string' }, password: { type: 'string' } }, required: ['db', 'user'] } } }, |
| 114 | { type: 'function', function: { name: 'provision_mailbox', description: 'Crea un mailbox <agentId>@bot.utopiaia.com manual (save_agent ya lo hace por defecto).', |
| 115 | parameters: { type: 'object', properties: { agentId: { type: 'string' } }, required: ['agentId'] } } }, |
| 116 | ]; |
| 117 | |
| 118 | async function executeTool(name, args, req) { |
| 119 | if (name === 'list_agents') { |
| 120 | return { agents: listAgents().map(a => ({ |
| 121 | id: a.id, name: a.name, botEmail: a.botEmail, enabled: a.enabled, ready: a.ready, |
| 122 | mailProvider: a.mailProvider, authorizedSenders: (a.authorizedSenders || []).map(s => s.email || s), |
| 123 | description: a.description || '', version: a.version, |
| 124 | })) }; |
| 125 | } |
| 126 | if (name === 'save_agent') return { agent: await createAgent(args) }; |
| 127 | if (name === 'update_agent') { |
| 128 | const { id, ...patch } = args; |
| 129 | if (!getAgent(id)) throw new Error(`agent '${id}' not found`); |
| 130 | return { agent: updateAgent(id, patch) }; |
| 131 | } |
| 132 | if (name === 'create_task') { |
| 133 | if (!args.agentId) throw new Error('agentId required — call list_agents first'); |
| 134 | const agent = getAgent(args.agentId); |
| 135 | if (!agent) throw new Error(`agent '${args.agentId}' not found — available: ${listAgents().map(a => a.id).join(', ')}`); |
| 136 | if (agent.mailProvider !== 'imap') throw new Error('create_task only supported on IMAP agents'); |
| 137 | const senders = (agent.authorizedSenders || []).map(s => (s.email || s).toLowerCase()); |
| 138 | let from = (args.fromEmail || '').toLowerCase(); |
| 139 | if (!from) from = req.session?.user?.email?.toLowerCase() || senders[0]; |
| 140 | if (!senders.includes(from)) throw new Error(`from ${from} not in authorizedSenders of ${args.agentId}`); |
| 141 | const result = await taskInjector.injectEmail({ |
| 142 | agentId: args.agentId, fromEmail: from, fromName: req.session?.user?.name || '', |
| 143 | subject: args.subject, body: args.body, |
| 144 | }); |
| 145 | checkAgent(agent).catch(() => {}); |
| 146 | return { task: { agentId: args.agentId, to: result.to, subject: args.subject } }; |
| 147 | } |
| 148 | if (name === 'list_mcp_registry') return { registry: listRegistry().map(e => ({ name: e.name, label: e.label, category: e.category, description: e.description, fields: e.fields })) }; |
| 149 | if (name === 'add_mcp_server') { |
| 150 | if (!getAgent(args.agentId)) throw new Error(`agent '${args.agentId}' not found`); |
| 151 | const built = addServer(args.agentId, args.name, args.values || {}); |
| 152 | return { mcp: { agent: args.agentId, name: args.name, command: built.command } }; |
| 153 | } |
| 154 | if (name === 'remove_mcp_server') { |
| 155 | if (!getAgent(args.agentId)) throw new Error(`agent '${args.agentId}' not found`); |
| 156 | removeServer(args.agentId, args.name); |
| 157 | return { removed: args.name }; |
| 158 | } |
| 159 | if (name === 'gitea_list_repos') { |
| 160 | const list = await gitea.listRepos(); |
| 161 | return { repos: list.slice(0, 30).map(r => ({ full_name: r.full_name, description: r.description, clone_url: r.clone_url, html_url: r.html_url })) }; |
| 162 | } |
| 163 | if (name === 'gitea_create_repo') return { repo: await gitea.createRepo(args) }; |
| 164 | if (name === 'check_repo') { |
| 165 | const p = args.path; |
| 166 | if (/^https?:\/\//.test(p) || p.startsWith('git@')) { |
| 167 | try { |
| 168 | const r = await fetch(p, { signal: AbortSignal.timeout(3000) }); |
| 169 | return { ok: r.ok, info: `HTTP ${r.status}`, path: p }; |
| 170 | } catch (e) { return { ok: false, info: e.message, path: p }; } |
| 171 | } |
| 172 | return { ok: fs.existsSync(p), info: fs.existsSync(p) ? 'exists' : 'not found', path: p }; |
| 173 | } |
| 174 | if (name === 'provision_database') { |
| 175 | const password = args.password || require('crypto').randomBytes(16).toString('base64').replace(/[+/=]/g, ''); |
| 176 | const r = await pg.provisionDatabase({ ...args, password }); |
| 177 | return { db: { db: r.db, user: r.user, host: r.host, port: r.port, password, connectionString: r.connectionString } }; |
| 178 | } |
| 179 | if (name === 'provision_mailbox') { |
| 180 | const email = mailServer.suggestEmailFor(args.agentId); |
| 181 | const password = require('crypto').randomBytes(16).toString('base64').replace(/[+/=]/g, ''); |
| 182 | await mailServer.addMailbox(email, password); |
| 183 | if (getAgent(args.agentId)) { |
| 184 | const credPath = path.join(os.homedir(), '.claude', 'skills', args.agentId, 'imap-credentials.json'); |
| 185 | fs.writeFileSync(credPath, JSON.stringify({ password }, null, 2)); |
| 186 | try { fs.chmodSync(credPath, 0o600); } catch {} |
| 187 | } |
| 188 | return { mailbox: { email, password, imapHost: mailServer.DOMAIN, imapPort: 993, smtpHost: mailServer.DOMAIN, smtpPort: 587 } }; |
| 189 | } |
| 190 | throw new Error(`unknown tool '${name}'`); |
| 191 | } |
| 192 | |
| 193 | router.post('/', async (req, res) => { |
| 194 | const { messages = [], sessionId: providedId } = req.body; |
| 195 | if (!Array.isArray(messages) || messages.length === 0) { |
| 196 | return res.status(400).json({ error: 'messages array required' }); |
| 197 | } |
| 198 | const userId = req.session.user?.sub || 'anon'; |
| 199 | const allActions = []; |
| 200 | let workingMessages = [...messages]; |
| 201 | let finalText = ''; |
| 202 | let finalReason = null; |
| 203 | |
| 204 | try { |
| 205 | // Tool-calling loop. We allow tools on the first call. After tools have |
| 206 | // run we force a final natural-language answer (tool_choice='none') so the |
| 207 | // model can never loop forever calling the same thing. If it didn't use |
| 208 | // any tool on the first call, we just take that text. |
| 209 | const MAX_ITERS = 3; |
| 210 | const calledTools = new Set(); |
| 211 | for (let iter = 0; iter < MAX_ITERS; iter++) { |
| 212 | const lastIter = iter === MAX_ITERS - 1; |
| 213 | const choiceMode = (iter === 0) ? 'auto' : (lastIter ? 'none' : 'auto'); |
| 214 | const resp = await chat({ |
| 215 | system: SYSTEM_PROMPT, |
| 216 | messages: workingMessages, |
| 217 | tools: TOOLS, |
| 218 | userSub: userId, |
| 219 | toolChoice: choiceMode, |
| 220 | }); |
| 221 | const choice = resp.choices?.[0]?.message || {}; |
| 222 | finalReason = resp.choices?.[0]?.finish_reason; |
| 223 | const toolCalls = choice.tool_calls || []; |
| 224 | |
| 225 | if (toolCalls.length === 0) { |
| 226 | finalText = choice.content || ''; |
| 227 | break; |
| 228 | } |
| 229 | |
| 230 | // Detect a runaway loop: same tool+args called again on a later iter. |
| 231 | const fp = toolCalls.map(t => `${t.function?.name}:${t.function?.arguments}`).join('|'); |
| 232 | if (calledTools.has(fp)) { |
| 233 | // Force final answer next iter |
| 234 | workingMessages.push({ |
| 235 | role: 'assistant', |
| 236 | content: 'Tengo lo que necesito, voy a responder al usuario.', |
| 237 | }); |
| 238 | // Loop again with tool_choice=none on the last iter |
| 239 | continue; |
| 240 | } |
| 241 | calledTools.add(fp); |
| 242 | |
| 243 | workingMessages.push({ |
| 244 | role: 'assistant', |
| 245 | content: choice.content || '', |
| 246 | tool_calls: toolCalls, |
| 247 | }); |
| 248 | |
| 249 | for (const tc of toolCalls) { |
| 250 | const name = tc.function?.name; |
| 251 | let args = {}; |
| 252 | try { args = JSON.parse(tc.function?.arguments || '{}'); } |
| 253 | catch { /* bad args */ } |
| 254 | let result; |
| 255 | try { |
| 256 | result = await executeTool(name, args, req); |
| 257 | allActions.push({ tool: name, ok: true, ...result }); |
| 258 | } catch (e) { |
| 259 | result = { error: e.message }; |
| 260 | allActions.push({ tool: name, ok: false, error: e.message }); |
| 261 | } |
| 262 | workingMessages.push({ |
| 263 | role: 'tool', |
| 264 | tool_call_id: tc.id, |
| 265 | content: JSON.stringify(result), |
| 266 | }); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // Strip an optional "{...function_calls: []...}" preamble (line-anchored so |
| 271 | // it doesn't eat the rest of the message), then fall back to a friendly |
| 272 | // default if the model returned nothing. |
| 273 | let cleanedText = (finalText || '').replace(/^\s*\{\s*"?function_calls"?\s*:\s*\[\s*\]\s*\}\s*\n?/i, '').trim(); |
| 274 | const reply = cleanedText || (allActions.length |
| 275 | ? `Hecho. (Acciones: ${allActions.map(a => a.tool).join(', ')})` |
| 276 | : '(sin respuesta del modelo — vuelve a probar)'); |
| 277 | const finalMessages = [ |
| 278 | ...messages, |
| 279 | { role: 'assistant', content: reply, actions: allActions.length ? allActions : undefined }, |
| 280 | ]; |
| 281 | const sessionId = providedId || sessions.newId(); |
| 282 | sessions.saveSession({ id: sessionId, userId, messages: finalMessages }); |
| 283 | |
| 284 | res.json({ sessionId, reply, actions: allActions, finishReason: finalReason }); |
| 285 | } catch (e) { |
| 286 | console.error('[chat] error:', e.message); |
| 287 | res.status(500).json({ error: e.message }); |
| 288 | } |
| 289 | }); |
| 290 | |
| 291 | module.exports = router; |