@saulwade/swl-ses 1.5.0 → 1.5.2
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/CLAUDE.md +19 -2
- package/README.md +561 -561
- package/agentes/arquitecto-swl.md +33 -1
- package/agentes/nemesis-auditor-swl.md +59 -19
- package/bin/swl-mcp-server.js +214 -214
- package/comandos/swl/.evolved.json +22 -22
- package/comandos/swl/contribuir.md +233 -233
- package/comandos/swl/nemesis.md +230 -56
- package/gateway/lib/event-channel.js +191 -191
- package/habilidades/backend-production-resilience/SKILL.md +288 -288
- package/habilidades/benchmark-memoria/SKILL.md +186 -186
- package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
- package/habilidades/doubt-driven-review/SKILL.md +171 -171
- package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
- package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
- package/habilidades/eval-framework/SKILL.md +212 -212
- package/habilidades/feynman-auditor-swl/SKILL.md +123 -123
- package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
- package/habilidades/harness-claude-code/SKILL.md +299 -299
- package/habilidades/infra-github-actions/SKILL.md +166 -166
- package/habilidades/legacy-code-rescue/SKILL.md +267 -267
- package/habilidades/manejo-errores/.evolved.json +8 -8
- package/habilidades/meta-skills-estandar/SKILL.md +225 -1
- package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
- package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
- package/habilidades/nemesis-evaluacion-json/SKILL.md +266 -0
- package/habilidades/nemesis-redistribuir/SKILL.md +341 -0
- package/habilidades/node-experto/SKILL.md +105 -4
- package/habilidades/patrones-python/SKILL.md +229 -229
- package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
- package/habilidades/planear-fase/SKILL.md +319 -319
- package/habilidades/protocolo-revision-swl/SKILL.md +350 -276
- package/habilidades/release-semver/.evolved.json +8 -8
- package/habilidades/state-inconsistency-auditor-swl/SKILL.md +166 -166
- package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
- package/habilidades/tdd-workflow/SKILL.md +150 -4
- package/habilidades/testing-python/SKILL.md +340 -340
- package/habilidades/verificar-trabajo/SKILL.md +8 -3
- package/habilidades/web-fetcher-routing/SKILL.md +75 -75
- package/hooks/check-update.js +31 -3
- package/hooks/claudemd-bloat-detector.js +161 -161
- package/hooks/lib/agent-routing.js +107 -107
- package/hooks/lib/auto-consolidator.js +335 -335
- package/hooks/lib/error-classifier.js +308 -308
- package/hooks/lib/merkle-audit.js +96 -96
- package/hooks/lib/provenance-tracker.js +191 -191
- package/hooks/lib/rate-limit-tracker.js +253 -253
- package/hooks/lib/resource-quota.js +122 -122
- package/hooks/lib/retry-jitter.js +165 -165
- package/hooks/lib/security-net.js +201 -201
- package/hooks/lib/skill-auditor.js +588 -588
- package/hooks/lib/sync-status.js +228 -228
- package/hooks/lib/taint-tracker.js +107 -107
- package/hooks/lib/text-similarity.js +241 -241
- package/hooks/lib/toon-compressor.js +245 -245
- package/hooks/registro-turnos.js +209 -209
- package/hooks/sugerir-regenerar-inventario.js +170 -170
- package/hooks/validar-formato-post-subagente.js +140 -140
- package/hooks/validar-memoria-hook.js +218 -218
- package/instintos/prompt-appendices.yaml +57 -57
- package/manifiestos/agent-output-schemas.json +57 -57
- package/manifiestos/modulos.json +1324 -1321
- package/manifiestos/skills-lock.json +1114 -1114
- package/package.json +2 -2
- package/plantillas/auditor-veto-template.md +105 -105
- package/plantillas/github-workflows/README.md +47 -47
- package/plantillas/github-workflows/release-please.yml +44 -44
- package/plantillas/github-workflows/swl-ci.yml +107 -107
- package/plantillas/github-workflows/swl-security.yml +51 -51
- package/plugin.json +353 -351
- package/reglas/analisis-previo-tareas-grandes.md +172 -172
- package/reglas/arreglar-al-detectar.md +147 -147
- package/reglas/fragmentos-compartidos.md +152 -152
- package/reglas/harness-claude-code.md +213 -213
- package/reglas/registro-componentes-nuevos.md +192 -0
- package/reglas/usar-context7.md +226 -226
- package/schemas/diary-entry.schema.json +80 -80
- package/scripts/actualizar.js +110 -1
- package/scripts/audit-tools/audit-history.js +330 -330
- package/scripts/audit-tools/bundle-tracker.js +290 -290
- package/scripts/audit-tools/canary-monitor.js +352 -352
- package/scripts/audit-tools/code-profiler.js +605 -605
- package/scripts/audit-tools/dep-doctor.js +320 -320
- package/scripts/audit-tools/env-validator.js +206 -206
- package/scripts/audit-tools/lib/fs-walk.js +48 -48
- package/scripts/audit-tools/lib/output.js +23 -23
- package/scripts/audit-tools/migration-checker.js +392 -392
- package/scripts/audit-tools/pentest-scanner.js +1436 -1436
- package/scripts/benchmark-memoria.js +167 -167
- package/scripts/configurar-branch-protection.js +418 -418
- package/scripts/derivar-feature-list.js +489 -489
- package/scripts/detectar-aprendizajes-duplicados.js +151 -151
- package/scripts/doctor.js +58 -4
- package/scripts/field-report.js +199 -199
- package/scripts/generar-checklists-consolidados.js +273 -273
- package/scripts/generar-inventario.js +420 -420
- package/scripts/generar-matriz-lenguajes.js +271 -271
- package/scripts/lib/artefactos-python.js +43 -43
- package/scripts/lib/benchmark-metrics.js +160 -160
- package/scripts/lib/budget-enforcer.js +252 -252
- package/scripts/lib/configurar-ci.js +380 -380
- package/scripts/lib/contadores-inventario.js +217 -217
- package/scripts/lib/detectar-stack-detallado.js +307 -307
- package/scripts/lib/diary-entry.js +234 -234
- package/scripts/lib/eval-metrics-store.js +218 -218
- package/scripts/lib/eval-quality.js +171 -171
- package/scripts/lib/eval-schemas.js +144 -144
- package/scripts/lib/eval-self-correct.js +106 -106
- package/scripts/lib/eval-validator.js +185 -185
- package/scripts/lib/expandir-targets.js +71 -71
- package/scripts/lib/jaccard-similarity.js +98 -98
- package/scripts/lib/longmemeval-runner.js +125 -125
- package/scripts/lib/mcp_config.py +127 -0
- package/scripts/lib/npm-version.js +261 -261
- package/scripts/lib/paquetes-conocidos.js +50 -50
- package/scripts/lib/prompt-builder.js +264 -264
- package/scripts/lib/rrf-fusion.js +175 -175
- package/scripts/lib/scoring-instintos.js +277 -277
- package/scripts/lib/semantic-search.js +252 -252
- package/scripts/lib/toml-merge.js +204 -204
- package/scripts/lib/transformadores/codex.js +375 -375
- package/scripts/lib/transformadores/cursor.js +359 -359
- package/scripts/limpiar-artefactos-python.js +131 -131
- package/scripts/mcp-orchestrator.py +8 -18
- package/scripts/mcp-pool-manager.py +12 -23
- package/scripts/mcp-server/README.md +170 -170
- package/scripts/mcp-server/auth.js +105 -105
- package/scripts/mcp-server/cache.js +106 -106
- package/scripts/mcp-server/telemetry.js +78 -78
- package/scripts/migrar-csv-a-array.js +168 -168
- package/scripts/migrar-fase-dominio.js +201 -201
- package/scripts/publicar.js +511 -511
- package/scripts/run-eval.js +141 -141
- package/scripts/validar-userland-vacio.js +110 -110
|
@@ -1,204 +1,204 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Merge mínimo de secciones TOML — zero-deps.
|
|
5
|
-
*
|
|
6
|
-
* Opera sobre el formato concreto de `~/.codex/config.toml` (OpenAI Codex CLI):
|
|
7
|
-
* [mcp_servers.<name>]
|
|
8
|
-
* command = "node"
|
|
9
|
-
* args = ["...", "..."]
|
|
10
|
-
* [mcp_servers.<name>.env]
|
|
11
|
-
* KEY = "value"
|
|
12
|
-
*
|
|
13
|
-
* Reglas:
|
|
14
|
-
* - NUNCA reescribe el archivo entero. Solo agrega o reemplaza la sección
|
|
15
|
-
* `[mcp_servers.<name>]` indicada (incluyendo sub-tabla `.env`).
|
|
16
|
-
* - Si el archivo no existe lo crea con permisos 0600.
|
|
17
|
-
* - Si el archivo tiene comentarios o secciones desconocidas, las preserva.
|
|
18
|
-
* - Bloque "owned" delimitado por marcadores `# SWL-MCP-BEGIN <name>` /
|
|
19
|
-
* `# SWL-MCP-END <name>` para permitir actualizaciones idempotentes.
|
|
20
|
-
*
|
|
21
|
-
* NO soporta:
|
|
22
|
-
* - TOML completo (arrays multilínea complejos, inline tables, etc.)
|
|
23
|
-
* - Multi-section nested tables fuera de `mcp_servers.*`
|
|
24
|
-
*
|
|
25
|
-
* Si en el futuro Codex publica un comando idempotente `codex mcp add --idempotent`
|
|
26
|
-
* podemos delegarle el trabajo y deprecar este helper.
|
|
27
|
-
*
|
|
28
|
-
* @module scripts/lib/toml-merge
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
const fs = require('fs');
|
|
32
|
-
const path = require('path');
|
|
33
|
-
|
|
34
|
-
const { atomicWriteSync } = require('../../hooks/lib/atomic-write');
|
|
35
|
-
|
|
36
|
-
const BEGIN_PREFIX = '# SWL-MCP-BEGIN';
|
|
37
|
-
const END_PREFIX = '# SWL-MCP-END';
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Serializa un servidor MCP en bloque TOML.
|
|
41
|
-
*
|
|
42
|
-
* @param {string} name - Nombre del server (identificador en config.toml).
|
|
43
|
-
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
44
|
-
* @returns {string} Bloque TOML con marcadores.
|
|
45
|
-
*/
|
|
46
|
-
function serializarServidor(name, cfg) {
|
|
47
|
-
if (!name || typeof name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
48
|
-
throw new Error(`Nombre de MCP server inválido: "${name}". Solo [a-zA-Z0-9_-].`);
|
|
49
|
-
}
|
|
50
|
-
if (!cfg || typeof cfg.command !== 'string' || cfg.command.length === 0) {
|
|
51
|
-
throw new Error(`MCP server "${name}" requiere "command" string no vacío.`);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const lineas = [];
|
|
55
|
-
lineas.push(`${BEGIN_PREFIX} ${name}`);
|
|
56
|
-
lineas.push(`[mcp_servers.${name}]`);
|
|
57
|
-
lineas.push(`command = ${tomlString(cfg.command)}`);
|
|
58
|
-
|
|
59
|
-
if (Array.isArray(cfg.args) && cfg.args.length > 0) {
|
|
60
|
-
const items = cfg.args.map(tomlString).join(', ');
|
|
61
|
-
lineas.push(`args = [${items}]`);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
if (cfg.env && typeof cfg.env === 'object' && Object.keys(cfg.env).length > 0) {
|
|
65
|
-
lineas.push('');
|
|
66
|
-
lineas.push(`[mcp_servers.${name}.env]`);
|
|
67
|
-
for (const [k, v] of Object.entries(cfg.env)) {
|
|
68
|
-
if (typeof v !== 'string') {
|
|
69
|
-
throw new Error(`MCP server "${name}" env.${k} debe ser string (recibido: ${typeof v}).`);
|
|
70
|
-
}
|
|
71
|
-
// Solo claves alfanuméricas/_ en env names — TOML restricción razonable
|
|
72
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
|
|
73
|
-
throw new Error(`MCP server "${name}" env key inválido: "${k}".`);
|
|
74
|
-
}
|
|
75
|
-
lineas.push(`${k} = ${tomlString(v)}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
lineas.push(`${END_PREFIX} ${name}`);
|
|
80
|
-
return lineas.join('\n');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Escapa un string para TOML usando comillas dobles.
|
|
85
|
-
* No usa basic-string raw para evitar pitfalls con backslashes.
|
|
86
|
-
*/
|
|
87
|
-
function tomlString(s) {
|
|
88
|
-
// TOML basic string: escape backslash, doblequote, control chars.
|
|
89
|
-
const escapado = String(s)
|
|
90
|
-
.replace(/\\/g, '\\\\')
|
|
91
|
-
.replace(/"/g, '\\"')
|
|
92
|
-
.replace(/\n/g, '\\n')
|
|
93
|
-
.replace(/\r/g, '\\r')
|
|
94
|
-
.replace(/\t/g, '\\t');
|
|
95
|
-
return `"${escapado}"`;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Inserta o actualiza un servidor MCP en `config.toml`.
|
|
100
|
-
*
|
|
101
|
-
* Idempotente: si el bloque ya existe con el mismo contenido, no escribe.
|
|
102
|
-
* Si existe con contenido distinto, lo reemplaza dentro de los marcadores.
|
|
103
|
-
* Si no existe, lo agrega al final del archivo precedido de línea en blanco.
|
|
104
|
-
*
|
|
105
|
-
* @param {string} rutaConfig - Path absoluto a config.toml (típicamente ~/.codex/config.toml).
|
|
106
|
-
* @param {string} name - Nombre del MCP server (clave de [mcp_servers.<name>]).
|
|
107
|
-
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
108
|
-
* @returns {{ accion: 'creado' | 'agregado' | 'actualizado' | 'sin-cambios', ruta: string }}
|
|
109
|
-
*/
|
|
110
|
-
function upsertMcpServer(rutaConfig, name, cfg) {
|
|
111
|
-
const bloqueNuevo = serializarServidor(name, cfg);
|
|
112
|
-
|
|
113
|
-
let existente = '';
|
|
114
|
-
let existia = false;
|
|
115
|
-
try {
|
|
116
|
-
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
117
|
-
existia = true;
|
|
118
|
-
} catch (err) {
|
|
119
|
-
if (err.code !== 'ENOENT') throw err;
|
|
120
|
-
// Archivo no existe — se crea
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
124
|
-
const endTag = `${END_PREFIX} ${name}`;
|
|
125
|
-
|
|
126
|
-
if (!existia) {
|
|
127
|
-
const dir = path.dirname(rutaConfig);
|
|
128
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
129
|
-
const contenido = `# config.toml de Codex CLI — gestionado parcialmente por swl-ses\n# Bloques delimitados por SWL-MCP-BEGIN/END son regenerables.\n\n${bloqueNuevo}\n`;
|
|
130
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
131
|
-
return { accion: 'creado', ruta: rutaConfig };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const idxBegin = existente.indexOf(beginTag);
|
|
135
|
-
const idxEnd = existente.indexOf(endTag);
|
|
136
|
-
|
|
137
|
-
// Caso 1: no existe el bloque → append al final
|
|
138
|
-
if (idxBegin === -1 || idxEnd === -1) {
|
|
139
|
-
const separador = existente.endsWith('\n') ? '\n' : '\n\n';
|
|
140
|
-
const contenido = existente + separador + bloqueNuevo + '\n';
|
|
141
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
142
|
-
return { accion: 'agregado', ruta: rutaConfig };
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Caso 2: existe — comparar contenido
|
|
146
|
-
// Calculamos fin REAL incluyendo el endTag completo.
|
|
147
|
-
const finBloqueExistente = idxEnd + endTag.length;
|
|
148
|
-
const bloqueExistente = existente.slice(idxBegin, finBloqueExistente);
|
|
149
|
-
|
|
150
|
-
if (bloqueExistente === bloqueNuevo) {
|
|
151
|
-
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const contenido = existente.slice(0, idxBegin) + bloqueNuevo + existente.slice(finBloqueExistente);
|
|
155
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
156
|
-
return { accion: 'actualizado', ruta: rutaConfig };
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Elimina un bloque MCP server por nombre. Idempotente: si no existe, no hace nada.
|
|
161
|
-
*
|
|
162
|
-
* @param {string} rutaConfig
|
|
163
|
-
* @param {string} name
|
|
164
|
-
* @returns {{ accion: 'eliminado' | 'sin-cambios', ruta: string }}
|
|
165
|
-
*/
|
|
166
|
-
function removeMcpServer(rutaConfig, name) {
|
|
167
|
-
let existente = '';
|
|
168
|
-
try {
|
|
169
|
-
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
170
|
-
} catch (err) {
|
|
171
|
-
if (err.code === 'ENOENT') return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
172
|
-
throw err;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
176
|
-
const endTag = `${END_PREFIX} ${name}`;
|
|
177
|
-
const idxBegin = existente.indexOf(beginTag);
|
|
178
|
-
const idxEnd = existente.indexOf(endTag);
|
|
179
|
-
|
|
180
|
-
if (idxBegin === -1 || idxEnd === -1) {
|
|
181
|
-
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// Quitar bloque + posible newline previo y posterior (cosmético)
|
|
185
|
-
let inicio = idxBegin;
|
|
186
|
-
let fin = idxEnd + endTag.length;
|
|
187
|
-
// Comer un \n previo si existe (no comer doble \n para preservar separadores entre secciones)
|
|
188
|
-
if (inicio > 0 && existente[inicio - 1] === '\n') inicio--;
|
|
189
|
-
if (fin < existente.length && existente[fin] === '\n') fin++;
|
|
190
|
-
|
|
191
|
-
const contenido = existente.slice(0, inicio) + existente.slice(fin);
|
|
192
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
193
|
-
return { accion: 'eliminado', ruta: rutaConfig };
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
module.exports = {
|
|
197
|
-
upsertMcpServer,
|
|
198
|
-
removeMcpServer,
|
|
199
|
-
serializarServidor,
|
|
200
|
-
// Para tests
|
|
201
|
-
_tomlString: tomlString,
|
|
202
|
-
BEGIN_PREFIX,
|
|
203
|
-
END_PREFIX,
|
|
204
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Merge mínimo de secciones TOML — zero-deps.
|
|
5
|
+
*
|
|
6
|
+
* Opera sobre el formato concreto de `~/.codex/config.toml` (OpenAI Codex CLI):
|
|
7
|
+
* [mcp_servers.<name>]
|
|
8
|
+
* command = "node"
|
|
9
|
+
* args = ["...", "..."]
|
|
10
|
+
* [mcp_servers.<name>.env]
|
|
11
|
+
* KEY = "value"
|
|
12
|
+
*
|
|
13
|
+
* Reglas:
|
|
14
|
+
* - NUNCA reescribe el archivo entero. Solo agrega o reemplaza la sección
|
|
15
|
+
* `[mcp_servers.<name>]` indicada (incluyendo sub-tabla `.env`).
|
|
16
|
+
* - Si el archivo no existe lo crea con permisos 0600.
|
|
17
|
+
* - Si el archivo tiene comentarios o secciones desconocidas, las preserva.
|
|
18
|
+
* - Bloque "owned" delimitado por marcadores `# SWL-MCP-BEGIN <name>` /
|
|
19
|
+
* `# SWL-MCP-END <name>` para permitir actualizaciones idempotentes.
|
|
20
|
+
*
|
|
21
|
+
* NO soporta:
|
|
22
|
+
* - TOML completo (arrays multilínea complejos, inline tables, etc.)
|
|
23
|
+
* - Multi-section nested tables fuera de `mcp_servers.*`
|
|
24
|
+
*
|
|
25
|
+
* Si en el futuro Codex publica un comando idempotente `codex mcp add --idempotent`
|
|
26
|
+
* podemos delegarle el trabajo y deprecar este helper.
|
|
27
|
+
*
|
|
28
|
+
* @module scripts/lib/toml-merge
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const fs = require('fs');
|
|
32
|
+
const path = require('path');
|
|
33
|
+
|
|
34
|
+
const { atomicWriteSync } = require('../../hooks/lib/atomic-write');
|
|
35
|
+
|
|
36
|
+
const BEGIN_PREFIX = '# SWL-MCP-BEGIN';
|
|
37
|
+
const END_PREFIX = '# SWL-MCP-END';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Serializa un servidor MCP en bloque TOML.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} name - Nombre del server (identificador en config.toml).
|
|
43
|
+
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
44
|
+
* @returns {string} Bloque TOML con marcadores.
|
|
45
|
+
*/
|
|
46
|
+
function serializarServidor(name, cfg) {
|
|
47
|
+
if (!name || typeof name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
48
|
+
throw new Error(`Nombre de MCP server inválido: "${name}". Solo [a-zA-Z0-9_-].`);
|
|
49
|
+
}
|
|
50
|
+
if (!cfg || typeof cfg.command !== 'string' || cfg.command.length === 0) {
|
|
51
|
+
throw new Error(`MCP server "${name}" requiere "command" string no vacío.`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const lineas = [];
|
|
55
|
+
lineas.push(`${BEGIN_PREFIX} ${name}`);
|
|
56
|
+
lineas.push(`[mcp_servers.${name}]`);
|
|
57
|
+
lineas.push(`command = ${tomlString(cfg.command)}`);
|
|
58
|
+
|
|
59
|
+
if (Array.isArray(cfg.args) && cfg.args.length > 0) {
|
|
60
|
+
const items = cfg.args.map(tomlString).join(', ');
|
|
61
|
+
lineas.push(`args = [${items}]`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (cfg.env && typeof cfg.env === 'object' && Object.keys(cfg.env).length > 0) {
|
|
65
|
+
lineas.push('');
|
|
66
|
+
lineas.push(`[mcp_servers.${name}.env]`);
|
|
67
|
+
for (const [k, v] of Object.entries(cfg.env)) {
|
|
68
|
+
if (typeof v !== 'string') {
|
|
69
|
+
throw new Error(`MCP server "${name}" env.${k} debe ser string (recibido: ${typeof v}).`);
|
|
70
|
+
}
|
|
71
|
+
// Solo claves alfanuméricas/_ en env names — TOML restricción razonable
|
|
72
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
|
|
73
|
+
throw new Error(`MCP server "${name}" env key inválido: "${k}".`);
|
|
74
|
+
}
|
|
75
|
+
lineas.push(`${k} = ${tomlString(v)}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
lineas.push(`${END_PREFIX} ${name}`);
|
|
80
|
+
return lineas.join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Escapa un string para TOML usando comillas dobles.
|
|
85
|
+
* No usa basic-string raw para evitar pitfalls con backslashes.
|
|
86
|
+
*/
|
|
87
|
+
function tomlString(s) {
|
|
88
|
+
// TOML basic string: escape backslash, doblequote, control chars.
|
|
89
|
+
const escapado = String(s)
|
|
90
|
+
.replace(/\\/g, '\\\\')
|
|
91
|
+
.replace(/"/g, '\\"')
|
|
92
|
+
.replace(/\n/g, '\\n')
|
|
93
|
+
.replace(/\r/g, '\\r')
|
|
94
|
+
.replace(/\t/g, '\\t');
|
|
95
|
+
return `"${escapado}"`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Inserta o actualiza un servidor MCP en `config.toml`.
|
|
100
|
+
*
|
|
101
|
+
* Idempotente: si el bloque ya existe con el mismo contenido, no escribe.
|
|
102
|
+
* Si existe con contenido distinto, lo reemplaza dentro de los marcadores.
|
|
103
|
+
* Si no existe, lo agrega al final del archivo precedido de línea en blanco.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} rutaConfig - Path absoluto a config.toml (típicamente ~/.codex/config.toml).
|
|
106
|
+
* @param {string} name - Nombre del MCP server (clave de [mcp_servers.<name>]).
|
|
107
|
+
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
108
|
+
* @returns {{ accion: 'creado' | 'agregado' | 'actualizado' | 'sin-cambios', ruta: string }}
|
|
109
|
+
*/
|
|
110
|
+
function upsertMcpServer(rutaConfig, name, cfg) {
|
|
111
|
+
const bloqueNuevo = serializarServidor(name, cfg);
|
|
112
|
+
|
|
113
|
+
let existente = '';
|
|
114
|
+
let existia = false;
|
|
115
|
+
try {
|
|
116
|
+
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
117
|
+
existia = true;
|
|
118
|
+
} catch (err) {
|
|
119
|
+
if (err.code !== 'ENOENT') throw err;
|
|
120
|
+
// Archivo no existe — se crea
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
124
|
+
const endTag = `${END_PREFIX} ${name}`;
|
|
125
|
+
|
|
126
|
+
if (!existia) {
|
|
127
|
+
const dir = path.dirname(rutaConfig);
|
|
128
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
129
|
+
const contenido = `# config.toml de Codex CLI — gestionado parcialmente por swl-ses\n# Bloques delimitados por SWL-MCP-BEGIN/END son regenerables.\n\n${bloqueNuevo}\n`;
|
|
130
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
131
|
+
return { accion: 'creado', ruta: rutaConfig };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const idxBegin = existente.indexOf(beginTag);
|
|
135
|
+
const idxEnd = existente.indexOf(endTag);
|
|
136
|
+
|
|
137
|
+
// Caso 1: no existe el bloque → append al final
|
|
138
|
+
if (idxBegin === -1 || idxEnd === -1) {
|
|
139
|
+
const separador = existente.endsWith('\n') ? '\n' : '\n\n';
|
|
140
|
+
const contenido = existente + separador + bloqueNuevo + '\n';
|
|
141
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
142
|
+
return { accion: 'agregado', ruta: rutaConfig };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Caso 2: existe — comparar contenido
|
|
146
|
+
// Calculamos fin REAL incluyendo el endTag completo.
|
|
147
|
+
const finBloqueExistente = idxEnd + endTag.length;
|
|
148
|
+
const bloqueExistente = existente.slice(idxBegin, finBloqueExistente);
|
|
149
|
+
|
|
150
|
+
if (bloqueExistente === bloqueNuevo) {
|
|
151
|
+
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const contenido = existente.slice(0, idxBegin) + bloqueNuevo + existente.slice(finBloqueExistente);
|
|
155
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
156
|
+
return { accion: 'actualizado', ruta: rutaConfig };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Elimina un bloque MCP server por nombre. Idempotente: si no existe, no hace nada.
|
|
161
|
+
*
|
|
162
|
+
* @param {string} rutaConfig
|
|
163
|
+
* @param {string} name
|
|
164
|
+
* @returns {{ accion: 'eliminado' | 'sin-cambios', ruta: string }}
|
|
165
|
+
*/
|
|
166
|
+
function removeMcpServer(rutaConfig, name) {
|
|
167
|
+
let existente = '';
|
|
168
|
+
try {
|
|
169
|
+
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
170
|
+
} catch (err) {
|
|
171
|
+
if (err.code === 'ENOENT') return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
176
|
+
const endTag = `${END_PREFIX} ${name}`;
|
|
177
|
+
const idxBegin = existente.indexOf(beginTag);
|
|
178
|
+
const idxEnd = existente.indexOf(endTag);
|
|
179
|
+
|
|
180
|
+
if (idxBegin === -1 || idxEnd === -1) {
|
|
181
|
+
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Quitar bloque + posible newline previo y posterior (cosmético)
|
|
185
|
+
let inicio = idxBegin;
|
|
186
|
+
let fin = idxEnd + endTag.length;
|
|
187
|
+
// Comer un \n previo si existe (no comer doble \n para preservar separadores entre secciones)
|
|
188
|
+
if (inicio > 0 && existente[inicio - 1] === '\n') inicio--;
|
|
189
|
+
if (fin < existente.length && existente[fin] === '\n') fin++;
|
|
190
|
+
|
|
191
|
+
const contenido = existente.slice(0, inicio) + existente.slice(fin);
|
|
192
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
193
|
+
return { accion: 'eliminado', ruta: rutaConfig };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = {
|
|
197
|
+
upsertMcpServer,
|
|
198
|
+
removeMcpServer,
|
|
199
|
+
serializarServidor,
|
|
200
|
+
// Para tests
|
|
201
|
+
_tomlString: tomlString,
|
|
202
|
+
BEGIN_PREFIX,
|
|
203
|
+
END_PREFIX,
|
|
204
|
+
};
|