Elffuss BraidHub

kikocis/clonagent public

main · 9.3 KiBRawPermalink
1// Calls the host-relay to launch Claude CLI sessions.
2// Two named roles per agent: 'scheduler' (fires on new email) and
3// 'executor' (fires when pending tasks exist). Never more than one
4// session of each role at a time.
5const path = require('path');
6const os = require('os');
7const fs = require('fs');
8const { mcpPath } = require('./mcp-fs');
9const agentSessions = require('./agent-sessions');
10const taskQueue = require('./task-queue');
11
12const RELAY_URL = process.env.AGENT_RELAY_URL || process.env.LITELLM_URL || 'http://localhost:3202';
13const PUBLIC_URL = (process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com').replace(/\/$/, '');
14const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15const SESSIONS_FILE = path.resolve(__dirname, '..', 'data', 'activity-sessions.json');
16const SPEND_CACHE_TTL = 60_000;
17const _spendCache = new Map(); // agentId -> { value, expiresAt }
18
19async function getMonthlySpend(agentId) {
20 const now = Date.now();
21 const hit = _spendCache.get(agentId);
22 if (hit && hit.expiresAt > now) return hit.value;
23
24 try {
25 const data = await fs.promises.readFile(SESSIONS_FILE, 'utf8');
26 const sessions = JSON.parse(data);
27 const monthStart = new Date();
28 monthStart.setDate(1); monthStart.setHours(0, 0, 0, 0);
29 const ms = monthStart.toISOString();
30 const value = sessions
31 .filter(s => (s.agentId || s.agent_id) === agentId && s.created_at >= ms && s.cost_usd > 0)
32 .reduce((t, s) => t + (s.cost_usd || 0), 0);
33 _spendCache.set(agentId, { value, expiresAt: now + SPEND_CACHE_TTL });
34 return value;
35 } catch { return 0; }
36}
37
38function newUuid() {
39 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
40 const r = Math.random() * 16 | 0;
41 return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
42 });
43}
44
45// ── Core launch helper ─────────────────────────────────────────────────────
46
47const DEFAULT_MODEL = 'claude-sonnet-4-6';
48
49async function _launch({ skillId, role, prompt, description, resumeClaudeId, model }) {
50 const skillDir = path.join(os.homedir(), '.claude', 'skills', skillId);
51 const sessionId = newUuid();
52 const mcp = mcpPath(skillId);
53 const resolvedModel = model || DEFAULT_MODEL;
54
55 // Register session with activity API
56 await fetch(`${PUBLIC_URL}/api/activity/sessions`, {
57 method: 'POST',
58 headers: { 'Content-Type': 'application/json' },
59 body: JSON.stringify({ id: sessionId, agentId: skillId, task: prompt,
60 description: `[${role}] ${description || prompt.slice(0, 60)}`, status: 'running' }),
61 }).catch(() => {});
62
63 const args = [
64 '--output-format', 'stream-json', '--verbose',
65 '--dangerously-skip-permissions',
66 '--model', resolvedModel,
67 ];
68 if (resumeClaudeId && UUID_RE.test(resumeClaudeId)) args.push('--resume', resumeClaudeId);
69 args.push('-p', `/${skillId}\n\n${prompt}`);
70 if (fs.existsSync(mcp)) args.push('--mcp-config', mcp);
71
72 const resp = await fetch(`${RELAY_URL}/run`, {
73 method: 'POST',
74 headers: { 'Content-Type': 'application/json' },
75 body: JSON.stringify({ sessionId, task: prompt, workdir: skillDir,
76 model: resolvedModel, args }),
77 });
78 if (!resp.ok) throw new Error(`relay ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
79
80 // Save the relay sessionId so activity.js can link it to the Claude UUID on init event
81 agentSessions.set(skillId, { [`${role}RelayId`]: sessionId });
82 agentSessions.setActive(skillId, role, true);
83
84 return { sessionId };
85}
86
87// ── Scheduler — fires on new email ────────────────────────────────────────
88// Reads the email, plans tasks, writes agent-tasks.json, exits.
89
90async function launchScheduler(agent, { from, subject, threadId }) {
91 const skillId = agent.id;
92 if (agentSessions.isActive(skillId, 'scheduler')) {
93 console.log(`[runner] ${skillId}: scheduler already active, skipping`);
94 return null;
95 }
96 if (agent.spendingLimitMonthly != null) {
97 const spent = getMonthlySpend(skillId);
98 if (spent >= agent.spendingLimitMonthly) {
99 console.warn(`[runner] ${skillId}: monthly limit $${agent.spendingLimitMonthly} reached (spent $${spent.toFixed(4)}) — launch blocked`);
100 return null;
101 }
102 }
103
104 const sess = agentSessions.get(skillId);
105 const resumeClaudeId = sess.schedulerClaudeId || null;
106 const tasksFile = taskQueue.filePath(skillId);
107
108 const prompt = `ROL: PLANIFICADOR
109
110Nueva comunicación recibida:
111 De: ${from}
112 Asunto: ${subject}
113 ThreadId: ${threadId}
114
115Tu tarea (sé rápido y concreto):
1161. Lee el email: python3 mail_client.py get-thread "${threadId}"
1172. Lee el fichero de tareas actual: cat agent-tasks.json (puede no existir aún)
1183. Añade las tareas necesarias a agent-tasks.json en formato JSON:
119 { "id": "<uuid4>", "title": "...", "description": "...", "priority": 1,
120 "status": "pending", "threadId": "${threadId}", "from": "${from}",
121 "createdAt": "<iso>" }
122 - priority 1=urgente, 2=normal, 3=baja
123 - No dupliques tareas ya existentes para el mismo threadId
1244. Actualiza el campo "plan" con tu análisis breve de la situación
1255. Escribe el fichero actualizado. El ejecutor se encarga de ejecutar las tareas.
1266. Sal cuando hayas terminado de planificar.
127
128Fichero de tareas: ${tasksFile}`;
129
130 try {
131 const launch = await _launch({ skillId, role: 'scheduler', prompt,
132 description: subject, resumeClaudeId, model: agent.model });
133 console.log(`[runner] ${skillId}: scheduler launched session=${launch.sessionId}`);
134 return launch;
135 } catch (err) {
136 agentSessions.setActive(skillId, 'scheduler', false);
137 throw err;
138 }
139}
140
141// ── Executor — fires when pending tasks exist ──────────────────────────────
142// Executes all pending tasks in order, updates statuses, exits when queue empty.
143
144async function launchExecutor(agent) {
145 const skillId = agent.id;
146 if (agentSessions.isActive(skillId, 'executor')) {
147 console.log(`[runner] ${skillId}: executor already active, skipping`);
148 return null;
149 }
150 if (agent.spendingLimitMonthly != null) {
151 const spent = getMonthlySpend(skillId);
152 if (spent >= agent.spendingLimitMonthly) {
153 console.warn(`[runner] ${skillId}: monthly limit $${agent.spendingLimitMonthly} reached (spent $${spent.toFixed(4)}) — executor blocked`);
154 return null;
155 }
156 }
157 if (!taskQueue.hasPending(skillId)) return null;
158
159 const sess = agentSessions.get(skillId);
160 const resumeClaudeId = sess.executorClaudeId || null;
161 const tasksFile = taskQueue.filePath(skillId);
162
163 const prompt = `ROL: EJECUTOR
164
165Ejecuta las tareas pendientes de agent-tasks.json.
166
167Proceso (repite hasta que no haya más tareas pendientes):
1681. Lee agent-tasks.json
1692. Toma la tarea con status="pending" de mayor prioridad (1=urgente)
1703. Actualiza su status a "in-progress" en el fichero
1714. Ejecuta la tarea (responder emails, analizar datos, lo que corresponda)
1725. Actualiza la tarea: status="done" o "failed", result="descripción breve", updatedAt=<iso>
1736. Si quedan más tareas pending, vuelve al paso 1
1747. Cuando no haya ninguna tarea pending, sal
175
176Reglas:
177- Marca "failed" (no crashees) si algo falla, y continúa con la siguiente
178- Usa mail_client.py para enviar respuestas de email
179- Sé conciso en los campos "result"
180
181Fichero de tareas: ${tasksFile}`;
182
183 try {
184 const launch = await _launch({ skillId, role: 'executor', prompt,
185 description: 'proceso cola de tareas', resumeClaudeId, model: agent.model });
186 console.log(`[runner] ${skillId}: executor launched session=${launch.sessionId}`);
187 return launch;
188 } catch (err) {
189 agentSessions.setActive(skillId, 'executor', false);
190 throw err;
191 }
192}
193
194// ── Legacy helper (used by chat.js / task injection) ──────────────────────
195
196async function launchAgent({ skillId, prompt, cwd, threadInfo, resumeSessionId }) {
197 const skillDir = cwd || path.join(os.homedir(), '.claude', 'skills', skillId);
198 const sessionId = newUuid();
199 const mcp = mcpPath(skillId);
200
201 await fetch(`${PUBLIC_URL}/api/activity/sessions`, {
202 method: 'POST',
203 headers: { 'Content-Type': 'application/json' },
204 body: JSON.stringify({ id: sessionId, agentId: skillId, task: prompt,
205 description: threadInfo?.subject || prompt.slice(0, 80), status: 'running' }),
206 }).catch(() => {});
207
208 const args = [
209 '--output-format', 'stream-json', '--verbose',
210 '--dangerously-skip-permissions', '--model', 'claude-sonnet-4-6',
211 ];
212 if (resumeSessionId && UUID_RE.test(resumeSessionId)) args.push('--resume', resumeSessionId);
213 args.push('-p', `/${skillId}\n\n${prompt}`);
214 if (fs.existsSync(mcp)) args.push('--mcp-config', mcp);
215
216 const resp = await fetch(`${RELAY_URL}/run`, {
217 method: 'POST',
218 headers: { 'Content-Type': 'application/json' },
219 body: JSON.stringify({ sessionId, task: prompt, workdir: skillDir,
220 model: 'claude-sonnet-4-6', args }),
221 });
222 if (!resp.ok) throw new Error(`relay ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
223 return { ...(await resp.json()), sessionId };
224}
225
226async function relayHealthy() {
227 try {
228 const r = await fetch(`${RELAY_URL}/health`, { signal: AbortSignal.timeout(2000) });
229 return r.ok;
230 } catch { return false; }
231}
232
233module.exports = { launchAgent, launchScheduler, launchExecutor, relayHealthy, RELAY_URL };