@meiti/healer 0.2.4 → 0.3.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @meiti/healer
2
2
 
3
- Connect [Healer](https://meiti.dev/healer) to Claude Code, DeepSeek Harness or any MCP agent in about a minute.
3
+ Connect [Healer](https://meiti.dev/healer) to Claude Code, Cursor, Gemini CLI, DeepSeek Harness or any MCP agent in about a minute. With `--for "Cursor"` or `--for "Gemini CLI"` the installer also adds Healer to `~/.cursor/mcp.json` or `~/.gemini/settings.json` (it never overwrites an existing "healer" entry or a file it cannot read).
4
4
 
5
5
  ```
6
6
  npx @meiti/healer
@@ -31,6 +31,8 @@ npx -y -p @meiti/healer healer-mcp
31
31
 
32
32
  ## Free level and your code
33
33
 
34
+ Healer uses pro unless your organization changed the rule in the panel. It never uses free without your yes: when a job would run on free, the agent asks you first.
35
+
34
36
  The free level repairs with free AI providers, which may keep and use what they receive, and the repaired code may be used to train Healer's models. On the pro level none of your code is used for training. For private code, use pro.
35
37
 
36
38
  MIT license.
package/instalar.mjs CHANGED
@@ -20,9 +20,12 @@ const PLUGIN = 'healer@meiti';
20
20
  const args = process.argv.slice(2);
21
21
  const reconectar = args.includes('--reconnect') || args.includes('--reconectar');
22
22
  const sinNavegador = args.includes('--no-browser') || !process.stdout.isTTY;
23
- const sinPlugin = args.includes('--no-plugin');
24
23
  const paraIdx = args.indexOf('--for');
25
24
  const cliente = paraIdx >= 0 && args[paraIdx + 1] ? args[paraIdx + 1] : 'Claude Code';
25
+ // 🔌 [2026-11-16] Cursor y Gemini CLI: el instalador escribe su configuración MCP (el servidor local, que lee la clave guardada).
26
+ // Para ellos no se instala el plugin de Claude Code.
27
+ const OTRO_AGENTE = /cursor/i.test(cliente) ? 'cursor' : /gemini/i.test(cliente) ? 'gemini' : null;
28
+ const sinPlugin = args.includes('--no-plugin') || !!OTRO_AGENTE;
26
29
 
27
30
  const es = /^es/i.test(process.env.HEALER_LANG || Intl.DateTimeFormat().resolvedOptions().locale || '');
28
31
  const T = es ? {
@@ -47,7 +50,10 @@ const T = es ? {
47
50
  pluginFallo: 'No pude instalar el plugin solo. Adentro de Claude Code escribe:',
48
51
  listo: 'Listo. Abre Claude Code en tu proyecto y escribe',
49
52
  listoOtros: 'Para otros agentes (DeepSeek Harness, Cursor), agrega este servidor MCP; lee la misma clave:',
50
- gratis: 'Nivel gratis: repara con proveedores de IA gratuitos, que pueden guardar lo que reciben, y el código reparado puede usarse para entrenar. Para código privado, usa /healer pro.',
53
+ gratis: 'Healer usa pro salvo que tu organización cambie la regla en el panel (Facturación > Nivel de IA). El nivel gratis nunca se usa sin tu sí: si un trabajo tocaría free, el agente te pregunta antes.',
54
+ agenteListo: (donde) => `Healer quedó agregado en ${donde}. Reinicia el agente para que cargue las herramientas.`,
55
+ agenteYa: (donde) => `${donde} ya tenía un servidor "healer": no lo toqué.`,
56
+ agenteFallo: (donde) => `No pude escribir ${donde}. Agrega a mano este servidor MCP:`,
51
57
  error: 'Algo falló:'
52
58
  } : {
53
59
  hola: "Hi. Let's connect Healer in about a minute.",
@@ -71,7 +77,10 @@ const T = es ? {
71
77
  pluginFallo: 'Could not install the plugin automatically. Inside Claude Code, type:',
72
78
  listo: 'All set. Open Claude Code in your project and type',
73
79
  listoOtros: 'For other agents (DeepSeek Harness, Cursor), add this MCP server; it reads the same key:',
74
- gratis: 'Free level: repairs with free AI providers, which may keep what they receive, and the repaired code may be used for training. For private code, use /healer pro.',
80
+ gratis: 'Healer uses pro unless your organization changes the rule in the panel (Billing > AI level). The free level is never used without your yes: if a job would run on free, the agent asks you first.',
81
+ agenteListo: (donde) => `Healer was added to ${donde}. Restart the agent so it loads the tools.`,
82
+ agenteYa: (donde) => `${donde} already had a "healer" server: left it as it was.`,
83
+ agenteFallo: (donde) => `Could not write ${donde}. Add this MCP server by hand:`,
75
84
  error: 'Something went wrong:'
76
85
  };
77
86
 
@@ -176,6 +185,26 @@ function instalarPlugin(clave) {
176
185
  else console.log(T.claveEnPluginFallo);
177
186
  }
178
187
 
188
+ // Agrega el servidor "healer" a la configuración MCP de Cursor o Gemini CLI sin tocar lo demás. Si el archivo no es JSON válido,
189
+ // no lo pisa: avisa y muestra qué agregar.
190
+ function configurarOtroAgente() {
191
+ const ruta = OTRO_AGENTE === 'cursor' ? path.join(os.homedir(), '.cursor', 'mcp.json') : path.join(os.homedir(), '.gemini', 'settings.json');
192
+ const servidor = { command: 'npx', args: ['-y', '-p', '@meiti/healer', 'healer-mcp'] };
193
+ try {
194
+ let config = {};
195
+ if (fs.existsSync(ruta)) config = JSON.parse(fs.readFileSync(ruta, 'utf8') || '{}');
196
+ if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('not a JSON object');
197
+ config.mcpServers = config.mcpServers && typeof config.mcpServers === 'object' ? config.mcpServers : {};
198
+ if (config.mcpServers.healer) { console.log(`\n${T.agenteYa(ruta)}`); return; }
199
+ config.mcpServers.healer = servidor;
200
+ fs.mkdirSync(path.dirname(ruta), { recursive: true });
201
+ fs.writeFileSync(ruta, JSON.stringify(config, null, 2) + '\n');
202
+ console.log(`\n${verde('✓')} ${T.agenteListo(ruta)}`);
203
+ } catch {
204
+ console.log(`\n${T.agenteFallo(ruta)}\n${JSON.stringify({ mcpServers: { healer: servidor } }, null, 2)}`);
205
+ }
206
+ }
207
+
179
208
  async function main() {
180
209
  console.log(LOGO + '\n');
181
210
  console.log(T.hola);
@@ -194,8 +223,8 @@ async function main() {
194
223
  }
195
224
 
196
225
  if (!sinPlugin) instalarPlugin(leerConfig()?.api_key || '');
197
-
198
- console.log(`\n${T.listo} ${negrita(cian('/healer'))}`);
226
+ if (OTRO_AGENTE) configurarOtroAgente();
227
+ else console.log(`\n${T.listo} ${negrita(cian('/healer'))}`);
199
228
  console.log(gris(`\n${T.gratis}`));
200
229
  console.log(gris(`${T.listoOtros} npx -y -p @meiti/healer healer-mcp\n`));
201
230
  }
package/mcp/servidor.mjs CHANGED
@@ -14,7 +14,7 @@ import path from 'node:path';
14
14
  import crypto from 'node:crypto';
15
15
  import readline from 'node:readline';
16
16
 
17
- const VERSION = '0.3.8';
17
+ const VERSION = '0.4.0';
18
18
  const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
19
19
  const leerClave = () => String(process.env.CLAUDE_PLUGIN_OPTION_API_KEY || '').trim();
20
20
  const ESTADO = path.join(os.tmpdir(), 'healer-claude-code');
@@ -112,7 +112,7 @@ async function api(metodo, ruta, cuerpo) {
112
112
  }
113
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 });
114
114
  const datos = await r.json().catch(() => ({}));
115
- if (!r.ok) throw new Error(`Healer answered ${r.status}: ${datos.error || 'no detail'}`);
115
+ if (!r.ok) { const e = new Error(`Healer answered ${r.status}: ${datos.error || datos.message || 'no detail'}`); e.status = r.status; e.datos = datos; throw e; }
116
116
  return datos;
117
117
  }
118
118
 
@@ -120,18 +120,26 @@ const archivoDeTrabajo = (jobId) => path.join(ESTADO, `${String(jobId).replace(/
120
120
 
121
121
  // ───────────────────────────── Herramientas ─────────────────────────────
122
122
 
123
- async function revisar({ ruta, nivel, tests }) {
123
+ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar }) {
124
124
  const raiz = path.resolve(ruta || process.cwd());
125
125
  if (!fs.existsSync(raiz) || !fs.statSync(raiz).isDirectory()) throw new Error(`Folder not found: ${raiz}.`);
126
126
  const { files, total, omitidos } = archivosDelProyecto(raiz);
127
127
  if (!Object.keys(files).length) throw new Error('No text files to send were found in that folder.');
128
128
  if (Array.isArray(tests) && tests.length && !files['.healer.json']) files['.healer.json'] = JSON.stringify({ tests }, null, 2);
129
129
  const appId = `claude-code/${path.basename(raiz).replace(/[^\w.-]/g, '-').slice(0, 60) || 'proyecto'}`;
130
- const envio = await api('POST', '/v1/repair', { files, app_id: appId, ai_level: nivel === 'pro' ? 'pro' : 'free' });
130
+ // 🔐 [2026-11-16] Sin nivel propio (antes free por defecto): vale la política de la organización (pro salvo que el dueño cambie).
131
+ // Si tocaría free y la organización pide preguntar, Healer responde 409 y no se encola nada.
132
+ let envio;
133
+ try {
134
+ envio = await api('POST', '/v1/repair', { files, app_id: appId, ...(nivel === 'free' || nivel === 'pro' ? { ai_level: nivel } : {}), ...(confirmar_free === true ? { confirm_free: true } : {}), ...(solo_revisar === true ? { review_only: true } : {}) });
135
+ } catch (e) {
136
+ if (e.status === 409) return `Needs the user's confirmation, nothing was queued: ${e.datos?.message}\nIn this tool, "confirm_free" is confirmar_free: true${e.datos?.reason === 'cupo_agotado' ? ', and "review_only" is solo_revisar: true' : ''}.`;
137
+ throw e;
138
+ }
131
139
  fs.mkdirSync(ESTADO, { recursive: true });
132
140
  fs.writeFileSync(archivoDeTrabajo(envio.job_id), JSON.stringify({ raiz, appId, enviado: new Date().toISOString() }));
133
141
  return [
134
- `Sent to Healer: job ${envio.job_id} (${envio.ai_level || nivel || 'free'} level).`,
142
+ `Sent to Healer: job ${envio.job_id} (${envio.ai_level === 'none' ? 'review only, no AI' : `${envio.ai_level} level`}${envio.ai_level_reason ? `, ${({ pedido: 'requested', organizacion: 'organization default', cupo: 'single repairs', confirmado: 'confirmed by the user', auto: 'organization allows free automatically', solo_revisar: 'review only' })[envio.ai_level_reason] || envio.ai_level_reason}` : ''}).`,
135
143
  `${Object.keys(files).length} files, ${Math.round(total / 1024)} KB${omitidos ? `, ${omitidos} skipped (binary or too large)` : ''}.`,
136
144
  'Healer runs the tests in an isolated sandbox and repairs what fails. It usually takes a few minutes: check with healer_resultado.'
137
145
  ].join('\n');
@@ -144,7 +152,8 @@ async function revisarPantalla({ ruta, start_command, port, pages }) {
144
152
  const { files, total, omitidos } = archivosDelProyecto(raiz);
145
153
  if (!Object.keys(files).length) throw new Error('No text files to send were found in that folder.');
146
154
  const appId = `claude-code/${path.basename(raiz).replace(/[^\w.-]/g, '-').slice(0, 60) || 'proyecto'}`;
147
- const envio = await api('POST', '/v1/screen', { files, app_id: appId, start_command, port, pages });
155
+ // Sin start_command, port ni pages, Healer los busca (.healer.json "screen", la última corrida que funcionó, package.json).
156
+ const envio = await api('POST', '/v1/screen', { files, app_id: appId, start_command: start_command || undefined, port: port || undefined, pages: Array.isArray(pages) && pages.length ? pages : undefined });
148
157
  return [
149
158
  `Screen review started: job ${envio.job_id}.`,
150
159
  `${Object.keys(files).length} files, ${Math.round(total / 1024)} KB${omitidos ? `, ${omitidos} skipped (binary or too large)` : ''}.`,
@@ -157,12 +166,16 @@ function informePantalla(r) {
157
166
  const lineas = [];
158
167
  const titulo = { checked: 'Screen review finished.', did_not_start: 'The app did not start, so no page could be checked.', unsupported_stack: 'Unsupported stack: no supported language was found to install and start the app.' }[r.status] || r.status;
159
168
  lineas.push(`Result: ${titulo}`, `Summary: ${r.message}`);
169
+ if (r.start) lineas.push(`Started with: "${r.start.command}" on port ${r.start.port} · source: ${r.start.source} (${r.start.detail}) · ${r.start.verified ? 'verified: the app answered' : 'not verified: the app did not answer'}.`);
170
+ for (const s of r.missing_services || []) lineas.push(`Missing service: ${s.address} (${s.requests} request(s) with no answer${s.found_in ? `; it seems to be in ${s.found_in}` : ''}). ${s.hint}`);
171
+ if (r.server_log) lineas.push('Server log (last lines):', ...String(r.server_log).split('\n').slice(-25).map((l) => ` ${l}`));
160
172
  if (r.ms) lineas.push(`Time: ${Math.round((r.ms.total || 0) / 1000)} s (install ${Math.round((r.ms.install || 0) / 1000)} s, start ${Math.round((r.ms.start || 0) / 1000)} s, pages ${Math.round((r.ms.pages || 0) / 1000)} s).`);
161
173
  for (const pg of r.pages || []) {
162
174
  lineas.push('', `Page ${pg.path}: ${pg.state}${pg.http ? ` (HTTP ${pg.http})` : ''}${pg.title ? `, title "${pg.title}"` : ''}`);
163
175
  if (pg.reasons?.length) lineas.push(` Why: ${pg.reasons.join('; ')}`);
164
176
  for (const e of pg.expectations || []) lineas.push(` ${e.answer} ${JSON.stringify(e.expectation)} · ${e.proof}`);
165
177
  if (pg.failed_requests?.length) lineas.push(` Requests that failed: ${pg.failed_requests.join(', ')}`);
178
+ if (pg.page_errors?.length) lineas.push(` Page errors: ${pg.page_errors.slice(0, 5).join(' | ')}`);
166
179
  if (pg.visual_issues?.length) lineas.push(` Visual issues: ${pg.visual_issues.slice(0, 8).map((v) => `${v.type}${v.element ? ` at ${v.element}` : ''}: ${v.detail}`).join(' | ')}`);
167
180
  if (pg.map) lineas.push(' Screen map:', ...String(pg.map).split('\n').slice(0, 60).map((l) => ` ${l}`));
168
181
  }
@@ -191,6 +204,8 @@ async function resultado({ job_id, esperar_segundos }) {
191
204
  const lineas = [];
192
205
  const titulo = { production_ready: 'Production ready: every check passes.', unresolved: r.partial_fix ? 'Partial delivery: some failures fixed, some remain.' : 'Unresolved: Healer could not leave every check passing.', unsupported_stack: 'Unsupported stack: no supported language was found to verify.' }[r.status] || r.status;
193
206
  lineas.push(`Result: ${titulo}`);
207
+ // 🔐 [2026-11-16] Siempre se dice con qué nivel corrió y por qué.
208
+ if (r.ai_level) lineas.push(`AI level: ${r.ai_level === 'none' ? 'none (review only)' : r.ai_level}${r.ai_level_reason ? ` (${({ pedido: 'requested', organizacion: 'organization default', cupo: 'single repairs', confirmado: 'confirmed by the user', auto: 'organization allows free automatically', solo_revisar: 'review only', benchmark: 'benchmark' })[r.ai_level_reason] || r.ai_level_reason})` : ''}.`);
194
209
  // 📋 [2026-11-14, pedido del usuario: "el usuario no ve lo que vemos, no lo demos por hecho"] El informe de Healer (report):
195
210
  // qué se reparó, tests antes y después, y cada pendiente con qué es, por qué quedó y qué hace falta. Sin informe (Healer
196
211
  // de antes), la línea de fallas de siempre.
@@ -309,7 +324,36 @@ async function informarDecision({ job_id, aplicados = [], descartados = [] }) {
309
324
  return `Thanks: recorded ${r.registrados ?? 0} decision(s) (${aplicados.length} applied, ${descartados.length} left out).`;
310
325
  }
311
326
 
327
+ // 🛈 [HEALER_INFO, 2026-11-16] Qué servidor es y qué permite la cuenta (igual que en el conector remoto): versión, cada herramienta
328
+ // con la huella de su definición, la regla de nivel de la organización y el cupo pro. Sin IA y sin costo.
329
+ const huella = (texto) => crypto.createHash('sha256').update(texto).digest('hex').slice(0, 12);
330
+ async function info() {
331
+ const tools = HERRAMIENTAS.map(({ name, description, inputSchema }) => ({ name, fingerprint: huella(JSON.stringify({ name, description, inputSchema })) }));
332
+ const tools_fingerprint = huella(tools.map((t) => `${t.name}:${t.fingerprint}`).join('|'));
333
+ let cuenta = null;
334
+ try { cuenta = await api('GET', '/v1/info'); } catch (e) { cuenta = { error: e.message }; }
335
+ const lineas = [
336
+ `Healer MCP server (local) version ${VERSION}, talking to ${API}${cuenta?.remote_connector_version ? ` (server connector version ${cuenta.remote_connector_version})` : ''}.`,
337
+ `Tools (${tools.length}), fingerprint ${tools_fingerprint}: ${tools.map((t) => `${t.name} [${t.fingerprint}]`).join(', ')}.`,
338
+ 'If a name here is missing from your tool list, restart the agent (or update the Healer plugin) to load the current version.',
339
+ ];
340
+ if (cuenta?.error) lineas.push(`Account: ${cuenta.error}`);
341
+ else if (cuenta) {
342
+ lineas.push(`AI level of the organization: ${cuenta.ai_level_default} by default; when a job would run on free: ${cuenta.when_free === 'ask' ? "ask the user first (free never runs without the user's yes)" : 'free runs automatically'}.`);
343
+ const r = cuenta.repairs;
344
+ if (r) lineas.push(`Pro repairs this month: ${r.used}${r.limit !== null ? ` of ${r.limit}` : ' (no monthly limit)'}${r.extra ? `, plus ${r.extra} single repair(s)` : ''}.`);
345
+ }
346
+ lineas.push('', JSON.stringify({ server: 'healer', kind: 'local', version: VERSION, tools_fingerprint, tools, account: cuenta }));
347
+ return lineas.join('\n');
348
+ }
349
+
312
350
  const HERRAMIENTAS = [
351
+ {
352
+ name: 'healer_info',
353
+ description: 'What this Healer server is and what your account allows, in one call (no AI, no cost): server version, every tool with a fingerprint of its definition, the organization rule for the AI level and the pro repairs left this month. Use it when a tool you expect is missing or behaves differently than described.',
354
+ inputSchema: { type: 'object', properties: {} },
355
+ run: info
356
+ },
313
357
  {
314
358
  name: 'healer_revisar',
315
359
  description: 'Send the project to Healer for independent verification: it runs the tests in an isolated sandbox, repairs what fails and returns only changes that leave the project better, never worse. Returns a job id; then call healer_resultado.',
@@ -317,7 +361,9 @@ const HERRAMIENTAS = [
317
361
  type: 'object',
318
362
  properties: {
319
363
  ruta: { type: 'string', description: 'Project folder. Defaults to the current working directory.' },
320
- nivel: { type: 'string', enum: ['free', 'pro'], description: 'free (open models, no cost) or pro (paid models, uses your plan). Defaults to free.' },
364
+ nivel: { type: 'string', enum: ['free', 'pro'], description: 'Optional. Leave it out unless the user asked for a level: the organization default applies (pro unless the owner changed it). Free means free AI providers, which may keep what they receive, and the code may be used for training.' },
365
+ confirmar_free: { type: 'boolean', description: 'Only after the user said yes to the free level for THIS job (Healer asks when a job would run on free). Never set it on your own.' },
366
+ solo_revisar: { type: 'boolean', description: 'Run the checks without repairing and without AI (offered when the pro repairs are used up and the user does not want free).' },
321
367
  tests: { type: 'array', items: { type: 'string' }, description: 'Optional: the tests that define "fixed" (e.g. tests/test_api.py::test_login). Without this Healer runs the full suite.' }
322
368
  }
323
369
  },
@@ -337,16 +383,16 @@ const HERRAMIENTAS = [
337
383
  },
338
384
  {
339
385
  name: 'healer_revisar_pantalla',
340
- description: 'Start the app in Healer\'s isolated sandbox and check what its pages really show, WITHOUT repairing anything and without AI (much faster than a full review). Per page: the load state (LOADED, DID NOT LOAD with the reason, or NOT THE EXPECTED PAGE), failed requests, measured visual issues, a text map of the screen, and YES / NO / CANNOT PROVE for each expectation. You set the expectations from what you know about the code. Returns a job id; then call healer_resultado.',
386
+ description: 'Start the app in Healer\'s isolated sandbox and check what its pages really show, WITHOUT repairing anything and without AI (much faster than a full review). Per page: the load state (LOADED, DID NOT LOAD with the reason, or NOT THE EXPECTED PAGE), failed requests, measured visual issues, a text map of the screen, and YES / NO / CANNOT PROVE for each expectation. Only the folder is needed: without start_command and port, Healer finds how to start the app (.healer.json "screen", the command that worked last time, or package.json / the Python entry file) and says where it came from; without pages it checks "/". You set the expectations from what you know about the code. Returns a job id; then call healer_resultado.',
341
387
  inputSchema: {
342
388
  type: 'object',
343
389
  properties: {
344
390
  ruta: { type: 'string', description: 'Project folder. Defaults to the current working directory.' },
345
- start_command: { type: 'string', description: 'The command that starts the app, e.g. "npm run dev". It must listen on 0.0.0.0.' },
346
- port: { type: 'number', description: 'The port the app listens on (1024-65535).' },
347
- pages: { type: 'array', items: { type: 'object' }, description: 'Up to 10 pages: [{ "path": "/", "expect_page": { "title_is": "My App" }, "expectations": [{ "exists": "Save" }, { "not_exists": "Delete all" }, { "text": "Total", "contains": "0" }, { "no_issues": true }], "storage": { "session": "test-token" }, "wait_for": "Dashboard", "width": 375 }]. Test accounts only in storage.' }
391
+ start_command: { type: 'string', description: 'Optional: the command that starts the app, e.g. "npm run dev". It must listen on 0.0.0.0. Leave it out and Healer finds it.' },
392
+ port: { type: 'number', description: 'Optional: the port the app listens on (1024-65535). Leave it out and Healer finds it.' },
393
+ pages: { type: 'array', items: { type: 'object' }, description: 'Optional (default: [{ "path": "/" }]). Up to 10 pages: [{ "path": "/", "expect_page": { "title_is": "My App" }, "expectations": [{ "exists": "Save" }, { "not_exists": "Delete all" }, { "text": "Total", "contains": "0" }, { "no_issues": true }], "storage": { "session": "test-token" }, "wait_for": "Dashboard", "width": 375 }]. Test accounts only in storage.' }
348
394
  },
349
- required: ['start_command', 'port', 'pages']
395
+ required: []
350
396
  },
351
397
  run: revisarPantalla
352
398
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meiti/healer",
3
- "version": "0.2.4",
3
+ "version": "0.3.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": {