Elffuss BraidHub

kikocis/clonagent public

main · 20.3 KiBRawPermalink
1// Read/write Claude Code skills under ~/.claude/skills/<id>/
2// Each ClonAgent is a skill folder with SKILL.md, gmail_client.py, config.json,
3// credentials.json (user-supplied), token.json (after OAuth), .versions/ (history).
4const fs = require('fs');
5const path = require('path');
6const os = require('os');
7
8const SKILLS_ROOT = path.join(os.homedir(), '.claude', 'skills');
9const TEMPLATES_ROOT = path.resolve(__dirname, '..', '..', 'templates');
10const DATA_DIR = path.resolve(__dirname, '..', 'data');
11const REGISTRY_FILE = path.join(DATA_DIR, 'agents.json');
12
13const VERSIONABLE_FILES = ['SKILL.md', 'config.json', 'gmail_client.py'];
14
15function ensureDataDir() {
16 if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
17 if (!fs.existsSync(REGISTRY_FILE)) fs.writeFileSync(REGISTRY_FILE, '[]');
18}
19
20function readRegistry() {
21 ensureDataDir();
22 try { return JSON.parse(fs.readFileSync(REGISTRY_FILE, 'utf8')); }
23 catch { return []; }
24}
25
26function writeRegistry(list) {
27 ensureDataDir();
28 fs.writeFileSync(REGISTRY_FILE, JSON.stringify(list, null, 2));
29}
30
31function listAgents() {
32 return readRegistry().map(a => {
33 const dir = path.join(SKILLS_ROOT, a.id);
34 const hasGmailCreds = fs.existsSync(path.join(dir, 'credentials.json'));
35 const hasGmailToken = fs.existsSync(path.join(dir, 'token.json'));
36 const hasImapCreds = fs.existsSync(path.join(dir, 'imap-credentials.json'));
37 const provider = a.mailProvider || 'gmail';
38 const ready = provider === 'imap' ? hasImapCreds : (hasGmailCreds && hasGmailToken);
39 return {
40 ...a,
41 authorizedSenders: normalizeSenders(a.authorizedSenders),
42 skillPath: dir,
43 hasCredentials: hasGmailCreds,
44 hasToken: hasGmailToken,
45 hasImapCredentials: hasImapCreds,
46 ready,
47 };
48 });
49}
50
51// Walk ~/.claude/skills/ for any folder containing a ClonAgent-style config.json
52// and reconcile with the registry. Skills that exist on disk but not in the
53// registry are added; skills in the registry without a folder are left as-is
54// (they may be in mid-creation). Returns a list of changes.
55// Files that should be kept in sync with the latest template (script logic
56// upgrades shouldn't require recreating the agent).
57const TEMPLATE_TRACKED = ['mail_client.py', 'gmail_client.py', 'requirements.txt'];
58
59function refreshSkillScripts(skillId) {
60 const skillDir = path.join(SKILLS_ROOT, skillId);
61 const cfgPath = path.join(skillDir, 'config.json');
62 if (!fs.existsSync(cfgPath)) return false;
63 let cfg; try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch { return false; }
64 const provider = cfg.mailProvider || ((cfg.botEmail || '').endsWith('@bot.utopiaia.com') ? 'imap' : 'gmail');
65 const tplDir = path.join(TEMPLATES_ROOT, provider === 'imap' ? 'email-triage-imap' : 'email-triage');
66 let updated = false;
67 for (const f of TEMPLATE_TRACKED) {
68 const src = path.join(tplDir, f);
69 if (!fs.existsSync(src)) continue;
70 const dst = path.join(skillDir, f);
71 const want = fs.readFileSync(src, 'utf8');
72 let cur = '';
73 try { cur = fs.readFileSync(dst, 'utf8'); } catch {}
74 if (cur !== want) { fs.writeFileSync(dst, want); updated = true; }
75 }
76 return updated;
77}
78
79// Backfill missing IMAP fields in any skill's config.json + refresh tracked
80// scripts from templates so old skills get logic upgrades. Idempotent.
81function repairConfigs() {
82 if (!fs.existsSync(SKILLS_ROOT)) return [];
83 const repaired = [];
84 for (const entry of fs.readdirSync(SKILLS_ROOT, { withFileTypes: true })) {
85 if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
86 const cfgPath = path.join(SKILLS_ROOT, entry.name, 'config.json');
87 if (!fs.existsSync(cfgPath)) continue;
88 let cfg; try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch { continue; }
89 let dirty = false;
90 if (cfg.mailProvider === 'imap' || (cfg.botEmail || '').endsWith('@bot.utopiaia.com')) {
91 if (!cfg.mailProvider) { cfg.mailProvider = 'imap'; dirty = true; }
92 if (!cfg.imapHost) { cfg.imapHost = 'bot.utopiaia.com'; dirty = true; }
93 if (!cfg.imapPort) { cfg.imapPort = 993; dirty = true; }
94 if (cfg.imapSsl == null){ cfg.imapSsl = true; dirty = true; }
95 if (!cfg.smtpHost) { cfg.smtpHost = 'bot.utopiaia.com'; dirty = true; }
96 if (!cfg.smtpPort) { cfg.smtpPort = 587; dirty = true; }
97 if (cfg.smtpSsl == null){ cfg.smtpSsl = false; dirty = true; }
98 }
99 if (dirty) fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
100 const scriptsUpdated = refreshSkillScripts(entry.name);
101 if (dirty || scriptsUpdated) repaired.push(entry.name);
102 }
103 return repaired;
104}
105
106function discoverAgents() {
107 if (!fs.existsSync(SKILLS_ROOT)) return [];
108 const reg = readRegistry();
109 const known = new Set(reg.map(a => a.id));
110 const added = [];
111
112 for (const entry of fs.readdirSync(SKILLS_ROOT, { withFileTypes: true })) {
113 if (!entry.isDirectory()) continue;
114 if (entry.name.startsWith('.')) continue;
115 const cfgPath = path.join(SKILLS_ROOT, entry.name, 'config.json');
116 if (!fs.existsSync(cfgPath)) continue;
117 let cfg;
118 try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch { continue; }
119 if (!cfg.id || !cfg.botEmail) continue;
120 if (known.has(cfg.id)) continue;
121 const stat = fs.statSync(cfgPath);
122 reg.push({
123 id: cfg.id,
124 name: cfg.name || cfg.id,
125 description: cfg.description || '',
126 botEmail: cfg.botEmail,
127 authorizedSenders: cfg.authorizedSenders || [],
128 projectPath: cfg.projectPath || '',
129 deployHost: cfg.deployHost || '',
130 deployUser: cfg.deployUser || '',
131 deployDir: cfg.deployDir || '',
132 sshKey: cfg.sshKey || '',
133 mailProvider: cfg.mailProvider || 'gmail',
134 enabled: false,
135 pollMinutes: cfg.pollMinutes || 1,
136 version: cfg.version || 1,
137 createdAt: stat.birthtime?.toISOString() || new Date().toISOString(),
138 updatedAt: stat.mtime?.toISOString() || new Date().toISOString(),
139 imapHost: cfg.imapHost,
140 imapPort: cfg.imapPort,
141 imapSsl: cfg.imapSsl,
142 smtpHost: cfg.smtpHost,
143 smtpPort: cfg.smtpPort,
144 smtpSsl: cfg.smtpSsl,
145 });
146 added.push(cfg.id);
147 }
148 if (added.length) writeRegistry(reg);
149 return added;
150}
151
152function getAgent(id) {
153 const agents = listAgents();
154 return agents.find(a => a.id === id) || null;
155}
156
157function renderTemplate(str, vars) {
158 return str.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => {
159 const v = vars[k];
160 if (Array.isArray(v)) return JSON.stringify(v);
161 return v == null ? '' : String(v);
162 });
163}
164
165// ─── Versioning ────────────────────────────────────────────────────────────
166// Every create/update snapshots the skill folder into .versions/v<N>/.
167// Each version is an immutable folder copy of the relevant files.
168// .versions/index.json keeps metadata (version, createdAt, reason).
169
170function versionsDir(id) { return path.join(SKILLS_ROOT, id, '.versions'); }
171function versionsIndex(id) { return path.join(versionsDir(id), 'index.json'); }
172
173function readVersionsIndex(id) {
174 const p = versionsIndex(id);
175 if (!fs.existsSync(p)) return [];
176 try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return []; }
177}
178
179function writeVersionsIndex(id, list) {
180 fs.mkdirSync(versionsDir(id), { recursive: true });
181 fs.writeFileSync(versionsIndex(id), JSON.stringify(list, null, 2));
182}
183
184function nextVersionNumber(id) {
185 const idx = readVersionsIndex(id);
186 return idx.length === 0 ? 1 : idx[idx.length - 1].version + 1;
187}
188
189function snapshotVersion(id, reason = 'edit') {
190 const skillDir = path.join(SKILLS_ROOT, id);
191 if (!fs.existsSync(skillDir)) return null;
192 const v = nextVersionNumber(id);
193 const dst = path.join(versionsDir(id), `v${v}`);
194 fs.mkdirSync(dst, { recursive: true });
195 for (const f of VERSIONABLE_FILES) {
196 const src = path.join(skillDir, f);
197 if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
198 }
199 const meta = {
200 version: v,
201 createdAt: new Date().toISOString(),
202 reason,
203 files: VERSIONABLE_FILES.filter(f => fs.existsSync(path.join(dst, f))),
204 };
205 const idx = readVersionsIndex(id);
206 idx.push(meta);
207 writeVersionsIndex(id, idx);
208 return meta;
209}
210
211function listVersions(id) {
212 return readVersionsIndex(id);
213}
214
215function rollbackVersion(id, targetVersion) {
216 const skillDir = path.join(SKILLS_ROOT, id);
217 const src = path.join(versionsDir(id), `v${targetVersion}`);
218 if (!fs.existsSync(src)) throw new Error(`version ${targetVersion} not found for ${id}`);
219 // Snapshot current state first as a "pre-rollback" version
220 snapshotVersion(id, `pre-rollback-to-v${targetVersion}`);
221 for (const f of fs.readdirSync(src)) {
222 fs.copyFileSync(path.join(src, f), path.join(skillDir, f));
223 }
224 // After rollback re-sync registry from config.json
225 const cfgPath = path.join(skillDir, 'config.json');
226 if (fs.existsSync(cfgPath)) {
227 const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
228 const reg = readRegistry();
229 const i = reg.findIndex(a => a.id === id);
230 if (i >= 0) {
231 reg[i] = {
232 ...reg[i],
233 ...cfg,
234 version: nextVersionNumber(id) - 1, // we just snapshotted
235 updatedAt: new Date().toISOString(),
236 };
237 writeRegistry(reg);
238 }
239 }
240 return snapshotVersion(id, `rollback-to-v${targetVersion}`);
241}
242
243// ─── CRUD ──────────────────────────────────────────────────────────────────
244
245async function createAgent(spec) {
246 // Auto-provision a mailbox in our docker-mailserver if mailProvider='imap'
247 // and the user hasn't explicitly disabled it. Default mailProvider when
248 // unspecified: 'imap' if the mail server is reachable, else 'gmail'.
249 const mail = require('./mail-server');
250 if (!spec.mailProvider) {
251 spec.mailProvider = (await mail.isAvailable()) ? 'imap' : 'gmail';
252 }
253 let provisionedPassword = null;
254 if (spec.mailProvider === 'imap' && spec.autoProvisionMailbox !== false) {
255 if (!(await mail.isAvailable())) throw new Error('mail server not available — run scripts/setup-mailserver.sh first');
256 const email = spec.botEmail && spec.botEmail.includes('@') ? spec.botEmail : mail.suggestEmailFor(spec.id);
257 provisionedPassword = require('crypto').randomBytes(16).toString('base64').replace(/[+/=]/g, '');
258 try { await mail.addMailbox(email, provisionedPassword); }
259 catch (e) {
260 // If the mailbox already exists treat as soft-fail and reuse without overwriting password
261 if (!/already exists|exists/i.test(e.message)) throw e;
262 provisionedPassword = null;
263 }
264 spec = {
265 ...spec,
266 botEmail: email,
267 imapHost: mail.DOMAIN, imapPort: 993, imapSsl: true,
268 smtpHost: mail.DOMAIN, smtpPort: 587, smtpSsl: false,
269 };
270 }
271
272 const errs = validateSpec(spec);
273 if (errs.length) throw new Error(`invalid spec: ${errs.join('; ')}`);
274
275 const reg = readRegistry();
276 if (reg.some(a => a.id === spec.id)) throw new Error(`agent '${spec.id}' already exists`);
277
278 const skillDir = path.join(SKILLS_ROOT, spec.id);
279 if (fs.existsSync(skillDir)) throw new Error(`skill folder ${skillDir} already exists`);
280 fs.mkdirSync(skillDir, { recursive: true });
281
282 // Pick template based on mail provider
283 const provider = spec.mailProvider || 'gmail';
284 const tplName = provider === 'imap' ? 'email-triage-imap' : 'email-triage';
285 const tplDir = path.join(TEMPLATES_ROOT, tplName);
286 for (const f of fs.readdirSync(tplDir)) {
287 const src = path.join(tplDir, f);
288 const dst = path.join(skillDir, f.replace(/\.template$/, ''));
289 const raw = fs.readFileSync(src, 'utf8');
290 const rendered = renderTemplate(raw, {
291 ID: spec.id,
292 NAME: spec.name,
293 DESCRIPTION: spec.description || '',
294 BOT_EMAIL: spec.botEmail,
295 AUTHORIZED_SENDERS: spec.authorizedSenders,
296 AUTHORIZED_SENDERS_PYLIST: spec.authorizedSenders.map(s => ` '${s}',`).join('\n'),
297 PROJECT_PATH: spec.projectPath || '',
298 DEPLOY_HOST: spec.deployHost || '',
299 DEPLOY_USER: spec.deployUser || '',
300 DEPLOY_DIR: spec.deployDir || '',
301 SSH_KEY: spec.sshKey || '',
302 EXTRA_CONTEXT: spec.extraContext || '',
303 VERSION: 'v1',
304 PUBLIC_URL: process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com',
305 // IMAP fields (only used by email-triage-imap template)
306 IMAP_HOST: spec.imapHost || (provider === 'imap' ? extractMailHost(spec.botEmail) : ''),
307 IMAP_PORT: spec.imapPort || 993,
308 SMTP_HOST: spec.smtpHost || (provider === 'imap' ? extractMailHost(spec.botEmail) : ''),
309 SMTP_PORT: spec.smtpPort || 587,
310 });
311 fs.writeFileSync(dst, rendered);
312 }
313
314 const cfg = {
315 id: spec.id, name: spec.name,
316 botEmail: spec.botEmail, authorizedSenders: spec.authorizedSenders,
317 projectPath: spec.projectPath, deployHost: spec.deployHost,
318 deployUser: spec.deployUser, deployDir: spec.deployDir,
319 sshKey: spec.sshKey,
320 mailProvider: provider,
321 version: 1,
322 publicUrl: process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com',
323 };
324 if (provider === 'imap') {
325 cfg.imapHost = spec.imapHost || extractMailHost(spec.botEmail);
326 cfg.imapPort = spec.imapPort || 993;
327 cfg.imapSsl = spec.imapSsl ?? true;
328 cfg.smtpHost = spec.smtpHost || extractMailHost(spec.botEmail);
329 cfg.smtpPort = spec.smtpPort || 587;
330 cfg.smtpSsl = spec.smtpSsl ?? false;
331 }
332 fs.writeFileSync(path.join(skillDir, 'config.json'), JSON.stringify(cfg, null, 2));
333
334 const entry = {
335 id: spec.id, name: spec.name,
336 description: spec.description || '',
337 botEmail: spec.botEmail, authorizedSenders: spec.authorizedSenders,
338 projectPath: spec.projectPath, deployHost: spec.deployHost,
339 deployUser: spec.deployUser, deployDir: spec.deployDir, sshKey: spec.sshKey,
340 mailProvider: provider,
341 imapHost: spec.imapHost, imapPort: spec.imapPort, imapSsl: spec.imapSsl,
342 smtpHost: spec.smtpHost, smtpPort: spec.smtpPort, smtpSsl: spec.smtpSsl,
343 enabled: false,
344 pollMinutes: spec.pollMinutes || 1,
345 version: 1,
346 createdAt: new Date().toISOString(),
347 updatedAt: new Date().toISOString(),
348 };
349 reg.push(entry);
350 writeRegistry(reg);
351
352 // Drop the IMAP password into the skill folder (mode 600) so mail_client.py
353 // can use it. Never include it in the API response.
354 if (provisionedPassword) {
355 const credPath = path.join(skillDir, 'imap-credentials.json');
356 fs.writeFileSync(credPath, JSON.stringify({ password: provisionedPassword }, null, 2));
357 try { fs.chmodSync(credPath, 0o600); } catch {}
358 }
359
360 snapshotVersion(spec.id, 'create');
361 return entry;
362}
363
364function updateAgent(id, patch) {
365 const reg = readRegistry();
366 const i = reg.findIndex(a => a.id === id);
367 if (i < 0) throw new Error(`agent '${id}' not found`);
368
369 const prev = reg[i];
370 const newVersion = (prev.version || 1) + 1;
371 if (patch.authorizedSenders) patch.authorizedSenders = normalizeSenders(patch.authorizedSenders);
372 const next = { ...prev, ...patch, id, version: newVersion, updatedAt: new Date().toISOString() };
373 reg[i] = next;
374 writeRegistry(reg);
375
376 // Rewrite config.json + re-render SKILL.md (using the right template per provider)
377 const skillDir = path.join(SKILLS_ROOT, id);
378 if (fs.existsSync(skillDir)) {
379 const provider = next.mailProvider || 'gmail';
380 const cfg = {
381 id: next.id, name: next.name,
382 botEmail: next.botEmail, authorizedSenders: next.authorizedSenders,
383 projectPath: next.projectPath, deployHost: next.deployHost,
384 deployUser: next.deployUser, deployDir: next.deployDir, sshKey: next.sshKey,
385 mailProvider: provider,
386 version: newVersion,
387 spendingLimitMonthly: next.spendingLimitMonthly ?? null,
388 publicUrl: process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com',
389 };
390 if (provider === 'imap') {
391 cfg.imapHost = next.imapHost || 'bot.utopiaia.com';
392 cfg.imapPort = next.imapPort || 993;
393 cfg.imapSsl = next.imapSsl ?? true;
394 cfg.smtpHost = next.smtpHost || 'bot.utopiaia.com';
395 cfg.smtpPort = next.smtpPort || 587;
396 cfg.smtpSsl = next.smtpSsl ?? false;
397 }
398 fs.writeFileSync(path.join(skillDir, 'config.json'), JSON.stringify(cfg, null, 2));
399
400 const tplName = provider === 'imap' ? 'email-triage-imap' : 'email-triage';
401 const tplPath = path.join(TEMPLATES_ROOT, tplName, 'SKILL.md');
402 if (fs.existsSync(tplPath)) {
403 const rendered = renderTemplate(fs.readFileSync(tplPath, 'utf8'), {
404 ID: next.id,
405 NAME: next.name,
406 DESCRIPTION: next.description || '',
407 BOT_EMAIL: next.botEmail,
408 AUTHORIZED_SENDERS: next.authorizedSenders,
409 PROJECT_PATH: next.projectPath || '',
410 DEPLOY_HOST: next.deployHost || '',
411 DEPLOY_USER: next.deployUser || '',
412 DEPLOY_DIR: next.deployDir || '',
413 SSH_KEY: next.sshKey || '',
414 EXTRA_CONTEXT: next.extraContext || '',
415 VERSION: `v${newVersion}`,
416 PUBLIC_URL: process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com',
417 IMAP_HOST: cfg.imapHost || '',
418 IMAP_PORT: cfg.imapPort || '',
419 SMTP_HOST: cfg.smtpHost || '',
420 SMTP_PORT: cfg.smtpPort || '',
421 });
422 fs.writeFileSync(path.join(skillDir, 'SKILL.md'), rendered);
423 }
424 }
425
426 const reason = patch.enabled !== undefined && Object.keys(patch).length === 1
427 ? `toggle ${patch.enabled ? 'on' : 'off'}`
428 : 'edit';
429 snapshotVersion(id, reason);
430 return next;
431}
432
433async function deleteAgent(id, { removeSkill = false, removeMailbox = false } = {}) {
434 const reg = readRegistry();
435 const target = reg.find(a => a.id === id);
436 if (!target) throw new Error(`agent '${id}' not found`);
437 const next = reg.filter(a => a.id !== id);
438 writeRegistry(next);
439
440 // Best-effort: remove the docker-mailserver mailbox so the address is freed
441 if (removeMailbox && target.mailProvider === 'imap' && target.botEmail) {
442 try {
443 const mail = require('./mail-server');
444 if (await mail.isAvailable()) await mail.deleteMailbox(target.botEmail);
445 } catch (e) { /* swallow — best-effort */ }
446 }
447 if (removeSkill) {
448 const skillDir = path.join(SKILLS_ROOT, id);
449 if (fs.existsSync(skillDir)) fs.rmSync(skillDir, { recursive: true, force: true });
450 }
451}
452
453function readSkillFile(id, file) {
454 const p = path.join(SKILLS_ROOT, id, file);
455 if (!fs.existsSync(p)) return null;
456 return fs.readFileSync(p, 'utf8');
457}
458
459function writeSkillFile(id, file, content) {
460 const skillDir = path.join(SKILLS_ROOT, id);
461 if (!fs.existsSync(skillDir)) throw new Error(`skill ${id} does not exist`);
462 fs.writeFileSync(path.join(skillDir, file), content);
463 if (VERSIONABLE_FILES.includes(file)) snapshotVersion(id, `manual-edit:${file}`);
464}
465
466function extractMailHost(email) {
467 const dom = (email || '').split('@')[1] || '';
468 return dom ? `mail.${dom}` : '';
469}
470
471// Sender roles:
472// owner — created the agent. Can edit behavior, add/remove senders, delete.
473// cocreator — can edit behavior (rulebooks, config, deploys) but not sender list.
474// reader — can only use the agent's skills via email; agent rejects any
475// request that would modify its behavior or configuration.
476const ROLES = ['owner', 'cocreator', 'reader'];
477
478function normalizeSenders(senders) {
479 if (!Array.isArray(senders)) return [];
480 return senders.map((s, i) => {
481 if (typeof s === 'string') return { email: s.toLowerCase(), role: i === 0 ? 'owner' : 'reader' };
482 if (s && typeof s === 'object' && s.email) {
483 const role = ROLES.includes(s.role) ? s.role : 'reader';
484 return { email: String(s.email).toLowerCase(), role };
485 }
486 return null;
487 }).filter(Boolean);
488}
489
490function validateSpec(s) {
491 const e = [];
492 if (!s.id || !/^[a-z0-9-]+$/.test(s.id)) e.push('id must be lowercase-kebab');
493 if (!s.name) e.push('name required');
494 if (!s.botEmail || !/.+@.+/.test(s.botEmail)) e.push('botEmail invalid');
495 const senders = normalizeSenders(s.authorizedSenders);
496 if (senders.length === 0) e.push('authorizedSenders must be a non-empty array');
497 s.authorizedSenders = senders; // mutate to canonical form
498 return e;
499}
500
501module.exports = {
502 SKILLS_ROOT,
503 listAgents, getAgent, createAgent, updateAgent, deleteAgent,
504 readSkillFile, writeSkillFile, validateSpec,
505 listVersions, rollbackVersion, snapshotVersion,
506 discoverAgents, repairConfigs, refreshSkillScripts,
507};