@meiti/healer 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/healer-mcp.mjs ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ // healer-mcp: el servidor MCP de Healer para agentes que no son Claude Code (DeepSeek Harness, Cursor, cualquier cliente
3
+ // MCP por stdio). El servidor lee la clave de un solo lugar, CLAUDE_PLUGIN_OPTION_API_KEY (en Claude Code es la opción
4
+ // sensible del plugin); acá se le pone desde HEALER_API_KEY o desde ~/.healer/config.json, que escribe el instalador.
5
+ // Este archivo va solo en el paquete npm, nunca dentro del plugin de Claude Code.
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+
10
+ if (!process.env.CLAUDE_PLUGIN_OPTION_API_KEY) {
11
+ let clave = (process.env.HEALER_API_KEY || '').trim();
12
+ if (!clave) {
13
+ try { clave = String(JSON.parse(fs.readFileSync(path.join(os.homedir(), '.healer', 'config.json'), 'utf8')).api_key || '').trim(); } catch { /* sin conectar: el servidor lo dice en la primera llamada */ }
14
+ }
15
+ process.env.CLAUDE_PLUGIN_OPTION_API_KEY = clave;
16
+ }
17
+
18
+ await import('./mcp/servidor.mjs');
package/instalar.mjs CHANGED
@@ -41,6 +41,8 @@ const T = es ? {
41
41
  plugin: 'Instalando el plugin de Claude Code...',
42
42
  pluginOk: 'Plugin instalado.',
43
43
  pluginYa: 'El plugin ya estaba instalado.',
44
+ claveEnPlugin: 'Clave guardada en el plugin. Si Claude Code estaba abierto, reinícialo.',
45
+ claveEnPluginFallo: 'No pude guardar la clave en el plugin. Adentro de Claude Code: /plugin > healer > Configure.',
44
46
  sinClaude: 'No encontré Claude Code en esta computadora. Cuando lo tengas, adentro escribe:',
45
47
  pluginFallo: 'No pude instalar el plugin solo. Adentro de Claude Code escribe:',
46
48
  listo: 'Listo. Abre Claude Code en tu proyecto y escribe',
@@ -63,6 +65,8 @@ const T = es ? {
63
65
  plugin: 'Installing the Claude Code plugin...',
64
66
  pluginOk: 'Plugin installed.',
65
67
  pluginYa: 'The plugin was already installed.',
68
+ claveEnPlugin: 'Key saved in the plugin. If Claude Code was open, restart it.',
69
+ claveEnPluginFallo: 'Could not save the key in the plugin. Inside Claude Code: /plugin > healer > Configure.',
66
70
  sinClaude: 'Claude Code is not on this computer. Once you have it, type inside it:',
67
71
  pluginFallo: 'Could not install the plugin automatically. Inside Claude Code, type:',
68
72
  listo: 'All set. Open Claude Code in your project and type',
@@ -141,19 +145,35 @@ function hayClaude() {
141
145
 
142
146
  // La CLI se corre desde una carpeta propia y vacía: arrancada desde la carpeta del usuario, Claude Code se niega
143
147
  // ("unsafe location") y el marketplace no se agrega.
144
- function claude(argumentos) {
145
- return spawnSync('claude', argumentos, { cwd: CARPETA, encoding: 'utf8', shell: process.platform === 'win32' });
148
+ // En Windows `claude` es un .cmd y solo arranca con shell; ahí se arma la línea entera (los argumentos son siempre
149
+ // constantes de este archivo, nunca algo que venga de afuera; la clave viaja por stdin).
150
+ function claude(argumentos, entrada) {
151
+ if (process.platform === 'win32') return spawnSync(['claude', ...argumentos].join(' '), { cwd: CARPETA, encoding: 'utf8', shell: true, input: entrada });
152
+ return spawnSync('claude', argumentos, { cwd: CARPETA, encoding: 'utf8', input: entrada });
146
153
  }
147
154
 
148
- function instalarPlugin() {
155
+ // El plugin de Claude Code recibe la clave por su opción sensible (userConfig api_key), que Claude Code guarda con sus
156
+ // propios secretos: el directorio oficial de plugins pide eso en vez de que el plugin la lea de la máquina. La clave va
157
+ // por stdin, nunca como argumento (no queda en el historial ni en la lista de procesos).
158
+ function instalarPlugin(clave) {
149
159
  const manual = ` /plugin marketplace add ${MARKETPLACE}\n /plugin install ${PLUGIN}`;
150
160
  if (!hayClaude()) { console.log(`\n${T.sinClaude}\n${cian(manual)}`); return; }
151
- if ((claude(['plugin', 'list']).stdout || '').includes(PLUGIN)) { console.log(`\n${verde('✓')} ${T.pluginYa}`); return; }
152
- console.log('\n' + T.plugin);
153
- claude(['plugin', 'marketplace', 'add', MARKETPLACE]); // si ya estaba agregado falla, y está bien
154
- const r = claude(['plugin', 'install', PLUGIN]);
155
- if (r.status === 0) console.log(`${verde('✓')} ${T.pluginOk}`);
156
- else console.log(`${T.pluginFallo}\n${cian(manual)}`);
161
+ if ((claude(['plugin', 'list']).stdout || '').includes(PLUGIN)) {
162
+ // Una versión vieja no tiene la opción de la clave: se actualiza antes de guardarla.
163
+ claude(['plugin', 'marketplace', 'update', 'meiti']);
164
+ claude(['plugin', 'update', PLUGIN]);
165
+ console.log(`\n${verde('✓')} ${T.pluginYa}`);
166
+ } else {
167
+ console.log('\n' + T.plugin);
168
+ claude(['plugin', 'marketplace', 'add', MARKETPLACE]); // si ya estaba agregado falla, y está bien
169
+ const r = claude(['plugin', 'install', PLUGIN]);
170
+ if (r.status !== 0) { console.log(`${T.pluginFallo}\n${cian(manual)}`); return; }
171
+ console.log(`${verde('✓')} ${T.pluginOk}`);
172
+ }
173
+ if (!clave) return;
174
+ const c = claude(['plugin', 'configure', PLUGIN, '--values-stdin'], JSON.stringify({ api_key: clave }));
175
+ if (c.status === 0) console.log(`${verde('✓')} ${T.claveEnPlugin}`);
176
+ else console.log(T.claveEnPluginFallo);
157
177
  }
158
178
 
159
179
  async function main() {
@@ -173,7 +193,7 @@ async function main() {
173
193
  console.log(`\n${verde('✓')} ${negrita(T.conectado)} ${gris(`${T.guardada} ${CONFIG}`)}`);
174
194
  }
175
195
 
176
- if (!sinPlugin) instalarPlugin();
196
+ if (!sinPlugin) instalarPlugin(leerConfig()?.api_key || '');
177
197
 
178
198
  console.log(`\n${T.listo} ${negrita(cian('/healer'))}`);
179
199
  console.log(gris(`\n${T.gratis}`));
package/mcp/servidor.mjs CHANGED
@@ -1,27 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // 🩺 Healer para Claude Code (2026-11-09): servidor MCP sin dependencias (solo Node 18+), por stdio, JSON-RPC 2.0.
3
3
  // Tres herramientas sobre la API pública de Healer (las mismas de la GitHub Action y del SDK):
4
- // healer_revisar arma el proyecto (lo que git versiona, o los archivos de texto si no hay git) y lo manda a reparar.
4
+ // healer_revisar arma el proyecto (lo que git mandaría según los .gitignore, nunca archivos de secretos) y lo manda a reparar.
5
5
  // healer_resultado consulta el trabajo; al terminar guarda la propuesta y devuelve el resumen y el diff.
6
6
  // healer_aplicar escribe los archivos corregidos SOLO si cada uno sigue igual a como se mandó (base_hashes).
7
7
  // Nunca escribe nada sin que se llame healer_aplicar, y el comando /healer le pide a Claude confirmar antes.
8
- // La clave sale de HEALER_API_KEY o, si no está, de ~/.healer/config.json (lo escribe npx @meiti/healer). Nunca se imprime.
8
+ // La clave llega SOLO por CLAUDE_PLUGIN_OPTION_API_KEY: en Claude Code es la opción sensible del plugin (la guarda el
9
+ // instalador de Healer); para otros agentes la pone healer-mcp.mjs del paquete npm, que vive fuera de este plugin.
10
+ // Nunca se imprime.
9
11
  import fs from 'node:fs';
10
12
  import os from 'node:os';
11
13
  import path from 'node:path';
12
14
  import crypto from 'node:crypto';
13
15
  import readline from 'node:readline';
14
- import { execFileSync } from 'node:child_process';
15
16
 
16
- const VERSION = '0.1.0';
17
+ const VERSION = '0.3.3';
17
18
  const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
18
- // Se lee en cada llamada, no al arrancar: si la persona conecta Healer con el instalador mientras Claude Code
19
- // ya está abierto, la próxima llamada ya encuentra la clave, sin reiniciar nada.
20
- const ARCHIVO_CONFIG = path.join(os.homedir(), '.healer', 'config.json');
21
- function leerClave() {
22
- if (process.env.HEALER_API_KEY) return process.env.HEALER_API_KEY.trim();
23
- try { return String(JSON.parse(fs.readFileSync(ARCHIVO_CONFIG, 'utf8')).api_key || '').trim(); } catch { return ''; }
24
- }
19
+ const leerClave = () => String(process.env.CLAUDE_PLUGIN_OPTION_API_KEY || '').trim();
25
20
  const ESTADO = path.join(os.tmpdir(), 'healer-claude-code');
26
21
  const TOPE_ARCHIVO = 1_000_000;
27
22
  const TOPE_TOTAL = 18 * 1024 * 1024;
@@ -29,23 +24,67 @@ const IGNORAR = new Set(['.git', 'node_modules', '.venv', 'venv', 'dist', 'build
29
24
 
30
25
  // ───────────────────────────── Proyecto ─────────────────────────────
31
26
 
32
- function archivosDelProyecto(raiz) {
33
- let rutas;
34
- try {
35
- // Lo que git versiona más lo nuevo sin ignorar: respeta el .gitignore del proyecto.
36
- rutas = execFileSync('git', ['-C', raiz, 'ls-files', '-co', '--exclude-standard'], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] })
37
- .split('\n').filter(Boolean);
38
- } catch {
39
- rutas = [];
40
- const recorrer = (dir) => {
41
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
42
- if (IGNORAR.has(e.name) || e.isSymbolicLink()) continue;
43
- const p = path.join(dir, e.name);
44
- if (e.isDirectory()) recorrer(p); else if (e.isFile()) rutas.push(path.relative(raiz, p).split(path.sep).join('/'));
45
- }
46
- };
47
- recorrer(raiz);
27
+ // Archivos de secretos: nunca salen de la máquina, aunque el proyecto se haya olvidado de ignorarlos.
28
+ const SECRETO = /^(\.env(\..+)?|.*\.(pem|key|p12|pfx|keystore|jks)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|\.npmrc|\.pypirc|\.netrc|credentials(\.json)?)$/i;
29
+ const PLANTILLA_ENV = /^\.env\.(example|sample|template|dist)$/i;
30
+
31
+ // Una línea de .gitignore → expresión regular sobre la ruta relativa a la carpeta del .gitignore. Cubre lo que se usa en
32
+ // la práctica: comentarios, "!" para volver a incluir, "/" final (solo carpetas), "/" inicial o en el medio (anclado),
33
+ // *, ?, ** y [clases]. Antes esto lo hacía `git ls-files`; se hace acá para que el plugin no ejecute ningún programa.
34
+ function reglaGitignore(linea) {
35
+ let l = linea.replace(/\r$/, '');
36
+ if (!l.trim() || l.startsWith('#')) return null;
37
+ l = l.replace(/(?<!\\)\s+$/, '');
38
+ const negada = l.startsWith('!');
39
+ if (negada) l = l.slice(1);
40
+ l = l.replace(/^\\([#!])/, '$1');
41
+ const soloCarpeta = l.endsWith('/');
42
+ if (soloCarpeta) l = l.slice(0, -1);
43
+ const anclada = l.includes('/');
44
+ if (l.startsWith('/')) l = l.slice(1);
45
+ let re = '';
46
+ for (let i = 0; i < l.length; i++) {
47
+ const c = l[i];
48
+ if (c === '*' && l[i + 1] === '*') {
49
+ if (l[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; }
50
+ } else if (c === '*') re += '[^/]*';
51
+ else if (c === '?') re += '[^/]';
52
+ else if (c === '[') { const fin = l.indexOf(']', i + 1); if (fin > i) { re += '[' + l.slice(i + 1, fin).replace(/^!/, '^').replace(/\\/g, '\\\\') + ']'; i = fin; } else re += '\\['; }
53
+ else if (c === '\\' && i + 1 < l.length) { re += l[i + 1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); i++; }
54
+ else re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
+ }
56
+ return { negada, soloCarpeta, re: new RegExp(anclada ? `^${re}$` : `(?:^|/)${re}$`) };
57
+ }
58
+
59
+ function leerReglas(archivo, base) {
60
+ try { return fs.readFileSync(archivo, 'utf8').split('\n').map(reglaGitignore).filter(Boolean).map((r) => ({ ...r, base })); } catch { return []; }
61
+ }
62
+
63
+ // Gana la última regla que coincide, como en git. `rel` es la ruta relativa a la raíz del proyecto.
64
+ function ignorado(rel, esCarpeta, reglas) {
65
+ let resultado = false;
66
+ for (const r of reglas) {
67
+ if (r.soloCarpeta && !esCarpeta) continue;
68
+ const local = r.base ? (rel.startsWith(r.base + '/') ? rel.slice(r.base.length + 1) : null) : rel;
69
+ if (local !== null && r.re.test(local)) resultado = !r.negada;
48
70
  }
71
+ return resultado;
72
+ }
73
+
74
+ function archivosDelProyecto(raiz) {
75
+ // Lo que git mandaría: respeta los .gitignore del proyecto (en cada carpeta) y .git/info/exclude.
76
+ const rutas = [];
77
+ const recorrer = (dir, rel, reglas) => {
78
+ const propias = [...reglas, ...leerReglas(path.join(dir, '.gitignore'), rel)];
79
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
80
+ if (IGNORAR.has(e.name) || e.isSymbolicLink()) continue;
81
+ const r = rel ? `${rel}/${e.name}` : e.name;
82
+ if (ignorado(r, e.isDirectory(), propias)) continue;
83
+ if (e.isDirectory()) recorrer(path.join(dir, e.name), r, propias);
84
+ else if (e.isFile() && (!SECRETO.test(e.name) || PLANTILLA_ENV.test(e.name))) rutas.push(r);
85
+ }
86
+ };
87
+ recorrer(raiz, '', leerReglas(path.join(raiz, '.git', 'info', 'exclude'), ''));
49
88
  const files = {};
50
89
  let total = 0;
51
90
  let omitidos = 0;
@@ -68,7 +107,9 @@ const sha256 = (texto) => crypto.createHash('sha256').update(texto, 'utf8').dige
68
107
 
69
108
  async function api(metodo, ruta, cuerpo) {
70
109
  const CLAVE = leerClave();
71
- if (!CLAVE) throw new Error('Healer is not connected yet. Run `npx @meiti/healer` in a terminal (it takes a minute and asks you to confirm in the browser), or set HEALER_API_KEY with a key from https://meiti.dev/healer (panel > API Keys).');
110
+ if (!CLAVE) {
111
+ throw new Error('Healer is not connected yet. To connect it, see meiti.dev/healer. In Claude Code you can also paste an API key in /plugin > healer > Configure and restart Claude Code.');
112
+ }
72
113
  const r = await fetch(API + ruta, { method: metodo, headers: { 'x-api-key': CLAVE, 'content-type': 'application/json', 'user-agent': `healer-claude-code/${VERSION}` }, body: cuerpo ? JSON.stringify(cuerpo) : undefined });
73
114
  const datos = await r.json().catch(() => ({}));
74
115
  if (!r.ok) throw new Error(`Healer answered ${r.status}: ${datos.error || 'no detail'}`);
@@ -135,25 +176,48 @@ async function resultado({ job_id, esperar_segundos }) {
135
176
  return lineas.join('\n');
136
177
  }
137
178
 
138
- // Diff con git si está (lo más legible); si no, solo las líneas que cambiaron.
179
+ // Diff unificado en JavaScript, con 2 líneas de contexto. Antes escribía los dos lados a disco y corría `git diff`:
180
+ // el escáner del directorio de plugins lo marcaba como "bajar y ejecutar", y además no hacía falta.
139
181
  function diffDe(antes, despues) {
140
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'healer-diff-'));
141
- try {
142
- fs.writeFileSync(path.join(dir, 'a'), antes);
143
- fs.writeFileSync(path.join(dir, 'b'), despues);
144
- try {
145
- execFileSync('git', ['diff', '--no-index', '--no-color', '-U2', 'a', 'b'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
146
- return '(no differences)';
147
- } catch (e) {
148
- const salida = String(e.stdout || '');
149
- if (salida) return salida.split('\n').slice(4).join('\n').slice(0, 12000);
150
- }
151
- } catch { /* sin git */ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
182
+ if (antes === despues) return '(no differences)';
152
183
  const a = antes.split('\n');
153
184
  const b = despues.split('\n');
154
- const fuera = a.filter((l) => !b.includes(l)).slice(0, 40).map((l) => `- ${l}`);
155
- const dentro = b.filter((l) => !a.includes(l)).slice(0, 40).map((l) => `+ ${l}`);
156
- return [...fuera, ...dentro].join('\n') || '(whitespace only)';
185
+ // Se recortan el principio y el final iguales: la tabla de abajo solo cubre la parte que cambió.
186
+ let ini = 0;
187
+ while (ini < a.length && ini < b.length && a[ini] === b[ini]) ini++;
188
+ let finA = a.length, finB = b.length;
189
+ while (finA > ini && finB > ini && a[finA - 1] === b[finB - 1]) { finA--; finB--; }
190
+ const ma = a.slice(ini, finA), mb = b.slice(ini, finB);
191
+ if (ma.length * mb.length > 4_000_000) {
192
+ // Cambio enorme: sin tabla, el bloque entero quitado y agregado.
193
+ return [`@@ line ${ini + 1} @@`, ...ma.slice(0, 200).map((l) => `-${l}`), ...mb.slice(0, 200).map((l) => `+${l}`)].join('\n').slice(0, 12000);
194
+ }
195
+ const lcs = Array.from({ length: ma.length + 1 }, () => new Uint32Array(mb.length + 1));
196
+ for (let i = ma.length - 1; i >= 0; i--) for (let j = mb.length - 1; j >= 0; j--) lcs[i][j] = ma[i] === mb[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
197
+ const ops = [];
198
+ for (let k = Math.max(0, ini - 2); k < ini; k++) ops.push([' ', a[k]]);
199
+ let i = 0, j = 0;
200
+ while (i < ma.length || j < mb.length) {
201
+ if (i < ma.length && j < mb.length && ma[i] === mb[j]) { ops.push([' ', ma[i]]); i++; j++; }
202
+ else if (i < ma.length && (j === mb.length || lcs[i + 1][j] >= lcs[i][j + 1])) { ops.push(['-', ma[i]]); i++; }
203
+ else { ops.push(['+', mb[j]]); j++; }
204
+ }
205
+ for (let k = finA; k < Math.min(a.length, finA + 2); k++) ops.push([' ', a[k]]);
206
+ // Más de 4 líneas iguales seguidas en el medio se resumen con "...", como los trozos de git.
207
+ const salida = [`@@ line ${Math.max(1, ini - 1)} @@`];
208
+ let iguales = [];
209
+ const volcar = (alFinal) => {
210
+ if (iguales.length > 4 && !alFinal) salida.push(...iguales.slice(0, 2), '...', ...iguales.slice(-2));
211
+ else salida.push(...iguales);
212
+ iguales = [];
213
+ };
214
+ for (const [t, l] of ops) {
215
+ if (t === ' ') { iguales.push(` ${l}`); continue; }
216
+ volcar(false);
217
+ salida.push(`${t}${l}`);
218
+ }
219
+ volcar(true);
220
+ return salida.join('\n').slice(0, 12000);
157
221
  }
158
222
 
159
223
  async function aplicar({ job_id }) {
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@meiti/healer",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Connect Healer to Claude Code (and any MCP agent) in a minute: a short code, one click in the browser, done.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "healer": "instalar.mjs",
8
- "healer-mcp": "mcp/servidor.mjs"
8
+ "healer-mcp": "healer-mcp.mjs"
9
9
  },
10
10
  "files": [
11
11
  "instalar.mjs",
12
+ "healer-mcp.mjs",
12
13
  "mcp/servidor.mjs",
13
14
  "README.md",
14
15
  "LICENSE"
@@ -31,6 +32,6 @@
31
32
  ],
32
33
  "license": "MIT",
33
34
  "scripts": {
34
- "prepack": "node -e \"require('fs').mkdirSync('mcp',{recursive:true});require('fs').copyFileSync('../claude-code/mcp/servidor.mjs','mcp/servidor.mjs')\""
35
+ "prepack": "node -e \"require('fs').mkdirSync('mcp',{recursive:true});require('fs').copyFileSync('../claude-code/plugins/healer/mcp/servidor.mjs','mcp/servidor.mjs')\""
35
36
  }
36
37
  }