Elffuss BraidHub

utopia-ia/elffuss public

4e3eafecd7b2 · 6.8 KiBRawPermalink
1// Skills de Elffuss Code: instrucciones en markdown (formato SKILL.md de
2// Claude Code) que el modelo sigue cuando aplican. Se instalan desde el
3// catálogo grande OFICIAL (github.com/anthropics/skills), desde los plugins
4// oficiales, o desde CUALQUIER repo público (marketplaces de la comunidad
5// tipo OpenClaude/openclaw). Todo transparente: se ve el repo, la lista y el
6// SKILL.md que se inyecta. Se guardan en IndexedDB (nada sale del navegador).
7import * as db from './db.js';
8
9const KEY = 'skills'; // skills instaladas
10const SRC_KEY = 'skills.sources'; // repos personalizados añadidos por el usuario
11const MAX_SKILL = 12_000; // caracteres del cuerpo que se inyectan al modelo
12
13export const CATALOG_REPO = 'anthropics/skills';
14export const DEFAULT_SOURCES = [
15 { repo: 'bbgnsurftech/claude-skills-collection', label: 'Comunidad · Mega-colección (1000+ skills)', official: true },
16 { repo: 'anthropics/skills', label: 'Anthropic · Agent Skills (oficial de Claude Code)', official: true },
17 { repo: 'anthropics/claude-plugins-official', label: 'Anthropic · Claude Code Plugins (oficial)', official: true },
18];
19
20let cache = []; // instaladas, en memoria (para que el systemPrompt sea síncrono)
21
22export async function initSkills() {
23 cache = (await db.get('kv', KEY).catch(() => null)) || [];
24 return cache;
25}
26
27export async function all() { return cache; }
28export function installed() { return cache; }
29export function isInstalled(repo, path) { return cache.some(s => s.repo === repo && s.path === path); }
30
31export async function install(skill) {
32 cache = cache.filter(s => !(s.repo === skill.repo && s.path === skill.path) && s.name !== skill.name);
33 const entry = { ...skill, content: (skill.content || '').slice(0, MAX_SKILL) };
34 cache.push(entry);
35 await db.set('kv', KEY, cache);
36 return entry; // devuelve la skill completa (name, description…)
37}
38
39// Mensaje «cómo usarla» tras instalar: qué hace + un ejemplo de qué pedir.
40export function usageMessage(skill) {
41 const desc = (skill.description || '').trim();
42 const ejemplo = firstExample(skill) || `algo relacionado con «${skill.name}»`;
43 return `✳ **Skill «${skill.name}» instalada.**\n\n` +
44 (desc ? desc + '\n\n' : '') +
45 `Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:\n\n> ${ejemplo}`;
46}
47
48// Intenta sacar un ejemplo de uso del cuerpo del SKILL.md (líneas de ejemplo/uso).
49function firstExample(skill) {
50 const body = skill.content || '';
51 const m = body.match(/(?:ejemplo|example|uso|usage|prueba|try)[^\n:]*[::]\s*["“]?([^\n"”]{6,90})/i)
52 || body.match(/^[-*]\s+([A-ZÁÉÍÓÚ][^\n]{10,80})/m);
53 return m ? m[1].trim().replace(/[.*_`]+$/, '') : null;
54}
55
56export async function remove(nameOrPath) {
57 cache = cache.filter(s => s.name !== nameOrPath && s.path !== nameOrPath);
58 await db.set('kv', KEY, cache);
59}
60
61export async function get(name) {
62 return cache.find(s => s.name.toLowerCase() === String(name).toLowerCase()) || null;
63}
64
65// ---- fuentes (repos) ----
66export async function sources() {
67 const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || [];
68 return [...DEFAULT_SOURCES, ...custom];
69}
70export async function addSource(repoOrUrl, label) {
71 const repo = repoOrUrl.trim().replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
72 if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error('Usa owner/repo (o la URL de GitHub)');
73 const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || [];
74 if (!custom.some(s => s.repo === repo) && !DEFAULT_SOURCES.some(s => s.repo === repo))
75 custom.push({ repo, label: label || repo });
76 await db.set('kv', SRC_KEY, custom);
77 return repo;
78}
79export async function removeSource(repo) {
80 const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || [];
81 await db.set('kv', SRC_KEY, custom.filter(s => s.repo !== repo));
82}
83
84// ---- catálogo desde GitHub ----
85// Una sola llamada al árbol git del repo → todos los SKILL.md.
86export async function listFromRepo(repo) {
87 let tree, branch;
88 for (const b of ['main', 'master']) {
89 const r = await fetch(`https://api.github.com/repos/${repo}/git/trees/${b}?recursive=1`);
90 if (r.ok) { tree = await r.json(); branch = b; break; }
91 if (r.status === 403) throw new Error('GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.');
92 }
93 if (!tree) throw new Error('No pude leer el repo (¿existe y es público?)');
94 return (tree.tree || [])
95 .filter(n => /(^|\/)SKILL\.md$/i.test(n.path))
96 .map(n => ({ repo, branch, path: n.path, dir: n.path.replace(/\/SKILL\.md$/i, ''), name: n.path.replace(/\/SKILL\.md$/i, '').split('/').pop() || repo }))
97 .sort((a, b) => a.dir.localeCompare(b.dir));
98}
99
100// Descarga el SKILL.md y lo instala (frontmatter YAML simple).
101export async function installFromRepo(entry) {
102 let md = null;
103 for (const b of [entry.branch, 'main', 'master'].filter(Boolean)) {
104 const r = await fetch(`https://raw.githubusercontent.com/${entry.repo}/${b}/${entry.path}`);
105 if (r.ok) { md = await r.text(); break; }
106 }
107 if (md == null) throw new Error('No pude descargar el SKILL.md');
108 const skill = parseSkill(md, entry.name);
109 return install({ ...skill, repo: entry.repo, path: entry.path });
110}
111
112// SKILL.md → { name, description, content }
113export function parseSkill(md, fallbackName = 'skill') {
114 const fm = md.match(/^---\n([\s\S]*?)\n---/);
115 const meta = fm?.[1] || '';
116 const name = meta.match(/^name:\s*(.+)$/m)?.[1]?.trim() || fallbackName;
117 const description = (meta.match(/^description:\s*([\s\S]+?)(?:\n\w+:|$)/m)?.[1] || '').replace(/\s+/g, ' ').trim();
118 const content = md.replace(/^---\n[\s\S]*?\n---\n?/, '').trim();
119 return { name, description, content };
120}
121
122// Creador de skills: Elffuss fabrica una skill propia (SKILL.md) a partir de
123// lo que el usuario quiere, y la instala al instante. Aparece en la pestaña
124// Skills y se inyecta en el prompt de los siguientes turnos.
125export async function createSkill({ name, description, instructions } = {}) {
126 if (!name || !instructions) throw new Error('Faltan name o instructions');
127 const skill = {
128 name: String(name).slice(0, 48),
129 description: (description || '').slice(0, 240),
130 content: String(instructions).slice(0, MAX_SKILL),
131 repo: 'creada por Elffuss',
132 path: 'local/' + Date.now(),
133 };
134 await install(skill);
135 return `Skill «${skill.name}» creada e instalada. Ya la sigo en cada conversación (mírala en la pestaña Skills).`;
136}
137
138// Bloque para el systemPrompt (síncrono, desde la caché).
139export function skillsPromptBlock() {
140 if (!cache.length) return '';
141 const parts = cache.map(s =>
142 `### Skill «${s.name}»${s.repo ? ` (de ${s.repo})` : ''}\n${s.description || ''}\n${(s.content || '').slice(0, MAX_SKILL)}`);
143 return `\n\nSKILLS ACTIVAS (instrucciones especializadas; síguelas cuando la tarea encaje):\n${parts.join('\n\n')}`;
144}