@meiti/healer 0.1.0 → 0.2.1

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.5';
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, '\\$&');
48
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;
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'}`);
@@ -104,7 +145,8 @@ async function resultado({ job_id, esperar_segundos }) {
104
145
  if (!['queued', 'running'].includes(r.status) || Date.now() >= limite) break;
105
146
  await new Promise((ok) => setTimeout(ok, 5000));
106
147
  }
107
- if (r.status === 'queued' || r.status === 'running') return `Still ${r.status === 'queued' ? 'queued' : 'running'}. Call healer_resultado again in a moment.`;
148
+ // El servidor manda en qué va (proyecto, minutos, etapa, lo hecho): se muestra eso en vez de solo "running".
149
+ if (r.status === 'queued' || r.status === 'running') return `${r.progress?.message || `Still ${r.status}.`}\nCall healer_resultado again in a moment.\nJob id: ${job_id}`;
108
150
  if (r.status === 'error') return `Healer could not finish: ${r.error || 'unknown error'}.`;
109
151
 
110
152
  const meta = fs.existsSync(archivoDeTrabajo(job_id)) ? JSON.parse(fs.readFileSync(archivoDeTrabajo(job_id), 'utf8')) : null;
@@ -123,8 +165,13 @@ async function resultado({ job_id, esperar_segundos }) {
123
165
  lineas.push('No file changes to apply.');
124
166
  return lineas.join('\n');
125
167
  }
126
- lineas.push(`Proposed changes in ${cambiados.length} file(s): ${cambiados.join(', ')}.`);
127
- lineas.push('Nothing has been written. Show this to the user and apply only if they agree, with healer_aplicar.');
168
+ // Qué arregló en cada archivo, para que el usuario elija: se puede aplicar solo una parte (igual que el conector remoto).
169
+ lineas.push(`Proposed changes in ${cambiados.length} file(s). What each one fixes:`);
170
+ for (const ruta of cambiados) {
171
+ const motivos = (r.history || []).filter((h) => h?.file === ruta).map((h) => String(h.error || '').replace(/\s+/g, ' ').slice(0, 200)).filter(Boolean);
172
+ lineas.push(`- ${ruta}${motivos.length ? `\n ${motivos.map((m) => `· ${m}`).join('\n ')}` : ''}`);
173
+ }
174
+ lineas.push('Nothing has been written. Review each file against the rest of the project, show this to the user and apply only what they agree to, with healer_aplicar (pass "archivos" to apply only some files).');
128
175
  if (meta) {
129
176
  for (const ruta of cambiados) {
130
177
  const local = path.join(meta.raiz, ruta);
@@ -135,48 +182,79 @@ async function resultado({ job_id, esperar_segundos }) {
135
182
  return lineas.join('\n');
136
183
  }
137
184
 
138
- // Diff con git si está (lo más legible); si no, solo las líneas que cambiaron.
185
+ // Diff unificado en JavaScript, con 2 líneas de contexto. Antes escribía los dos lados a disco y corría `git diff`:
186
+ // el escáner del directorio de plugins lo marcaba como "bajar y ejecutar", y además no hacía falta.
139
187
  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 }); }
188
+ if (antes === despues) return '(no differences)';
152
189
  const a = antes.split('\n');
153
190
  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)';
191
+ // Se recortan el principio y el final iguales: la tabla de abajo solo cubre la parte que cambió.
192
+ let ini = 0;
193
+ while (ini < a.length && ini < b.length && a[ini] === b[ini]) ini++;
194
+ let finA = a.length, finB = b.length;
195
+ while (finA > ini && finB > ini && a[finA - 1] === b[finB - 1]) { finA--; finB--; }
196
+ const ma = a.slice(ini, finA), mb = b.slice(ini, finB);
197
+ if (ma.length * mb.length > 4_000_000) {
198
+ // Cambio enorme: sin tabla, el bloque entero quitado y agregado.
199
+ return [`@@ line ${ini + 1} @@`, ...ma.slice(0, 200).map((l) => `-${l}`), ...mb.slice(0, 200).map((l) => `+${l}`)].join('\n').slice(0, 12000);
200
+ }
201
+ const lcs = Array.from({ length: ma.length + 1 }, () => new Uint32Array(mb.length + 1));
202
+ 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]);
203
+ const ops = [];
204
+ for (let k = Math.max(0, ini - 2); k < ini; k++) ops.push([' ', a[k]]);
205
+ let i = 0, j = 0;
206
+ while (i < ma.length || j < mb.length) {
207
+ if (i < ma.length && j < mb.length && ma[i] === mb[j]) { ops.push([' ', ma[i]]); i++; j++; }
208
+ else if (i < ma.length && (j === mb.length || lcs[i + 1][j] >= lcs[i][j + 1])) { ops.push(['-', ma[i]]); i++; }
209
+ else { ops.push(['+', mb[j]]); j++; }
210
+ }
211
+ for (let k = finA; k < Math.min(a.length, finA + 2); k++) ops.push([' ', a[k]]);
212
+ // Más de 4 líneas iguales seguidas en el medio se resumen con "...", como los trozos de git.
213
+ const salida = [`@@ line ${Math.max(1, ini - 1)} @@`];
214
+ let iguales = [];
215
+ const volcar = (alFinal) => {
216
+ if (iguales.length > 4 && !alFinal) salida.push(...iguales.slice(0, 2), '...', ...iguales.slice(-2));
217
+ else salida.push(...iguales);
218
+ iguales = [];
219
+ };
220
+ for (const [t, l] of ops) {
221
+ if (t === ' ') { iguales.push(` ${l}`); continue; }
222
+ volcar(false);
223
+ salida.push(`${t}${l}`);
224
+ }
225
+ volcar(true);
226
+ return salida.join('\n').slice(0, 12000);
157
227
  }
158
228
 
159
- async function aplicar({ job_id }) {
229
+ async function aplicar({ job_id, archivos }) {
160
230
  const archivo = archivoDeTrabajo(job_id);
161
231
  if (!fs.existsSync(archivo)) throw new Error('No proposal stored for that job: call healer_resultado first.');
162
232
  const t = JSON.parse(fs.readFileSync(archivo, 'utf8'));
163
233
  if (!t.changed_files?.length) return 'That job has no changes to apply.';
234
+ // Solo lo que el usuario aprobó (si mandó "archivos"); un nombre que Healer no cambió frena todo.
235
+ const pedidos = Array.isArray(archivos) && archivos.length ? archivos.map(String) : null;
236
+ if (pedidos) {
237
+ const ajenos = pedidos.filter((p) => !t.changed_files.includes(p));
238
+ if (ajenos.length) throw new Error(`These are not among the files Healer changed: ${ajenos.join(', ')}. Changed files: ${t.changed_files.join(', ')}.`);
239
+ }
240
+ const elegidos = pedidos ?? t.changed_files;
164
241
  // La base tiene que coincidir: si el usuario tocó un archivo después de mandarlo, ese no se pisa.
165
- const distintos = t.changed_files.filter((ruta) => {
242
+ const distintos = elegidos.filter((ruta) => {
166
243
  const local = path.join(t.raiz, ruta);
167
244
  const actual = fs.existsSync(local) ? fs.readFileSync(local, 'utf8') : null;
168
245
  return t.base_hashes[ruta] && (actual === null || sha256(actual) !== t.base_hashes[ruta]);
169
246
  });
170
247
  if (distintos.length) return `Not applied: these files changed since they were sent to Healer: ${distintos.join(', ')}. Send the project again with healer_revisar.`;
171
- for (const ruta of t.changed_files) {
248
+ for (const ruta of elegidos) {
172
249
  const destino = path.resolve(t.raiz, ruta);
173
250
  if (!destino.startsWith(t.raiz + path.sep)) throw new Error(`Path outside the project: ${ruta}`);
174
251
  if (typeof t.files[ruta] !== 'string') continue;
175
252
  fs.mkdirSync(path.dirname(destino), { recursive: true });
176
253
  fs.writeFileSync(destino, t.files[ruta]);
177
254
  }
178
- fs.writeFileSync(archivo, JSON.stringify({ ...t, aplicado: new Date().toISOString() }));
179
- return `Applied: ${t.changed_files.length} file(s) written (${t.changed_files.join(', ')}). Review the diff with git before committing.`;
255
+ fs.writeFileSync(archivo, JSON.stringify({ ...t, aplicado: new Date().toISOString(), aplicados: elegidos }));
256
+ const descartados = t.changed_files.filter((c) => !elegidos.includes(c));
257
+ return `Applied: ${elegidos.length} file(s) written (${elegidos.join(', ')}).${descartados.length ? ` Left out as requested: ${descartados.join(', ')}.` : ''} Review the diff with git before committing.`;
180
258
  }
181
259
 
182
260
  const HERRAMIENTAS = [
@@ -201,8 +279,8 @@ const HERRAMIENTAS = [
201
279
  },
202
280
  {
203
281
  name: 'healer_aplicar',
204
- description: 'Write Healer\'s proposed changes into the project. Only call it after the user agreed. It refuses any file that changed since it was sent.',
205
- inputSchema: { type: 'object', properties: { job_id: { type: 'string' } }, required: ['job_id'] },
282
+ description: 'Write Healer\'s proposed changes into the project. Only call it after the user agreed. Pass "archivos" to write only the files the user approved (the rest are left out). It refuses any file that changed since it was sent.',
283
+ inputSchema: { type: 'object', properties: { job_id: { type: 'string' }, archivos: { type: 'array', items: { type: 'string' }, description: 'Optional: paths (as listed by healer_resultado) of the only files to write.' } }, required: ['job_id'] },
206
284
  run: aplicar
207
285
  }
208
286
  ];
@@ -218,7 +296,9 @@ readline.createInterface({ input: process.stdin }).on('line', async (linea) => {
218
296
  if (m.id === undefined) return; // notificaciones (initialized, cancelled): nada que responder
219
297
  try {
220
298
  if (m.method === 'initialize') {
221
- return responder(m.id, { protocolVersion: m.params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'healer', version: VERSION } });
299
+ // Mismo ícono y título que el conector remoto, para los clientes que los muestran (MCP 2025-11-25).
300
+ const icono = (lado) => ({ src: `https://healer-api.meiti.dev/icono-${lado}.png?v=1`, mimeType: 'image/png', sizes: [`${lado}x${lado}`] });
301
+ return responder(m.id, { protocolVersion: m.params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'healer', title: 'Healer', version: VERSION, websiteUrl: 'https://meiti.dev/healer', icons: [icono(512), icono(192), icono(64)] } });
222
302
  }
223
303
  if (m.method === 'ping') return responder(m.id, {});
224
304
  if (m.method === 'tools/list') return responder(m.id, { tools: HERRAMIENTAS.map(({ run, ...h }) => h) });
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@meiti/healer",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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-local/mcp/servidor.mjs','mcp/servidor.mjs')\""
35
36
  }
36
37
  }