From f6006681f10c58a12e555414cf0bac8fda7293c2 Mon Sep 17 00:00:00 2001 From: elffuss-bot Date: Thu, 1 Oct 2026 00:00:00 +0000 Subject: [PATCH] Stand-in import of elffuss/claw One parentless commit with only the files that the open seed tasks touch and the modules they import. The full squashed import (SPEC 8.6) is a later step: this tree is not the cutoff tree. T2T-StandIn-Source-Commit: 70b800e87ef05a9574bf2ae8226cef90015dbe21 --- LICENSE | 202 +++++++++++++++++++++++++++++++++++++++++ NOTICE | 5 + README.md | 3 + tests/README.md | 24 +++++ tests/harness/VERSION | 1 + web/js/db.js | 32 +++++++ web/js/runtime/caps.js | 112 +++++++++++++++++++++++ web/js/skills.js | 191 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 570 insertions(+) create mode 100644 LICENSE create mode 100644 NOTICE create mode 100644 README.md create mode 100644 tests/README.md create mode 100644 tests/harness/VERSION create mode 100644 web/js/db.js create mode 100644 web/js/runtime/caps.js create mode 100644 web/js/skills.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..10b0bd9 --- /dev/null +++ b/NOTICE @@ -0,0 +1,5 @@ +elffuss-claw +Copyright 2026 Kiko Cisneros + +This product includes software developed as part of the Elffuss project. +Licensed under the Apache License, Version 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5268a41 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# claw + +Stand-in of the claw repository for the public testnet of Elffuss Token to Token (T2T): only the files that some open task touches, and the modules they import. The full import is a later step. diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..0c1eed2 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,24 @@ +# Tests E2E de Elffuss + +```bash +python3 ../server/serve.py & # el dev server en :8642 +npm i # playwright +npm run e2e # casos de datos: Excel→gráfico y carpetas vigiladas +``` + +`e2e_datos.mjs` valida con el **modo básico** (determinista, sin GPU ni modelo): + +- **A · Excel → visualización**: siembra un `.xlsx` REAL (SheetJS) en una carpeta + autorizada, pide «visualiza ventas.xlsx» y comprueba que la cadena + `fs.read` (xlsx→CSV) → `app.create` renderiza una app de gráfico con la + columna correcta en el visualizador. Igual con CSV. +- **B · Automatización entre carpetas**: «pones un fichero en una carpeta y + Elffuss lo procesa y te lo deja en otra» — crea `fs.watch entrada→salida`, + deja DESPUÉS un `stock.xlsx` y un `nota.txt` en `entrada`, y comprueba que en + `salida` aparecen `stock.csv` (convertido) y `nota.txt` (copiado), con aviso + en el chat. También `fs.copy` one-shot con patrón (`*.txt` sí, `.md` no). + +Las carpetas del test son **OPFS** (los pickers nativos exigen gesto de +usuario); los handles se registran en el IndexedDB de Elffuss igual que los +reales. Esto valida la plataforma — la calidad del modelo se evalúa con los +casos de `../coordinacion/ERRORES.md`. diff --git a/tests/harness/VERSION b/tests/harness/VERSION new file mode 100644 index 0000000..3eefcb9 --- /dev/null +++ b/tests/harness/VERSION @@ -0,0 +1 @@ +1.0.0 diff --git a/web/js/db.js b/web/js/db.js new file mode 100644 index 0000000..2a4e417 --- /dev/null +++ b/web/js/db.js @@ -0,0 +1,32 @@ +// IndexedDB mínima: stores clave→valor. +const NAME = 'elffuss', VERSION = 2; +const STORES = ['kv', 'apps', 'tasks', 'vault', 'fs', 'memory']; +let dbPromise = null; + +function open() { + if (dbPromise) return dbPromise; + dbPromise = new Promise((resolve, reject) => { + const req = indexedDB.open(NAME, VERSION); + req.onupgradeneeded = () => { + for (const s of STORES) + if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + return dbPromise; +} + +function tx(store, mode, fn) { + return open().then(db => new Promise((resolve, reject) => { + const req = fn(db.transaction(store, mode).objectStore(store)); + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + })); +} + +export const get = (store, key) => tx(store, 'readonly', s => s.get(key)); +export const set = (store, key, val) => tx(store, 'readwrite', s => s.put(val, key)); +export const del = (store, key) => tx(store, 'readwrite', s => s.delete(key)); +export const keys = (store) => tx(store, 'readonly', s => s.getAllKeys()); +export const all = (store) => tx(store, 'readonly', s => s.getAll()); diff --git a/web/js/runtime/caps.js b/web/js/runtime/caps.js new file mode 100644 index 0000000..db6a3a7 --- /dev/null +++ b/web/js/runtime/caps.js @@ -0,0 +1,112 @@ +// Elffuss Runtime · sonda de capacidades del dispositivo. +// ───────────────────────────────────────────────────────────────────────────── +// PRIMER módulo de nuestro runtime propio. El nudo del problema «cargar modelos +// grandes» es saber QUÉ cabe en cada equipo: +// · Escritorio (GPU potente, RAM amplia): modelos grandes, pero hay que +// shardear los pesos porque WebGPU limita el tamaño de cada buffer. +// · Móvil: RAM total limitada y el navegador mata la pestaña por encima de +// ~1-2 GB → techo real ~1-2 GB por mucho que la GPU sea potente. +// Esta sonda reporta límites de WebGPU + memoria + un «presupuesto de modelo» +// realista por plataforma. La usan la selección de cerebro y el loader por shards. + +const GiB = 1024 ** 3; +const MiB = 1024 ** 2; + +// Detección de plataforma SIN depender de cadenas frágiles: primero el +// userAgentData estructurado, luego el userAgent como respaldo. Solo se lee el +// entorno del USUARIO para decidir qué correr (feature-detection), no se registra. +function detectPlatform() { + const uad = navigator.userAgentData; + const ua = navigator.userAgent || ''; + const touch = (navigator.maxTouchPoints || 0) > 1; + const iOS = /iPhone|iPad|iPod/i.test(ua) || + // iPad moderno se hace pasar por Mac: Mac + pantalla táctil = iPad. + (/Mac/i.test(ua) && touch); + const android = /Android/i.test(ua); + const mobile = !!(uad?.mobile) || iOS || android || + matchMedia('(max-width: 820px)').matches || matchMedia('(pointer: coarse)').matches; + const mac = /Mac/i.test(uad?.platform || ua) && !iOS; + return { mobile, iOS, android, mac, touch }; +} + +// Presupuesto de modelo realista (bytes de PESOS que el equipo puede sostener, +// dejando margen para activaciones + KV + el propio navegador). +// · iOS: el navegador revienta la pestaña sobre ~1.3 GB de datos vivos. +// · Android: variable; tiramos conservador. +// · Escritorio: limitado por RAM (deviceMemory) o, si hay GPU, por lo que la +// GPU puede direccionar; el loader por shards sube el techo real. +function modelBudget(platform, memGB) { + if (platform.iOS) return Math.round(1.3 * GiB); + if (platform.android) return Math.round(1.0 * GiB); + if (platform.mobile) return Math.round(1.0 * GiB); + // escritorio: ~60 % de la RAM declarada, tope de seguridad 12 GB + return Math.min(Math.round(memGB * 0.6 * GiB), 12 * GiB); +} + +// Tamaño máximo de un SHARD de pesos en la GPU: nunca puede exceder el binding +// de storage buffer del adaptador (a menudo 128 MiB–2 GiB). El loader partirá los +// tensores grandes en trozos de este tamaño. Se deja un pelín por debajo del +// límite para las estructuras auxiliares. +function shardCap(limits) { + const bind = limits?.maxStorageBufferBindingSize || 128 * MiB; + // usar como mucho el binding, y no más de 256 MiB por shard (equilibrio entre + // nº de bind groups y presión de memoria); mínimo 16 MiB. + return Math.max(16 * MiB, Math.min(bind, 256 * MiB)); +} + +export async function probe() { + const platform = detectPlatform(); + // deviceMemory viene redondeado (2,4,8…) y en móvil suele mentir a la baja; + // si no está, asumimos 4 en móvil y 8 en escritorio. + const memGB = navigator.deviceMemory || (platform.mobile ? 4 : 8); + + let gpu = false, limits = null, info = null, error = null; + if (navigator.gpu) { + try { + const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); + if (adapter) { + gpu = true; + const L = adapter.limits || {}; + limits = { + maxBufferSize: L.maxBufferSize || 0, + maxStorageBufferBindingSize: L.maxStorageBufferBindingSize || 0, + maxComputeWorkgroupStorageSize: L.maxComputeWorkgroupStorageSize || 0, + maxComputeInvocationsPerWorkgroup: L.maxComputeInvocationsPerWorkgroup || 0, + maxComputeWorkgroupSizeX: L.maxComputeWorkgroupSizeX || 0, + }; + // requestAdapterInfo está deprecándose a favor de adapter.info; probamos ambos. + try { info = adapter.info || (adapter.requestAdapterInfo ? await adapter.requestAdapterInfo() : null); } catch { /* opcional */ } + } else { + error = 'navigator.gpu existe pero no hay adaptador real'; + } + } catch (e) { error = String(e?.message || e); } + } else { + error = 'sin WebGPU'; + } + + const budget = modelBudget(platform, memGB); + return { + platform, + memGB, + gpu, + limits, + info, // {vendor, architecture, device, description} si el navegador lo da + error, + budgetBytes: budget, + budgetGiB: +(budget / GiB).toFixed(2), + shardCapBytes: shardCap(limits), + // ¿entra un modelo de N bytes de pesos? (el loader por shards salva el límite + // de buffer; el muro real es el presupuesto de memoria del equipo). + fits(weightBytes) { return gpu && weightBytes <= budget; }, + }; +} + +// Resumen legible de una línea para diagnóstico en la UI (sin datos sensibles). +export function summarize(c) { + const p = c.platform.iOS ? 'iOS' : c.platform.android ? 'Android' + : c.platform.mac ? 'Mac' : c.platform.mobile ? 'móvil' : 'escritorio'; + const g = c.gpu + ? `WebGPU · buffer≤${(c.limits.maxBufferSize / GiB).toFixed(1)}GiB · binding≤${(c.limits.maxStorageBufferBindingSize / MiB) | 0}MiB` + : `sin GPU (${c.error || '—'})`; + return `${p} · ~${c.memGB}GB RAM · presupuesto ${c.budgetGiB}GiB · ${g}`; +} diff --git a/web/js/skills.js b/web/js/skills.js new file mode 100644 index 0000000..b66f7da --- /dev/null +++ b/web/js/skills.js @@ -0,0 +1,191 @@ +// Skills de Elffuss Code: instrucciones en markdown (formato SKILL.md de +// Claude Code) que el modelo sigue cuando aplican. Se instalan desde el +// catálogo grande OFICIAL (github.com/anthropics/skills), desde los plugins +// oficiales, o desde CUALQUIER repo público (marketplaces de la comunidad +// tipo OpenClaude/openclaw). Todo transparente: se ve el repo, la lista y el +// SKILL.md que se inyecta. Se guardan en IndexedDB (nada sale del navegador). +import * as db from './db.js'; + +const KEY = 'skills'; // skills instaladas +const SRC_KEY = 'skills.sources'; // repos personalizados añadidos por el usuario +const MAX_SKILL = 12_000; // caracteres del cuerpo que se inyectan al modelo + +export const CATALOG_REPO = 'anthropics/skills'; +export const DEFAULT_SOURCES = [ + { repo: 'KikoCis/elffuss-claw-skills', label: 'Elffuss · Skills que funcionan en Claw (3D·Excel·web·juegos)', official: true }, + { repo: 'bbgnsurftech/claude-skills-collection', label: 'Comunidad · Mega-colección (1000+ skills)', official: true }, + { repo: 'anthropics/skills', label: 'Anthropic · Agent Skills (oficial de Claude Code)', official: true }, + { repo: 'anthropics/claude-plugins-official', label: 'Anthropic · Claude Code Plugins (oficial)', official: true }, + { repo: 'earthtojake/text-to-cad', label: 'Text-to-CAD · CAD/STEP/DXF (Python, solo referencia)', official: true }, + { repo: 'scottstts/Threejs-Awesome-Graphics-Agent-Skills', label: '3D en el navegador · Three.js (funciona en Claw)', official: true }, +]; + +let cache = []; // instaladas, en memoria (para que el systemPrompt sea síncrono) + +// `loaded` distingue «no hay skills» de «no se pudo leer»: si la lectura +// falla, cache queda vacío pero loaded=false, y install() se niega a persistir +// (antes, un fallo transitorio de IndexedDB borraba TODAS las skills al +// guardar la siguiente). +let loaded = false; +export async function initSkills() { + try { + const stored = await db.get('kv', KEY); + cache = Array.isArray(stored) ? stored : []; + loaded = true; + } catch (e) { + cache = []; + loaded = false; + console.warn('[elffuss] no se pudieron leer las skills; no las sobrescribiré', e); + } + return cache; +} +export function skillsLoaded() { return loaded; } + +export async function all() { return cache; } +export function installed() { return cache; } +export function isInstalled(repo, path) { return cache.some(s => s.repo === repo && s.path === path); } + +export async function install(skill) { + // Si la carga inicial falló, cache no representa lo instalado: reintentar + // leer antes de escribir. Sin esto, guardar aquí borraría las skills reales. + if (!loaded) { + await initSkills(); + if (!loaded) throw new Error('No pude leer tus skills guardadas; no instalo para no perderlas. Recarga la página e inténtalo otra vez.'); + } + cache = cache.filter(s => !(s.repo === skill.repo && s.path === skill.path) && s.name !== skill.name); + const entry = { ...skill, content: (skill.content || '').slice(0, MAX_SKILL) }; + cache.push(entry); + await db.set('kv', KEY, cache); + return entry; // devuelve la skill completa (name, description…) +} + +// Mensaje «cómo usarla» tras instalar: qué hace + un ejemplo de qué pedir. +export function usageMessage(skill) { + const desc = (skill.description || '').trim(); + const ejemplo = firstExample(skill) || `algo relacionado con «${skill.name}»`; + return `✳ **Skill «${skill.name}» instalada.**\n\n` + + (desc ? desc + '\n\n' : '') + + `Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:\n\n> ${ejemplo}`; +} + +// Intenta sacar un ejemplo de uso del cuerpo del SKILL.md (líneas de ejemplo/uso). +function firstExample(skill) { + const body = skill.content || ''; + const m = body.match(/(?:ejemplo|example|uso|usage|prueba|try)[^\n:]*[::]\s*["“]?([^\n"”]{6,90})/i) + || body.match(/^[-*]\s+([A-ZÁÉÍÓÚ][^\n]{10,80})/m); + return m ? m[1].trim().replace(/[.*_`]+$/, '') : null; +} + +export async function remove(nameOrPath) { + cache = cache.filter(s => s.name !== nameOrPath && s.path !== nameOrPath); + await db.set('kv', KEY, cache); +} + +export async function get(name) { + return cache.find(s => s.name.toLowerCase() === String(name).toLowerCase()) || null; +} + +// ---- fuentes (repos) ---- +export async function sources() { + const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || []; + return [...DEFAULT_SOURCES, ...custom]; +} +export async function addSource(repoOrUrl, label) { + const repo = repoOrUrl.trim().replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, ''); + if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error('Usa owner/repo (o la URL de GitHub)'); + const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || []; + if (!custom.some(s => s.repo === repo) && !DEFAULT_SOURCES.some(s => s.repo === repo)) + custom.push({ repo, label: label || repo }); + await db.set('kv', SRC_KEY, custom); + return repo; +} +export async function removeSource(repo) { + const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || []; + await db.set('kv', SRC_KEY, custom.filter(s => s.repo !== repo)); +} + +// ---- catálogo desde GitHub ---- +// Una sola llamada al árbol git del repo → todos los SKILL.md. +export async function listFromRepo(repo) { + let tree, branch; + for (const b of ['main', 'master']) { + const r = await fetch(`https://api.github.com/repos/${repo}/git/trees/${b}?recursive=1`); + if (r.ok) { tree = await r.json(); branch = b; break; } + if (r.status === 403) throw new Error('GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.'); + } + if (!tree) throw new Error('No pude leer el repo (¿existe y es público?)'); + return (tree.tree || []) + .filter(n => /(^|\/)SKILL\.md$/i.test(n.path)) + .map(n => ({ repo, branch, path: n.path, dir: n.path.replace(/\/SKILL\.md$/i, ''), name: n.path.replace(/\/SKILL\.md$/i, '').split('/').pop() || repo })) + .sort((a, b) => a.dir.localeCompare(b.dir)); +} + +// Descarga el SKILL.md y lo instala (frontmatter YAML simple). +export async function installFromRepo(entry) { + let md = null; + for (const b of [entry.branch, 'main', 'master'].filter(Boolean)) { + const r = await fetch(`https://raw.githubusercontent.com/${entry.repo}/${b}/${entry.path}`); + if (r.ok) { md = await r.text(); break; } + } + if (md == null) throw new Error('No pude descargar el SKILL.md'); + const skill = parseSkill(md, entry.name); + return install({ ...skill, repo: entry.repo, path: entry.path }); +} + +// SKILL.md → { name, description, content } +export function parseSkill(md, fallbackName = 'skill') { + const fm = md.match(/^---\n([\s\S]*?)\n---/); + const meta = fm?.[1] || ''; + const name = meta.match(/^name:\s*(.+)$/m)?.[1]?.trim() || fallbackName; + const description = (meta.match(/^description:\s*([\s\S]+?)(?:\n\w+:|$)/m)?.[1] || '').replace(/\s+/g, ' ').trim(); + const content = md.replace(/^---\n[\s\S]*?\n---\n?/, '').trim(); + return { name, description, content }; +} + +// Creador de skills: Elffuss fabrica una skill propia (SKILL.md) a partir de +// lo que el usuario quiere, y la instala al instante. Aparece en la pestaña +// Skills y se inyecta en el prompt de los siguientes turnos. +export async function createSkill({ name, description, instructions } = {}) { + if (!name || !instructions) throw new Error('Faltan name o instructions'); + const skill = { + name: String(name).slice(0, 48), + description: (description || '').slice(0, 240), + content: String(instructions).slice(0, MAX_SKILL), + repo: 'creada por Elffuss', + path: 'local/' + Date.now(), + }; + await install(skill); + return `Skill «${skill.name}» creada e instalada. Ya la sigo en cada conversación (mírala en la pestaña Skills).`; +} + +// Editar una skill YA instalada: reemplaza sus instrucciones (o las añade con append), +// conservando su origen. Para ajustar el script/argumentos de una skill existente. +export async function editSkill({ name, description, instructions, append } = {}) { + if (!name) throw new Error('Falta name'); + const s = cache.find(x => x.name.toLowerCase() === String(name).toLowerCase()); + if (!s) throw new Error(`No hay ninguna skill «${name}». Créala primero con skill.create.`); + let content = s.content || ''; + if (instructions != null) content = append ? (content + '\n' + instructions) : String(instructions); + const updated = { ...s, description: description != null ? String(description).slice(0, 240) : s.description, content: content.slice(0, MAX_SKILL) }; + await install(updated); + return `Skill «${s.name}» actualizada. Ya sigo la nueva versión.`; +} + +// Bloque para el systemPrompt (síncrono, desde la caché). +export function skillsPromptBlock() { + if (!cache.length) return ''; + const nombres = cache.map(s => `«${s.name}»`).join(', '); + const parts = cache.map(s => + `### Skill «${s.name}»${s.repo ? ` (de ${s.repo})` : ''}\n${s.description || ''}\n${(s.content || '').slice(0, MAX_SKILL)}`); + // Framing DIRECTIVO: un modelo pequeño con el framing pasivo de antes negaba + // tener la skill aunque estuviera inyectada («I don't have that skill»). Aquí + // se le dice explícitamente que ES una capacidad suya AHORA, que no la niegue, + // que empareje por tema aunque el usuario use otro nombre, y que si la skill + // trae una plantilla de app la cree con app.create copiándola. + return `\n\nSKILLS INSTALADAS — son capacidades que TIENES AHORA MISMO: ${nombres}.\n` + + `REGLAS con las skills:\n` + + `- Si la petición encaja con una skill (aunque el usuario la nombre con otras palabras o un nombre parecido, empareja por el TEMA de su descripción), ÚSALA siguiendo sus instrucciones al pie de la letra.\n` + + `- NUNCA digas que no tienes esa skill o esa capacidad: la tienes, está aquí abajo.\n` + + `- Si la skill incluye una plantilla de app (HTML), créala con la herramienta app.create COPIANDO esa plantilla y adaptando solo lo que la skill indique — no inventes una app genérica distinta.\n\n` + + parts.join('\n\n'); +}