nexakit 0.1.0 → 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.
Files changed (124) hide show
  1. package/.claude-plugin/marketplace.json +18 -1
  2. package/README.md +51 -30
  3. package/assets/brand/README.md +0 -2
  4. package/assets/runtime/package-lock.json +2 -2
  5. package/bin/agent-task.js +12 -10
  6. package/bin/agent-toolkit-gemini.js +11 -9
  7. package/bin/agent-toolkit-inbox.js +12 -10
  8. package/bin/agent-toolkit-mcp.js +14 -8
  9. package/bin/agent-toolkit.js +12 -9
  10. package/bin/nexakit.js +12 -9
  11. package/bin/project-memory-mcp.js +12 -9
  12. package/bin/project-memory.js +5 -3
  13. package/catalogs/generadores.json +936 -0
  14. package/{skills/depurar → catalogs/skills/vercel-composition-patterns}/LICENSE.txt +6 -6
  15. package/catalogs/skills/vercel-react-best-practices/LICENSE.txt +27 -0
  16. package/catalogs/skills.json +70 -35
  17. package/docs/skills/evidencias/2026-10-28-recomendador-preparacion.md +1 -1
  18. package/package.json +5 -3
  19. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -0
  20. package/plugins/nexakit-modelo/hooks/hooks.json +1 -0
  21. package/plugins/nexakit-modelo/hooks/register.js +48 -0
  22. package/plugins/nexakit-modelo/hooks/status.js +8 -0
  23. package/plugins/nexakit-modelo/tests/register.test.ts +21 -0
  24. package/plugins/nexakit-panel/.claude-plugin/plugin.json +1 -0
  25. package/plugins/nexakit-panel/README.md +20 -0
  26. package/plugins/nexakit-panel/hooks/hooks.json +1 -0
  27. package/plugins/nexakit-panel/hooks/lienzo.js +382 -0
  28. package/plugins/nexakit-panel/hooks/panel.js +273 -0
  29. package/plugins/nexakit-panel/hooks/redact.js +9 -0
  30. package/plugins/nexakit-panel/hooks/register.tsx +248 -0
  31. package/plugins/nexakit-panel/tests/lienzo.test.ts +142 -0
  32. package/plugins/nexakit-panel/tests/panel.test.ts +240 -0
  33. package/plugins/nexakit-panel/tests/register.test.ts +167 -0
  34. package/plugins/nexakit-panel/types/index.d.ts +41 -0
  35. package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -0
  36. package/plugins/nexakit-sesion/README.md +12 -0
  37. package/plugins/nexakit-sesion/hooks/aviso.js +38 -0
  38. package/plugins/nexakit-sesion/hooks/hooks.json +1 -0
  39. package/plugins/nexakit-sesion/hooks/register.js +28 -0
  40. package/plugins/nexakit-sesion/tests/register.test.ts +96 -0
  41. package/schemas/generators.schema.json +299 -0
  42. package/schemas/skill-catalog.schema.json +9 -2
  43. package/scripts/prepare-package.js +3 -0
  44. package/skills/cerrar-memoria/SKILL.md +6 -2
  45. package/skills/cerrar-memoria/references/cierre.md +5 -1
  46. package/skills/elegir-modelo/SKILL.md +68 -0
  47. package/skills/elegir-modelo/modelos.mjs +108 -0
  48. package/skills/gemini/SKILL.md +1 -1
  49. package/skills/project-handoff/SKILL.md +39 -12
  50. package/skills/project-handoff/references/handoff-template.md +24 -17
  51. package/skills/quality-gate/SKILL.md +6 -12
  52. package/skills/revisar/SKILL.md +6 -16
  53. package/skills/{desarrollo-con-pruebas/LICENSE.txt → revisar-skill/LICENSE-find-skills.txt} +5 -5
  54. package/skills/revisar-skill/SKILL.md +94 -0
  55. package/skills/revision-cruzada/SKILL.md +53 -475
  56. package/skills/web-design-guidelines/AGENTS.md +156 -0
  57. package/skills/{spec-driven-development → web-design-guidelines}/LICENSE.txt +1 -6
  58. package/skills/web-design-guidelines/SKILL.md +20 -30
  59. package/src/agent-models.js +53 -13
  60. package/src/brand.js +117 -0
  61. package/src/clean-command.js +29 -0
  62. package/src/clean-project-flow.js +105 -0
  63. package/src/clean-project.js +431 -0
  64. package/src/cli-executable.js +6 -4
  65. package/src/cli.js +16 -9
  66. package/src/connect.js +56 -4
  67. package/src/gemini-files.js +3 -3
  68. package/src/gemini-tools.js +23 -8
  69. package/src/generators-catalog.js +63 -0
  70. package/src/init.js +9 -1
  71. package/src/install-lock.js +127 -0
  72. package/src/install-registry.js +61 -0
  73. package/src/legacy-repair.js +71 -0
  74. package/src/link-states.js +172 -0
  75. package/src/memory-locator.js +118 -0
  76. package/src/missing-dependencies.js +21 -0
  77. package/src/model-command.js +147 -0
  78. package/src/panel-cli.js +182 -0
  79. package/src/project-root.js +60 -0
  80. package/src/project-signals.js +345 -0
  81. package/src/recommend-report.js +77 -0
  82. package/src/redact.js +9 -0
  83. package/src/review-instructions.js +211 -0
  84. package/src/review-policy.js +35 -0
  85. package/src/revision-adapters.js +157 -0
  86. package/src/revision-context.js +86 -0
  87. package/src/revision-isolation.js +222 -0
  88. package/src/revision-process.js +103 -0
  89. package/src/revision-provenance.js +89 -0
  90. package/src/revision-snapshot.js +120 -0
  91. package/src/revision.js +242 -0
  92. package/src/setup-apply.js +231 -0
  93. package/src/setup-plan.js +231 -0
  94. package/src/setup-state.js +284 -0
  95. package/src/setup-tui.js +647 -0
  96. package/src/skill-catalog-add.js +91 -0
  97. package/src/skill-catalog-audit.js +26 -27
  98. package/src/skill-files.js +39 -0
  99. package/src/skill-recommendations.js +344 -208
  100. package/src/skill-scan-report.js +14 -0
  101. package/src/skill-scan.js +178 -0
  102. package/src/stable-command.js +53 -0
  103. package/src/stable-install.js +222 -0
  104. package/src/superpowers.js +133 -0
  105. package/src/sync-apply.js +8 -5
  106. package/src/sync-files.js +2 -1
  107. package/src/terminal-text.js +68 -0
  108. package/src/toolkit-cli.js +397 -70
  109. package/src/toolkit-commands-guide.js +53 -39
  110. package/src/toolkit-setup.js +507 -110
  111. package/assets/brand/agent-toolkit-mark-v1.png +0 -0
  112. package/skills/depurar/SKILL.md +0 -69
  113. package/skills/depurar/agents/openai.yaml +0 -7
  114. package/skills/depurar/references/tecnicas-de-diagnostico.md +0 -37
  115. package/skills/desarrollo-con-pruebas/SKILL.md +0 -55
  116. package/skills/desarrollo-con-pruebas/agents/openai.yaml +0 -7
  117. package/skills/desarrollo-con-pruebas/references/buenas-pruebas.md +0 -33
  118. package/skills/estado/SKILL.md +0 -41
  119. package/skills/programar/SKILL.md +0 -19
  120. package/skills/spec-driven-development/SKILL.md +0 -48
  121. package/skills/spec-driven-development/agents/openai.yaml +0 -7
  122. package/skills/spec-driven-development/references/spec-template.md +0 -55
  123. package/skills/spec-driven-development/references/workflow.md +0 -70
  124. package/src/toolkit-tui.js +0 -961
@@ -0,0 +1,647 @@
1
+ import { createCleanProject } from './clean-project-flow.js';
2
+ // `npx nexakit`: three questions with the answer already suggested (skills, memory, agents) and one confirmation,
3
+ // in the style of `npm create vite`. Answered questions fold into one ◇ line; the active one uses ◆. The model,
4
+ // the drawing and the keys are pure, so every screen is tested as text; runSetupTui is the only part with I/O.
5
+ import os from 'node:os';
6
+ import fs from 'node:fs/promises';
7
+ import { planCleanProject, checkRequirements } from './clean-project.js';
8
+ import { runCleanCommand } from './clean-command.js';
9
+ import path from 'node:path';
10
+ import { applySetup } from './setup-apply.js';
11
+ import { AGENTS, AGENT_NAMES, buildConfirmation, joinNames, shortPath, suggestedAnswers } from './setup-plan.js';
12
+ import { gatherSetupState, inspectMemoryPath, memoryConnections } from './setup-state.js';
13
+ import { applyToolkitDetach, planToolkitDetach } from './skill-recommendations.js';
14
+ import { LOGO_WIDTH, colorLevel, levelOf, paint, renderLogo } from './brand.js';
15
+ import { cellWidth, fitLine, wrapText } from './terminal-text.js';
16
+
17
+ const KEYS = Object.freeze({
18
+ up: ['\x1b[A', 'k'], down: ['\x1b[B', 'j'], toggle: [' '], enter: ['\r', '\n'],
19
+ back: ['\x7f', '\x08', '\x1b[D'], left: ['\x1b[D'], right: ['\x1b[C'], quit: ['q', 'Q', '\x03']
20
+ });
21
+ const is = (key, name) => KEYS[name].includes(key);
22
+ const MENU = Object.freeze([
23
+ ['exit', 'No, salir'], ['skills', 'Añadir o quitar skills'], ['agents', 'Cambiar agentes'], ['detach', 'Quitar nexakit de este proyecto']
24
+ ]);
25
+ const MAX_DETECTED = 4;
26
+ // Languages and generic signals go after the frameworks the person will recognise.
27
+ const GENERIC_SIGNALS = new Set(['nodejs', 'python', 'rust', 'rest-api', 'vitest', 'mcp-sdk']);
28
+ const detectedLabels = signals => [...signals]
29
+ .sort((a, b) => GENERIC_SIGNALS.has(a.id) - GENERIC_SIGNALS.has(b.id) || a.label.localeCompare(b.label))
30
+ .map(signal => signal.label);
31
+
32
+ // ── Model ────────────────────────────────────────────────────────────────────────────────────────────────────────
33
+
34
+ function memoryOptions(model) {
35
+ const { state } = model;
36
+ if (!state.project.git) return ['later'];
37
+ return [state.memory.existing ? 'existing' : 'suggested', 'other', 'later'];
38
+ }
39
+
40
+ // Skills shown before "ver N más…": the suggested ones and any already chosen or installed.
41
+ function visibleSkills(model) {
42
+ const { state, answers, expanded } = model;
43
+ if (expanded) return state.skills;
44
+ return state.skills.filter(skill => skill.suggested || answers.skills.chosen.includes(skill.name) ||
45
+ Object.values(skill.links ?? {}).includes('installed'));
46
+ }
47
+ // What the info view says about trust: untested skills say so, and review observations are shown as written.
48
+ function skillTrust(skill) {
49
+ const lines = [];
50
+ if (skill.tested === false) lines.push('', ...wrapText('No probada: nadie ha comprobado aún que mejore el trabajo.', 60));
51
+ if (skill.reviewNotes) lines.push(...wrapText(`Observaciones: ${skill.reviewNotes}`, 60));
52
+ return lines;
53
+ }
54
+
55
+ function skillRows(model) {
56
+ const visible = visibleSkills(model);
57
+ const hidden = model.state.skills.length - visible.length;
58
+ return hidden > 0 ? [...visible.map(skill => ({ skill })), { more: hidden }] : visible.map(skill => ({ skill }));
59
+ }
60
+
61
+ export function createSetupModel(state) {
62
+ const answers = suggestedAnswers(state);
63
+ const confirmation = buildConfirmation(state, answers);
64
+ const model = {
65
+ state, answers, step: confirmation.allReady ? 'menu' : 'skills', flow: confirmation.allReady ? 'menu' : 'full',
66
+ cursor: 0, expanded: false, info: false, detail: false, confirmYes: true,
67
+ memoryInput: '', memoryError: null, progress: [], result: null, detachPlan: null, message: null
68
+ };
69
+ model.memoryChoice = answers.memory.decision === 'later' ? 'later'
70
+ : answers.memory.path === (state.memory.existing?.vaultPath ?? state.memory.suggestedPath) ? memoryOptions(model)[0] : 'other';
71
+ model.cleanChoice = {frontend:null,backend:null,database:null,mobile:null};
72
+ model.cleanGit = true; model.cleanFolder = state.creationRoot ?? state.project.root;
73
+ model.folderInput = ''; model.requirements = null; model.cleanPlan = null;
74
+ if (state.folder && !state.savedAnswers && !state.cleanProject) { model.step = 'mode'; model.cursor = state.folder.empty ? 0 : 1; }
75
+ if (state.cleanProject && state.cleanProject.status !== 'creado') model.step = 'clean-failed';
76
+ return model;
77
+ }
78
+
79
+ const cleanParts = ['frontend','backend','database','mobile'];
80
+ function technologyOptions(model, part) {
81
+ return model.state.generators.generators.filter(g=>g.part===part && (part!=='database' || model.cleanChoice.backend || g.id==='supabase'));
82
+ }
83
+ function goTechnology(model, part) { return go(model, `tech-${part}`, {cursor:part==='frontend'?0:technologyOptions(model,part).length}); }
84
+
85
+ // Leaving the skills question: a suggestion left unchecked is remembered as discarded, so it is not offered again.
86
+ function closeSkills(model) {
87
+ const chosen = model.state.skills.filter(skill => model.answers.skills.chosen.includes(skill.name)).map(skill => skill.name);
88
+ const discarded = new Set(model.answers.skills.discarded);
89
+ for (const skill of model.state.skills) {
90
+ if (chosen.includes(skill.name)) discarded.delete(skill.name);
91
+ else if (skill.suggested) discarded.add(skill.name);
92
+ }
93
+ return { ...model.answers, skills: { chosen, discarded: model.state.skills.map(s => s.name).filter(name => discarded.has(name)) } };
94
+ }
95
+
96
+ function memoryAnswer(model, choice) {
97
+ const { state } = model;
98
+ if (choice === 'later') return { decision: 'later' };
99
+ if (choice === 'existing') return { decision: 'path', path: state.memory.existing.vaultPath };
100
+ if (choice === 'suggested') return { decision: 'path', path: state.memory.suggestedPath };
101
+ return model.answers.memory;
102
+ }
103
+
104
+ const go = (model, step, extra = {}) => ({ ...model, step, cursor: 0, info: false, detail: false, message: null, ...extra });
105
+ const nextAfter = (model, step) => {
106
+ if (model.flow === 'menu') return 'confirm';
107
+ return { skills: 'memory', memory: 'agents', 'memory-path': 'agents', agents: 'confirm' }[step];
108
+ };
109
+ const previousOf = (model, step) => {
110
+ if (model.flow === 'menu') return step === 'confirm' ? model.menuEntry : 'menu';
111
+ return { memory: 'skills', 'memory-path': 'memory', agents: 'memory', confirm: 'agents' }[step];
112
+ };
113
+
114
+ export function handleSetupKey(model, key) {
115
+ if (key === '\x03') return ['creating','applying'].includes(model.step) ? {model} : { model, effect: 'exit' };
116
+ const { step } = model;
117
+
118
+ if (step === 'clean-folder') {
119
+ if (is(key,'enter')) {
120
+ const name = model.folderInput.trim();
121
+ if (!name || /[\\/:\x00-\x1f]/.test(name) || ['.','..','.git','.agent-toolkit'].includes(name)) return {model:{...model,message:'Escribe el nombre de una subcarpeta nueva.'}};
122
+ return {model,effect:'check-clean-folder',path:path.join(model.cleanFolder,name)};
123
+ }
124
+ if (key==='\x1b') return {model:go(model,'mode')};
125
+ if (key==='\x7f'||key==='\x08') return {model:{...model,folderInput:[...model.folderInput].slice(0,-1).join('')}};
126
+ if (/^[^\x00-\x1f\x7f]+$/u.test(key) && !key.startsWith('\x1b')) return {model:{...model,folderInput:model.folderInput+key,message:null}};
127
+ return {model};
128
+ }
129
+ if (step === 'memory-path') {
130
+ if (is(key, 'enter')) {
131
+ const raw = model.memoryInput.trim();
132
+ const expanded = raw === '~' || raw.startsWith('~/') ? path.join(model.state.homeDirectory, raw.slice(1)) : raw;
133
+ if (!path.isAbsolute(expanded)) return { model: { ...model, memoryError: 'Escribe una ruta completa, por ejemplo ~/memorias/mi-proyecto.' } };
134
+ return { model: { ...model, memoryError: null }, effect: 'check-path', path: path.resolve(expanded) };
135
+ }
136
+ if (key === '\x1b') return { model: go(model, 'memory', { cursor: memoryOptions(model).indexOf('other') }) };
137
+ if (key === '\x7f' || key === '\x08') return { model: { ...model, memoryInput: [...model.memoryInput].slice(0, -1).join('') } };
138
+ if (/^[^\x00-\x1f\x7f]+$/u.test(key) && !key.startsWith('\x1b')) return { model: { ...model, memoryInput: model.memoryInput + key, memoryError: null } };
139
+ return { model };
140
+ }
141
+
142
+ if (is(key, 'quit') && !['applying','creating'].includes(step)) return { model, effect: 'exit' };
143
+
144
+ if (step==='mode') {
145
+ if(is(key,'up')||is(key,'down')) return {model:{...model,cursor:model.cursor===0?1:0}};
146
+ if(is(key,'enter')) return {model:model.cursor===1?go(model,'skills'):model.state.folder.empty?goTechnology(model,'frontend'):go(model,'clean-folder')};
147
+ return {model};
148
+ }
149
+ if (step.startsWith('tech-')) {
150
+ const part=step.slice(5), options=technologyOptions(model,part);
151
+ if(is(key,'up')) return {model:{...model,cursor:Math.max(0,model.cursor-1)}};
152
+ if(is(key,'down')) return {model:{...model,cursor:Math.min(options.length,model.cursor+1)}};
153
+ if(is(key,'back')) { const i=cleanParts.indexOf(part);return {model:i?goTechnology(model,cleanParts[i-1]):go(model,'mode')}; }
154
+ if(is(key,'enter')) {
155
+ const next={...model,cleanChoice:{...model.cleanChoice,[part]:options[model.cursor]?.id ?? null}};
156
+ if(part==='backend' && !next.cleanChoice.backend) next.cleanChoice.database=null;
157
+ if(part!=='mobile') return {model:goTechnology(next,cleanParts[cleanParts.indexOf(part)+1])};
158
+ if(!next.cleanChoice.frontend && !next.cleanChoice.backend && !next.cleanChoice.mobile) return {model:{...next,message:'Elige al menos una parte.'}};
159
+ if(next.cleanChoice.database==='supabase' && !next.cleanChoice.frontend && !next.cleanChoice.backend) return {model:{...next,message:'Supabase necesita frontend o backend.'}};
160
+ return next.state.folder.insideGit ? {model:go(next,'clean-confirm'),effect:'prepare-clean'} : {model:go(next,'git')};
161
+ }
162
+ return {model};
163
+ }
164
+ if(step==='git') {
165
+ if(is(key,'toggle')||is(key,'left')||is(key,'right')) return {model:{...model,cleanGit:!model.cleanGit}};
166
+ if(is(key,'enter')) return {model:go(model,'clean-confirm'),effect:'prepare-clean'};
167
+ if(is(key,'back')) return {model:goTechnology(model,'mobile')};
168
+ return {model};
169
+ }
170
+ if(step==='clean-confirm') {
171
+ if(is(key,'back')) return {model:goTechnology(model,'mobile')};
172
+ if(is(key,'enter') && model.cleanPlan && model.requirements && model.requirements.every(r=>r.ok)) return {model,effect:'create-project',choice:model.cleanChoice,git:!model.state.folder.insideGit && model.cleanGit,folder:model.cleanFolder};
173
+ return {model};
174
+ }
175
+ if(step==='clean-failed') return is(key,'enter') ? {model:go(model,'skills')} : {model};
176
+ if(step==='creating') return {model};
177
+
178
+ if (step === 'done' || step === 'detached') return { model, effect: 'exit' };
179
+ if (step === 'applying') return { model };
180
+
181
+ if (step === 'menu') {
182
+ if (is(key, 'up')) return { model: { ...model, cursor: Math.max(0, model.cursor - 1) } };
183
+ if (is(key, 'down')) return { model: { ...model, cursor: Math.min(MENU.length - 1, model.cursor + 1) } };
184
+ if (is(key, 'enter')) {
185
+ const [choice] = MENU[model.cursor];
186
+ if (choice === 'exit') return { model, effect: 'exit' };
187
+ if (choice === 'detach') return { model, effect: 'detach-preview' };
188
+ return { model: go(model, choice, { menuEntry: choice, expanded: choice === 'skills' }) };
189
+ }
190
+ return { model };
191
+ }
192
+
193
+ if (step === 'detach-confirm') {
194
+ if (is(key, 'left') || is(key, 'right') || is(key, 'toggle')) return { model: { ...model, confirmYes: !model.confirmYes } };
195
+ if (is(key, 'enter')) return model.confirmYes ? { model, effect: 'detach-apply' } : { model: go(model, 'menu') };
196
+ if (key === '\x7f' || key === '\x08') return { model: go(model, 'menu') };
197
+ return { model };
198
+ }
199
+
200
+ if (step === 'skills') {
201
+ const rows = skillRows(model);
202
+ if (is(key, 'up')) return { model: { ...model, cursor: Math.max(0, model.cursor - 1), info: false } };
203
+ if (is(key, 'down')) return { model: { ...model, cursor: Math.min(rows.length - 1, model.cursor + 1), info: false } };
204
+ if (key === 'i') return { model: { ...model, info: !model.info } };
205
+ const row = rows[model.cursor];
206
+ if (is(key, 'toggle') || (is(key, 'enter') && row?.more)) {
207
+ if (row?.more) return { model: { ...model, expanded: true } };
208
+ const chosen = model.answers.skills.chosen.includes(row.skill.name)
209
+ ? model.answers.skills.chosen.filter(name => name !== row.skill.name)
210
+ : [...model.answers.skills.chosen, row.skill.name];
211
+ return { model: { ...model, answers: { ...model.answers, skills: { ...model.answers.skills, chosen } } } };
212
+ }
213
+ if (is(key, 'enter')) return { model: go({ ...model, answers: closeSkills(model) }, nextAfter(model, 'skills')) };
214
+ if (is(key, 'back') && model.flow === 'menu') return { model: go(model, 'menu') };
215
+ return { model };
216
+ }
217
+
218
+ if (step === 'memory') {
219
+ const options = memoryOptions(model);
220
+ const cursor = model.cursor;
221
+ if (is(key, 'up')) return { model: { ...model, cursor: Math.max(0, cursor - 1) } };
222
+ if (is(key, 'down')) return { model: { ...model, cursor: Math.min(options.length - 1, cursor + 1) } };
223
+ if (is(key, 'enter')) {
224
+ const choice = options[cursor];
225
+ if (choice === 'other') return { model: go(model, 'memory-path', { memoryChoice: 'other' }) };
226
+ return { model: go({ ...model, memoryChoice: choice, answers: { ...model.answers, memory: memoryAnswer(model, choice) } }, nextAfter(model, 'memory')) };
227
+ }
228
+ if (is(key, 'back')) return { model: go(model, previousOf(model, 'memory')) };
229
+ return { model };
230
+ }
231
+
232
+ if (step === 'agents') {
233
+ if (is(key, 'up')) return { model: { ...model, cursor: Math.max(0, model.cursor - 1) } };
234
+ if (is(key, 'down')) return { model: { ...model, cursor: Math.min(AGENTS.length - 1, model.cursor + 1) } };
235
+ if (is(key, 'toggle')) {
236
+ const agent = AGENTS[model.cursor];
237
+ const agents = model.answers.agents.includes(agent) ? model.answers.agents.filter(a => a !== agent) : [...model.answers.agents, agent];
238
+ return { model: { ...model, message: null, answers: { ...model.answers, agents: AGENTS.filter(a => agents.includes(a)) } } };
239
+ }
240
+ if (is(key, 'enter')) {
241
+ if (!model.answers.agents.length) return { model: { ...model, message: 'Marca al menos una IA.' } };
242
+ return { model: go(model, nextAfter(model, 'agents')) };
243
+ }
244
+ if (is(key, 'back')) return { model: go(model, previousOf(model, 'agents')) };
245
+ return { model };
246
+ }
247
+
248
+ if (step === 'confirm') {
249
+ if (key === 'd') return { model: { ...model, detail: !model.detail } };
250
+ if (is(key, 'left') || is(key, 'right') || is(key, 'toggle')) return { model: { ...model, confirmYes: !model.confirmYes } };
251
+ if (is(key, 'enter')) {
252
+ if (!model.confirmYes) return { model, effect: 'exit' };
253
+ return buildConfirmation(model.state, model.answers).blocks.length ? { model, effect: 'apply' } : { model, effect: 'exit' };
254
+ }
255
+ if (key === '\x7f' || key === '\x08') return { model: go(model, previousOf(model, 'confirm')) };
256
+ return { model };
257
+ }
258
+ return { model };
259
+ }
260
+
261
+ // The answer to "otra carpeta…" once its path was checked (an existing memory, a new one, or something not touched).
262
+ export function applyMemoryPathCheck(model, target, kind, connections) {
263
+ if (kind === 'invalid') return { ...model, memoryError: 'Esa carpeta no está vacía y no es una memoria; elige otra.' };
264
+ if (kind === 'foreign') return { ...model, memoryError: 'Esa es la memoria de otro proyecto; elige otra carpeta.' };
265
+ const memory = { ...model.state.memory, kinds: { ...model.state.memory.kinds, [target]: kind },
266
+ connections: { ...model.state.memory.connections, ...(connections && { [target]: connections }) } };
267
+ return go({ ...model, state: { ...model.state, memory }, answers: { ...model.answers, memory: { decision: 'path', path: target } } }, nextAfter(model, 'memory'));
268
+ }
269
+
270
+ // ── Drawing ──────────────────────────────────────────────────────────────────────────────────────────────────────
271
+
272
+ function folded(model) {
273
+ const { state, answers } = model;
274
+ const lines = [`Proyecto: ${state.project.displayName}${state.project.fromSubfolder ? ' (repositorio completo)' : ''}`];
275
+ const order = ['skills', 'memory', 'memory-path', 'agents', 'confirm'];
276
+ const at = order.indexOf(model.step);
277
+ if (model.step === 'skills' || at < 0) {
278
+ if (state.signals.length && model.step === 'skills') {
279
+ const labels = detectedLabels(state.signals);
280
+ lines.push(`Detecté: ${labels.slice(0, MAX_DETECTED).join(' · ')}${labels.length > MAX_DETECTED ? ` · y ${labels.length - MAX_DETECTED} más` : ''}`);
281
+ }
282
+ return lines;
283
+ }
284
+ if (model.flow === 'full' || model.menuEntry === 'skills') lines.push(`Skills: ${answers.skills.chosen.length} ${answers.skills.chosen.length === 1 ? 'elegida' : 'elegidas'}`);
285
+ if (model.flow === 'full' && at > order.indexOf('memory-path')) {
286
+ lines.push(answers.memory.decision === 'later' ? 'Memoria: ahora no' : `Memoria: ${shortPath(answers.memory.path, state.homeDirectory)}`);
287
+ }
288
+ if ((model.flow === 'full' && at > order.indexOf('agents')) || model.menuEntry === 'agents' && model.step === 'confirm') {
289
+ lines.push(`IA: ${joinNames(answers.agents.map(agent => AGENT_NAMES[agent]))}`);
290
+ }
291
+ return lines;
292
+ }
293
+
294
+ function question(model) {
295
+ const { state, answers } = model;
296
+ const home = state.homeDirectory;
297
+ if (model.step.startsWith('tech-')) {
298
+ const part=model.step.slice(5),labels={frontend:'frontend',backend:'backend',database:'base de datos',mobile:'app móvil'};
299
+ const options=[...technologyOptions(model,part).map(g=>g.label),`No quiero ${labels[part]}`];
300
+ return {title:`Elige ${labels[part]}`,body:options.map((text,i)=>({text:`${i===model.cursor?'●':'○'} ${text}`,cursor:i===model.cursor})),info:model.message?[model.message]:[],keys:'↑/↓ elegir · Enter continuar · q salir'};
301
+ }
302
+ switch (model.step) {
303
+ case 'mode': return {title:'¿Proyecto limpio o ya empezado?',body:['Proyecto limpio: crear la base desde cero','Ya empezado: preparar lo que hay'].map((text,i)=>({text:`${i===model.cursor?'●':'○'} ${text}`,cursor:i===model.cursor})),info:[],keys:'↑/↓ elegir · Enter continuar · q salir'};
304
+ case 'clean-folder': return {title:'Nombre de la subcarpeta nueva',body:[{text:model.folderInput+'▌'}],info:model.message?[model.message]:[],keys:'Enter comprobar · Esc volver'};
305
+ case 'git': return {title:'¿Inicio Git con un primer commit?',body:[{text:model.cleanGit?'● Sí / ○ No':'○ Sí / ● No'}],info:[],keys:'←/→ cambiar · Enter continuar · q salir'};
306
+ case 'clean-confirm': return {title:'¿Creo la base del proyecto?',body:(model.cleanPlan?.parts ?? []).flatMap(p=>[
307
+ {text:`${p.part}: ${p.id} → ${p.dir}`},...(p.commands.some(c=>/\.venv[\\/]/.test(c.argv[0]))?[{text:`${p.dir}: ${process.platform==='win32'?'py':'python3'} -m venv .venv`}]:[]),...p.commands.map(c=>({text:`${c.cwd}: ${c.argv.map(a=>JSON.stringify(a)).join(' ')}`})),
308
+ ...p.writes.map(w=>({text:`Crear ${w.path}: ${w.content}`})),{text:`Comprobar ${p.check.cwd}: ${p.check.argv.map(a=>JSON.stringify(a)).join(' ')}`}]),
309
+ info:model.requirements===null?['Comprobando requisitos…']:[...(model.state.folder?.insideGit?['El commit queda a tu cargo en el repositorio existente.']:model.cleanGit?['git init','git add -A','git commit -m \"chore: crear la base del proyecto con nexakit\"']:[]),...model.requirements.filter(r=>!r.ok).map(r=>`! Falta ${r.program} ${r.minVersion} o superior (${r.found ?? 'no encontrado'}).`),...(model.message?[model.message]:[])],keys:'Enter crear · retroceso volver · q salir'};
310
+ case 'creating': return {title:'Creando el proyecto…',body:(model.cleanProgress ?? []).map(text=>({text})),info:[],keys:'Espera a que termine la orden'};
311
+ case 'clean-failed': return {title:'La creación no terminó',body:[{text:model.cleanFailure ?? `Revisa el registro en .agent-toolkit/creacion.log.`}],info:['Se conserva lo creado. Enter prepara lo existente.'],keys:'Enter continuar · q salir'};
312
+ case 'skills': {
313
+ const rows = skillRows(model);
314
+ const width = Math.min(28, Math.max(...rows.filter(r => r.skill).map(r => r.skill.name.length), 10));
315
+ const body = rows.map((row, index) => ({
316
+ cursor: index === model.cursor,
317
+ text: row.more ? `◻ ver ${row.more} más…` : `${answers.skills.chosen.includes(row.skill.name) ? '◼' : '◻'} ${row.skill.name.padEnd(width)} ${row.skill.reason ?? ''}${row.skill.tested === false ? ' · no probada' : ''}`.trimEnd()
318
+ }));
319
+ const current = rows[model.cursor]?.skill;
320
+ const external = state.externalSkills?.length
321
+ ? ['', ...wrapText(`Se instalan aparte: ${state.externalSkills.map(ref => ref.name).join(', ')}`, 60)]
322
+ : [];
323
+ const missing = state.uncoveredTech?.length
324
+ ? ['', ...wrapText(`Sin skill en el catálogo: ${joinNames(state.uncoveredTech.map(item => item.label))}. Para buscar una, pide a tu IA «busca una skill para ${state.uncoveredTech[0].label}».`, 60)]
325
+ : [];
326
+ const info = [...(model.message?[model.message]:[]), ...(model.info && current ? ['', ...wrapText(current.summary, 60), ...skillTrust(current)] : []), ...external, ...missing];
327
+ return { title: '¿Qué skills quieres?', body, info, keys: 'espacio marcar · i qué hace · Enter seguir · q salir' };
328
+ }
329
+ case 'memory': {
330
+ const labels = {
331
+ existing: `Usar la memoria existente en ${shortPath(state.memory.existing?.vaultPath ?? '', home)}`,
332
+ suggested: `Sí, en ${shortPath(state.memory.suggestedPath, home)}`,
333
+ other: 'Sí, en otra carpeta…',
334
+ later: 'Ahora no'
335
+ };
336
+ const options = memoryOptions(model);
337
+ const body = options.map((option, index) => ({ cursor: index === model.cursor, text: `${index === model.cursor ? '●' : '○'} ${labels[option]}` }));
338
+ const info = state.project.git
339
+ ? ['', 'Guarda decisiones, arquitectura y entregas.', 'Se abre en Obsidian y la leen tus IA.']
340
+ : ['', 'La memoria necesita un repositorio Git; ejecuta `git init` para activarla.'];
341
+ return { title: state.memory.existing ? '¿Usar la memoria del proyecto?' : '¿Crear la memoria del proyecto?', body, info, keys: 'Enter seguir · ← volver · q salir' };
342
+ }
343
+ case 'memory-path':
344
+ return {
345
+ title: '¿En qué carpeta?', body: [{ cursor: true, text: `${model.memoryInput}▏` }],
346
+ info: model.memoryError ? ['', model.memoryError] : ['', 'Una carpeta vacía o que aún no existe, o una memoria tuya.'],
347
+ keys: 'Enter seguir · Esc volver'
348
+ };
349
+ case 'agents': {
350
+ const body = AGENTS.map((agent, index) => ({
351
+ cursor: index === model.cursor,
352
+ text: `${answers.agents.includes(agent) ? '◼' : '◻'} ${AGENT_NAMES[agent].padEnd(12)} ${state.agentsFound[agent] ? 'encontrado' : 'no encontrado'}`
353
+ }));
354
+ const info = [];
355
+ if (answers.agents.length >= 2) info.push('', 'Desde cualquiera puedes pedir revisión a otra.');
356
+ const unchecked = (state.savedAnswers?.agents ?? []).filter(agent => !answers.agents.includes(agent));
357
+ if (unchecked.length) info.push('', 'Desmarcar no desconecta nada; para quitarlo usa `npx nexakit quitar`.');
358
+ if (model.message) info.push('', model.message);
359
+ return { title: '¿Con qué IA trabajas?', body, info, keys: 'espacio marcar · Enter seguir · ← volver · q salir' };
360
+ }
361
+ case 'confirm': {
362
+ const confirmation = buildConfirmation(state, answers);
363
+ if (!confirmation.blocks.length) {
364
+ return { title: 'No hay nada que preparar', body: confirmation.lines.map(line => ({ text: ` ${line.mark} ${line.text}` })), info: [], keys: 'Enter salir · ← volver' };
365
+ }
366
+ const body = model.detail ? detailLines(model, confirmation) : confirmation.lines.map(line => ({ text: ` ${line.mark} ${line.text}` }));
367
+ const info = ['', 'No toco archivos tuyos. Se puede deshacer con', '`npx nexakit quitar`.', '',
368
+ `¿Lo preparo? ${model.confirmYes ? '● Sí / ○ No' : '○ Sí / ● No'}`];
369
+ return { title: 'Voy a preparar:', body, info, keys: 'Enter elegir · ←/→ cambiar · d detalle · Retroceso volver' };
370
+ }
371
+ default:
372
+ return null;
373
+ }
374
+ }
375
+
376
+ function detailLines(model, confirmation) {
377
+ const { state, answers } = model;
378
+ const home = state.homeDirectory;
379
+ const lines = [`Proyecto: ${shortPath(state.project.root, home)}`, `nexakit: ${shortPath(state.internal?.linkRoot ?? '', home)}`];
380
+ for (const name of answers.skills.chosen) {
381
+ const skill = state.skills.find(entry => entry.name === name);
382
+ lines.push(`skill ${name}${skill?.license ? ` (${skill.license})` : ''}: .claude ${skill?.links.claude} · .agents ${skill?.links.codex}`);
383
+ }
384
+ if (answers.memory.decision === 'path') lines.push(`memoria: ${shortPath(answers.memory.path, home)}`);
385
+ lines.push(`bloques: ${confirmation.blocks.map(block => block.id).join(', ')}`);
386
+ return lines.map(text => ({ text: ` ${text}` }));
387
+ }
388
+
389
+ function finalLines(model) {
390
+ const { state, answers, result } = model;
391
+ const lines = model.progress.map(item => `${item.phase === 'failed' ? '✗' : item.phase === 'done' ? '◇' : '◆'} ${item.label}${item.phase === 'start' ? '…' : ''}`);
392
+ if (result?.finalCheck) lines.push(`${result.finalCheck.ok ? '◇' : '!'} Comprobación final: ${result.finalCheck.message}`);
393
+ if (model.step !== 'done') return { lines, end: [] };
394
+ if (!result.ok) {
395
+ const reason = result.failed?.message ?? `Comprobación final: ${result.finalCheck?.message ?? ''}`;
396
+ return { lines, end: [result.failed ? 'Se detuvo aquí.' : 'Terminó, pero algo no quedó listo.', ...wrapText(reason, 60)] };
397
+ }
398
+ const names = joinNames(answers.agents.map(agent => AGENT_NAMES[agent]));
399
+ const end = ['Listo. Ahora:', ` 1. Cierra y abre ${names}`];
400
+ if (answers.memory.decision === 'path') {
401
+ end.push(' 2. Pídele: «lee la memoria y resume el proyecto»',
402
+ 'Abre la memoria en Obsidian: «Abrir carpeta como bóveda»', `→ ${shortPath(answers.memory.path, state.homeDirectory)}`);
403
+ } else {
404
+ end.push(' 2. Pídele lo que necesites: las skills ya están en el proyecto');
405
+ }
406
+ return { lines, end };
407
+ }
408
+
409
+ function renderBody(model, { columns, level }) {
410
+ const c = paint(level);
411
+ const width = Math.max(30, columns - 1);
412
+ const out = [];
413
+ const push = (text, paint = value => value) => out.push(paint(fitLine(text, width)));
414
+ // Rows that carry a path or a sentence wrap instead of being cut; continuation lines keep the │ gutter.
415
+ const pushWrapped = (prefix, text, paint = value => value, continuation = `│${' '.repeat(prefix.length - 1)}`) => {
416
+ const lines = wrapText(text, Math.max(10, width - Math.max(cellWidth(prefix), cellWidth(continuation))));
417
+ lines.forEach((line, index) => out.push(paint(`${index === 0 ? prefix : continuation}${line}`)));
418
+ };
419
+ const { state } = model;
420
+
421
+ if (model.step === 'menu') {
422
+ push(`◇ Proyecto: ${state.project.displayName}`, c.dim);
423
+ push('│');
424
+ const ready = buildConfirmation(state, model.answers).lines.filter(line => line.mark === '✓').map(line => line.text);
425
+ push('◇ Todo está listo', c.green);
426
+ for (const text of ready) push(`│ ${text}`, c.dim);
427
+ push('│');
428
+ push('◆ ¿Quieres cambiar algo?', c.accent);
429
+ MENU.forEach(([, label], index) => push(`│ ${index === model.cursor ? '❯' : ' '} ${index === model.cursor ? '●' : '○'} ${label}`, index === model.cursor ? c.accent : undefined));
430
+ push('└ Enter elegir · q salir', c.dim);
431
+ return out.join('\n');
432
+ }
433
+
434
+ if (['applying', 'done'].includes(model.step)) {
435
+ const agents = joinNames(model.answers.agents.map(agent => AGENT_NAMES[agent]));
436
+ const memory = model.answers.memory.decision === 'path' ? ' · memoria' : '';
437
+ push(`◇ ${state.project.displayName} · ${model.answers.skills.chosen.length} ${model.answers.skills.chosen.length === 1 ? 'skill' : 'skills'}${memory} · ${agents}`, c.dim);
438
+ push('│');
439
+ const { lines, end } = finalLines(model);
440
+ for (const line of lines) push(line, line.startsWith('✗') ? c.red : line.startsWith('◆') ? c.accent : undefined);
441
+ if (end.length) {
442
+ push('│');
443
+ push(`└ ${end[0]}`, model.result?.ok ? c.green : c.red);
444
+ for (const line of end.slice(1)) push(` ${line}`);
445
+ }
446
+ return out.join('\n');
447
+ }
448
+
449
+ if (model.step === 'detach-confirm' || model.step === 'detached') {
450
+ push(`◇ Proyecto: ${state.project.displayName}`, c.dim);
451
+ push('│');
452
+ const plan = model.detachPlan;
453
+ const removable = (plan?.items ?? []).filter(item => item.action !== 'conflict').length;
454
+ const kept = (plan?.items ?? []).filter(item => item.action === 'conflict').length;
455
+ if (model.step === 'detached') {
456
+ push('◇ nexakit quitado de este proyecto', c.green);
457
+ push(`└ Se quitaron ${removable} enlaces. La memoria y tus IA no se tocaron.`);
458
+ return out.join('\n');
459
+ }
460
+ push('◆ ¿Quitar nexakit de este proyecto?', c.accent);
461
+ push(`│ − ${removable} skills del proyecto y su bloque en .gitignore`);
462
+ if (kept) push(`│ ! ${kept} carpetas tuyas se quedan como están`);
463
+ push('│ La memoria y la configuración de tus IA no se tocan.');
464
+ push('│');
465
+ push(`│ ${model.confirmYes ? '● Sí / ○ No' : '○ Sí / ● No'}`);
466
+ push('└ Enter elegir · ←/→ cambiar', c.dim);
467
+ return out.join('\n');
468
+ }
469
+
470
+ for (const line of folded(model)) {
471
+ if (level !== 'none' && line.startsWith('Detecté: ')) {
472
+ const labels = line.slice('Detecté: '.length).split(' · ');
473
+ if (cellWidth(`◇ Detecté: ${labels.map((label) => ` ${label} `).join(' ')}`) <= width) {
474
+ out.push(`${c.dim('◇ Detecté:')} ${labels.map((label) => (/^y \d+ más$/u.test(label) ? c.dim(label) : c.chip(label))).join(' ')}`);
475
+ continue;
476
+ }
477
+ }
478
+ pushWrapped('◇ ', line, c.dim, ' ');
479
+ }
480
+ push('│');
481
+ const q = question(model);
482
+ push(`◆ ${q.title}`, c.accent);
483
+ for (const row of q.body) {
484
+ const text = row.text.startsWith(' ') ? row.text.slice(1) : row.text;
485
+ const marker = row.text.startsWith(' ') && /^ [+−↻!✓] /u.test(row.text) ? `│ ${text.slice(0, 2)}` : `│ ${row.cursor ? '❯' : ' '} `;
486
+ const shown = marker.startsWith('│ ') && /^[+−↻!✓] /u.test(text) ? text.slice(2) : text;
487
+ // A checkbox or radio row continues under its label, not under the box.
488
+ const continuation = /^[◼◻●○] /u.test(shown) ? `│${' '.repeat(marker.length + 1)}` : undefined;
489
+ pushWrapped(marker, shown, row.cursor ? c.accent : undefined, continuation);
490
+ }
491
+ for (const line of q.info) {
492
+ if (!line) push('│');
493
+ else pushWrapped('│ ', line, line.startsWith('¿Lo preparo') ? c.bold : c.dim);
494
+ }
495
+ pushWrapped('└ ', q.keys, c.dim, ' ');
496
+ return out.join('\n');
497
+ }
498
+
499
+ // ── Loop ─────────────────────────────────────────────────────────────────────────────────────────────────────────
500
+
501
+ const STEP_NUMBER = Object.freeze({ skills: 1, memory: 2, 'memory-path': 2, agents: 3, confirm: 4 });
502
+ const STEP_COUNT = 4;
503
+ const TAGLINE = 'Tus skills. Tu memoria. Tus IA trabajando juntas.';
504
+ const TAGLINE_SHORT = 'Skills, memoria e IA, juntas.';
505
+
506
+ // El logo solo sale cuando hay color, ancho y alto de sobra; si no, queda la línea de siempre con el paso.
507
+ function renderHeader(model, { columns, rows, level, bodyRows }) {
508
+ const c = paint(level);
509
+ const width = Math.max(30, columns - 1);
510
+ const version = model.state.version ? ` v${model.state.version}` : '';
511
+ const number = model.flow === 'full' ? STEP_NUMBER[model.step] : undefined;
512
+ const steps = number ? `Paso ${number} de ${STEP_COUNT}` : '';
513
+ const dots = number ? Array.from({ length: STEP_COUNT }, (_, index) => (index < number ? '●' : '○')).join('') : '';
514
+ const celebrates = model.step === 'done' && model.result?.ok;
515
+
516
+ if (level !== 'none' && columns >= LOGO_WIDTH + 4 && (['skills', 'menu'].includes(model.step) || celebrates)) {
517
+ const tagline = fitLine(width - 2 >= cellWidth(TAGLINE) ? TAGLINE : TAGLINE_SHORT, width - 2);
518
+ const sub = celebrates ? `✓ Todo listo · ${version.trim()}` : `${version.trim()}${steps ? ` · ${steps} ${dots}` : ''}`;
519
+ const fitted = fitLine(sub, width - 2);
520
+ const painted = fitted === sub && steps && !celebrates
521
+ ? `${c.dim(`${version.trim()} · ${steps} `)}${c.accent(dots.slice(0, number))}${c.dim(dots.slice(number))}`
522
+ : celebrates ? c.green(fitted) : c.dim(fitted);
523
+ const block = ['', ...renderLogo(level).map((line) => ` ${line}`), '', ` ${c.soft(tagline)}`, ` ${painted}`, ''];
524
+ if (!rows || block.length + bodyRows <= rows - 1) return block;
525
+ }
526
+
527
+ const plain = `◆ nexakit${version}${steps ? ` · ${steps} ${dots}` : ''}`;
528
+ if (cellWidth(plain) > width) return [c.bold(fitLine(plain, width))];
529
+ const tail = steps ? `${c.dim(` · ${steps} `)}${c.accent(dots.slice(0, number))}${c.dim(dots.slice(number))}` : '';
530
+ return [`${c.accent('◆ nexakit')}${c.dim(version)}${tail}`];
531
+ }
532
+
533
+ export function renderSetupFrame(model, { columns = 80, rows, color = true } = {}) {
534
+ const level = levelOf(color);
535
+ const body = renderBody(model, { columns, level });
536
+ const header = renderHeader(model, { columns, rows, level, bodyRows: body.split('\n').length });
537
+ return `${header.join('\n')}\n${body}`;
538
+ }
539
+
540
+ export async function runSetupTui({ input = process.stdin, output = process.stdout, options = {}, applyOptions = {}, gather = gatherSetupState } = {}) {
541
+ const level = colorLevel(output);
542
+ const home = options.homeDirectory ?? os.homedir();
543
+ output.write('Revisando el proyecto…\n');
544
+ let model = createSetupModel(await gather(options));
545
+ let exitCode = 0;
546
+ let creationController;
547
+ // The questions live on the alternate screen, where moving home and erasing redraws in place: clearing the
548
+ // normal screen pushes a copy of every frame into the scrollback in most terminals. On exit the last frame is
549
+ // printed once on the normal screen, so the result stays readable.
550
+ const frame = () => renderSetupFrame(model, { columns: output.columns || 80, rows: output.rows, color: level });
551
+ const render = () => output.write(`\x1b[H\x1b[J${frame()}\n`);
552
+
553
+ return new Promise(resolve => {
554
+ let closed = false;
555
+ let chain = Promise.resolve();
556
+ const cleanup = code => {
557
+ if (closed) return;
558
+ closed = true;
559
+ input.off?.('data', onData);
560
+ output.off?.('resize', render);
561
+ try { if (typeof input.setRawMode === 'function') input.setRawMode(false); } catch {}
562
+ try { input.pause?.(); } catch {}
563
+ output.write(`\x1b[?1049l${frame()}\n\x1b[?25h`);
564
+ resolve(code);
565
+ };
566
+
567
+ const runEffect = async (effect, extra) => {
568
+ if (effect === 'exit') return cleanup(exitCode);
569
+ if (effect === 'check-path') {
570
+ const kind = await inspectMemoryPath(extra.path, { repositoryRoot: model.state.project.root });
571
+ const connections = ['memory', 'new'].includes(kind)
572
+ ? await memoryConnections(extra.path, { homeDirectory: home, codexHome: model.state.internal.codexHome, runCommand: options.runCommand,
573
+ nodePath: model.state.internal.nodePath, toolkitRoot: model.state.internal.linkRoot, agentsFound: model.state.agentsFound,
574
+ kind, mcpName: `${model.state.project.id}-memory` })
575
+ : null;
576
+ model = applyMemoryPathCheck(model, extra.path, kind, connections);
577
+ } else if (effect === 'check-clean-folder') {
578
+ const exists=await fs.lstat(extra.path).catch(e=>{if(e.code==='ENOENT')return null;throw e;});
579
+ model=exists?{...model,message:'Esa carpeta ya existe. Elige otra.'}:goTechnology({...model,cleanFolder:extra.path},'frontend');
580
+ } else if (effect === 'prepare-clean') {
581
+ try {
582
+ const cleanPlan=planCleanProject({choice:model.cleanChoice,catalog:model.state.generators,name:path.basename(model.cleanFolder)});
583
+ const requirements=await checkRequirements(cleanPlan,model.state.generators,{runCommand:options.runCommand ?? runCleanCommand});
584
+ model={...model,cleanPlan,requirements};
585
+ } catch(e) { model={...model,cleanPlan:null,requirements:[],message:e.message}; }
586
+ } else if (effect === 'create-project') {
587
+ model={...model,step:'creating',cleanProgress:[]}; creationController=new AbortController(); render();
588
+ const result=await createCleanProject({...extra,insideGit:model.state.folder.insideGit},{options,gather,signal:creationController.signal,runCommand:options.runCommand ?? runCleanCommand,
589
+ onProgress:(part,argv)=>{model={...model,cleanProgress:[`${part}: ${argv.join(' ')}`]};render();}});
590
+ if(result.state){options={...options,start:result.state.project.root};model=createSetupModel(result.state);}
591
+ if(result.ok){model={...model,step:'skills',flow:'full',message:result.gitResult==='sin-git'?'Git no está instalado; seguimos sin él.':null};}
592
+ else{exitCode=1;model={...model,step:'clean-failed',cleanFailure:`${result.failed.part}: ${result.failed.argv.join(' ')}\n${result.failed.output}\nRegistro: .agent-toolkit/creacion.log`};}
593
+ } else if (effect === 'apply') {
594
+ const labels = Object.fromEntries(buildConfirmation(model.state, model.answers).blocks.map(block => [block.id, block.label]));
595
+ model = { ...model, step: 'applying', progress: [] };
596
+ render();
597
+ const result = await applySetup(options, model.answers, {
598
+ ...applyOptions,
599
+ onProgress: (id, phase) => {
600
+ const progress = model.progress.filter(item => item.id !== id);
601
+ model = { ...model, progress: [...progress, { id, label: labels[id] ?? id, phase }] };
602
+ render();
603
+ }
604
+ });
605
+ exitCode = result.ok ? 0 : 1;
606
+ model = { ...model, step: 'done', result };
607
+ } else if (effect === 'detach-preview') {
608
+ const { catalog, toolkitRoot } = model.state.internal;
609
+ const plan = await planToolkitDetach({ projectRoot: model.state.project.root, catalog, toolkitRoot, homeDirectory: home });
610
+ model = { ...model, step: 'detach-confirm', detachPlan: plan, confirmYes: false };
611
+ } else if (effect === 'detach-apply') {
612
+ await applyToolkitDetach(model.detachPlan);
613
+ model = { ...model, step: 'detached' };
614
+ }
615
+ render();
616
+ };
617
+
618
+ const handle = async key => {
619
+ if (closed) return;
620
+ const { model: next, effect, ...extra } = handleSetupKey(model, key);
621
+ model = next;
622
+ if (effect) await runEffect(effect, extra);
623
+ else render();
624
+ };
625
+ const onData = chunk => {
626
+ const key = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
627
+ if(key === '\x03' && model.step==='creating'){creationController?.abort();return;}
628
+ if (key === '\x03' && !['applying','creating'].includes(model.step)) return cleanup(exitCode);
629
+ chain = chain.then(() => handle(key)).catch(error => {
630
+ model = { ...model, step: 'done', result: { ok: false, failed: { message: error instanceof Error ? error.message : String(error) } } };
631
+ exitCode = 1;
632
+ render();
633
+ });
634
+ };
635
+
636
+ try {
637
+ output.write('\x1b[?1049h\x1b[?25l');
638
+ if (typeof input.setRawMode === 'function') input.setRawMode(true);
639
+ input.resume?.();
640
+ input.on('data', onData);
641
+ output.on?.('resize', render);
642
+ render();
643
+ } catch {
644
+ cleanup(1);
645
+ }
646
+ });
647
+ }