orca-multiagent-kit 1.5.0 → 1.7.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 (110) hide show
  1. package/AI_INSTALL.md +4 -3
  2. package/CHANGELOG.md +70 -1
  3. package/GUIA.html +11 -9
  4. package/README.md +23 -23
  5. package/VERSION +1 -1
  6. package/bin/backup.js +44 -0
  7. package/bin/fetch.js +243 -0
  8. package/bin/hooks.js +187 -0
  9. package/bin/omk.js +134 -51
  10. package/bin/run/cleanup.js +402 -0
  11. package/bin/run/git.js +641 -0
  12. package/bin/run/glob.js +193 -0
  13. package/bin/run/ledger.js +243 -0
  14. package/bin/run/plan.js +328 -0
  15. package/bin/run/units.js +101 -0
  16. package/bin/run/util.js +116 -0
  17. package/bin/run.js +224 -0
  18. package/bin/setup.js +81 -8
  19. package/bin/sync.js +222 -0
  20. package/bin/team.js +353 -0
  21. package/bin/ui.js +8 -4
  22. package/bin/update.js +169 -0
  23. package/core/AGENTS.md +7 -7
  24. package/docs/EJECUTABLE.md +5 -4
  25. package/docs/MANUAL.md +16 -3
  26. package/docs/ORQUESTADOR.md +59 -1
  27. package/docs/PLUGIN-ORCA.md +131 -24
  28. package/hooks/orca-gate.cjs +402 -0
  29. package/install.sh +26 -13
  30. package/orca-plugin/README.md +7 -1
  31. package/orca-plugin/assets/logos/README.md +10 -0
  32. package/orca-plugin/assets/logos/agent.png +0 -0
  33. package/orca-plugin/assets/logos/aider.png +0 -0
  34. package/orca-plugin/assets/logos/amp.png +0 -0
  35. package/orca-plugin/assets/logos/antigravity.png +0 -0
  36. package/orca-plugin/assets/logos/claude.png +0 -0
  37. package/orca-plugin/assets/logos/cline.png +0 -0
  38. package/orca-plugin/assets/logos/codex.png +0 -0
  39. package/orca-plugin/assets/logos/copilot.png +0 -0
  40. package/orca-plugin/assets/logos/cursor.png +0 -0
  41. package/orca-plugin/assets/logos/devin.png +0 -0
  42. package/orca-plugin/assets/logos/droid.png +0 -0
  43. package/orca-plugin/assets/logos/gemini.png +0 -0
  44. package/orca-plugin/assets/logos/goose.png +0 -0
  45. package/orca-plugin/assets/logos/grok.png +0 -0
  46. package/orca-plugin/assets/logos/kimi.png +0 -0
  47. package/orca-plugin/assets/logos/kiro.png +0 -0
  48. package/orca-plugin/assets/logos/opencode.png +0 -0
  49. package/orca-plugin/assets/logos/qwen-code.png +0 -0
  50. package/orca-plugin/orca-plugin.json +25 -7
  51. package/orca-plugin/src/icons.test.ts +14 -0
  52. package/orca-plugin/src/icons.ts +30 -0
  53. package/orca-plugin/src/kit.test.ts +491 -22
  54. package/orca-plugin/src/kit.ts +687 -37
  55. package/orca-plugin/src/models.test.ts +28 -0
  56. package/orca-plugin/src/models.ts +29 -0
  57. package/orca-plugin/src/node.d.ts +40 -0
  58. package/orca-plugin/src/panel-state.ts +36 -0
  59. package/orca-plugin/src/panel.check.ts +71 -0
  60. package/orca-plugin/src/panel.test.tsx +296 -33
  61. package/orca-plugin/src/panel.tsx +501 -81
  62. package/orca-plugin/src/plan-card.test.ts +99 -0
  63. package/orca-plugin/src/plan-card.ts +107 -0
  64. package/orca-plugin/src/protocol.ts +205 -5
  65. package/orca-plugin/src/tabs/autonomy.tsx +72 -0
  66. package/orca-plugin/src/tabs/history.test.tsx +79 -0
  67. package/orca-plugin/src/tabs/history.tsx +119 -0
  68. package/orca-plugin/src/tabs/notices.test.tsx +184 -0
  69. package/orca-plugin/src/tabs/notices.tsx +274 -0
  70. package/orca-plugin/src/tabs/worktrees.test.tsx +131 -0
  71. package/orca-plugin/src/tabs/worktrees.tsx +138 -0
  72. package/orca-plugin/src/ui/action-card.tsx +112 -0
  73. package/orca-plugin/src/ui/agent-icon.tsx +13 -0
  74. package/orca-plugin/src/worker/actions.test.ts +288 -0
  75. package/orca-plugin/src/worker/actions.ts +292 -0
  76. package/orca-plugin/src/worker/context.test.ts +32 -0
  77. package/orca-plugin/src/worker/context.ts +95 -0
  78. package/orca-plugin/src/worker/history.test.ts +149 -0
  79. package/orca-plugin/src/worker/history.ts +181 -0
  80. package/orca-plugin/src/worker/notices.test.ts +356 -0
  81. package/orca-plugin/src/worker/notices.ts +288 -0
  82. package/orca-plugin/src/worker/system.test.ts +58 -0
  83. package/orca-plugin/src/worker/system.ts +122 -0
  84. package/orca-plugin/src/worker/worktrees.test.ts +177 -0
  85. package/orca-plugin/src/worker/worktrees.ts +188 -0
  86. package/orca-plugin/src/worker.test.ts +285 -24
  87. package/orca-plugin/src/worker.ts +344 -64
  88. package/output-styles/csr-minimal.md +1 -0
  89. package/package.json +3 -3
  90. package/rules/50-done-gate.md +1 -1
  91. package/rules/95-multi-agent.md +13 -3
  92. package/skills/kit-init/SKILL.md +16 -4
  93. package/skills/orca/SKILL.md +28 -5
  94. package/skills/orca/references/adapters/artifact.md +2 -0
  95. package/skills/orca/references/adapters/chat.md +2 -0
  96. package/skills/orca/references/adapters/native-plan.md +6 -0
  97. package/skills/orca/references/adapters/plan-file.md +2 -0
  98. package/skills/orca/references/engine-manual.md +7 -5
  99. package/skills/orca/references/engine-orca.md +1 -0
  100. package/skills/orca/references/engine-subagents.md +4 -4
  101. package/skills/orca/references/integrate.md +14 -2
  102. package/skills/orca/references/ledger.md +1 -1
  103. package/skills/orca/references/olimpo.md +2 -1
  104. package/skills/orca/references/plan-card.md +45 -0
  105. package/skills/orca/references/plan.md +2 -1
  106. package/skills/orca/references/units.md +1 -1
  107. package/skills/orca/references/worker-contract.md +2 -2
  108. package/templates/AGENTS.md +2 -2
  109. package/templates/CLAUDE.md +1 -1
  110. package/templates/claude-settings.json +25 -0
package/bin/hooks.js ADDED
@@ -0,0 +1,187 @@
1
+ // Hooks de Claude Code del kit. Los de templates/claude-settings.json recuerdan la puerta de reparto en
2
+ // cada mensaje y al aprobar un plan; van en la configuración global y en la de cada proyecto. En la
3
+ // global va además la puerta obligatoria (hooks/orca-gate.cjs, instalada en ~/.agents/hooks): deniega
4
+ // editar hasta que el veredicto de la skill orca esté en el chat y, si reparte, hasta que la persona
5
+ // responda al plan. Se fusionan en un settings.json que ya existe sin tocar nada más: solo se añaden o
6
+ // se ponen al día las entradas marcadas con el nombre del kit.
7
+ 'use strict';
8
+
9
+ const { spawnSync } = require('node:child_process');
10
+ const fs = require('node:fs');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+
14
+ // Herramientas que la puerta vigila: las de edición, las de shell y las que lanzan subagentes.
15
+ const GATE_MATCHER = 'Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell|Agent|Task';
16
+ const GATE_TIMEOUT_S = 10;
17
+ // La ruta va entre comillas dobles en una orden que ejecutan bash o PowerShell: nada que expandan.
18
+ const SAFE_PATH = /^[\w .:/()+@~-]+$/;
19
+
20
+ const KIT_MARK = '[Orca Multiagent Kit]';
21
+
22
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ const isKitHook = (hook) => isObject(hook) && typeof hook.command === 'string' && hook.command.includes(KIT_MARK);
24
+
25
+ /**
26
+ * La carpeta de configuración de Claude Code, como la resuelve install.sh: CLAUDE_CONFIG_DIR, salvo
27
+ * que sea un perfil que gestiona la app Orca (importa ~/.claude y no se toca).
28
+ */
29
+ function claudeDir(env = process.env, home = env.HOME || os.homedir()) {
30
+ const dir = env.CLAUDE_CONFIG_DIR;
31
+ const orcaProfile = dir && (/[\\/]orca[\\/]claude-profiles[\\/]/i.test(dir) || dir === env.ORCA_CLAUDE_INJECTED_CONFIG_DIR);
32
+ return dir && !orcaProfile ? dir : path.join(home, '.claude');
33
+ }
34
+
35
+ /**
36
+ * `settings` con los hooks del kit de `template`. Devuelve `{ settings, changed }`, o `null` si la
37
+ * clave `hooks` de `settings` no tiene la forma esperada (no se toca). Los hooks que no son del kit
38
+ * se conservan tal cual, también dentro de una entrada compartida con uno del kit.
39
+ */
40
+ function mergeKitHooks(settings, template) {
41
+ const current = settings.hooks === undefined ? {} : settings.hooks;
42
+ if (!isObject(current) || !isObject(template.hooks)) return null;
43
+ const hooks = { ...current };
44
+ let changed = false;
45
+ for (const [event, entries] of Object.entries(template.hooks)) {
46
+ if (hooks[event] !== undefined && !Array.isArray(hooks[event])) return null;
47
+ const list = [...(hooks[event] || [])];
48
+ for (const entry of entries) {
49
+ const at = list.findIndex((existing) => isObject(existing) && (existing.matcher || '') === (entry.matcher || '')
50
+ && Array.isArray(existing.hooks) && existing.hooks.some(isKitHook));
51
+ if (at === -1) { list.push(entry); changed = true; continue; }
52
+ const merged = { ...list[at], hooks: [...list[at].hooks.filter((hook) => !isKitHook(hook)), ...entry.hooks] };
53
+ if (JSON.stringify(merged) !== JSON.stringify(list[at])) { list[at] = merged; changed = true; }
54
+ }
55
+ hooks[event] = list;
56
+ }
57
+ return { settings: { ...settings, hooks }, changed };
58
+ }
59
+
60
+ /**
61
+ * La orden del hook de la puerta, o `null` si no hay con qué ejecutarla: `node` si está en el PATH
62
+ * (Claude Code lo lanza desde su shell) o, con el ejecutable autónomo, el propio omk instalado.
63
+ */
64
+ function gateCommand({ agentsHome, omkBinary = null, hasNode = nodeOnPath() }) {
65
+ const script = path.join(agentsHome, 'hooks', 'orca-gate.cjs').split(path.sep).join('/');
66
+ if (hasNode && SAFE_PATH.test(script)) return `node "${script}" "${KIT_MARK}"`;
67
+ const binary = omkBinary && omkBinary.split(path.sep).join('/');
68
+ if (binary && SAFE_PATH.test(binary)) return `"${binary}" gate hook "${KIT_MARK}"`;
69
+ return null;
70
+ }
71
+
72
+ function nodeOnPath() {
73
+ const r = spawnSync(process.platform === 'win32' ? 'node.exe' : 'node', ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 15000 });
74
+ return r.status === 0 && /^v\d+/.test((r.stdout || '').trim());
75
+ }
76
+
77
+ /** La plantilla de la configuración global: la del proyecto más la puerta en UserPromptSubmit y PreToolUse. */
78
+ function globalTemplate(template, command) {
79
+ const hooks = JSON.parse(JSON.stringify(template.hooks));
80
+ const gate = { type: 'command', command, timeout: GATE_TIMEOUT_S };
81
+ const prompt = (hooks.UserPromptSubmit || []).find((entry) => !entry.matcher);
82
+ if (prompt) prompt.hooks.push(gate);
83
+ else hooks.UserPromptSubmit = [...(hooks.UserPromptSubmit || []), { hooks: [gate] }];
84
+ hooks.PreToolUse = [...(hooks.PreToolUse || []), { matcher: GATE_MATCHER, hooks: [gate] }];
85
+ // Cuándo se carga la skill orca: Skill es poco frecuente, así que este hook no frena el trabajo normal.
86
+ hooks.PostToolUse = [...(hooks.PostToolUse || []), { matcher: 'Skill', hooks: [gate] }];
87
+ return { ...template, hooks };
88
+ }
89
+
90
+ /**
91
+ * Deja en `file` los hooks del kit de `template` (el objeto de la plantilla). Devuelve qué pasó:
92
+ * 'created' (no existía y `create`), 'missing' (no existía), 'added' / 'current' (ya estaban al día),
93
+ * o 'invalid' (no es un JSON con la forma esperada: no se toca). `backup(file)` se llama antes de
94
+ * escribir sobre un fichero que ya existía.
95
+ */
96
+ function syncClaudeHooks(file, template, { dryRun = false, create = false, backup = null } = {}) {
97
+ let text;
98
+ try {
99
+ text = fs.readFileSync(file, 'utf8');
100
+ } catch (e) {
101
+ if (e.code !== 'ENOENT') throw e;
102
+ if (!create) return 'missing';
103
+ if (!dryRun) {
104
+ fs.mkdirSync(path.dirname(file), { recursive: true });
105
+ fs.writeFileSync(file, `${JSON.stringify({ hooks: template.hooks }, null, 2)}\n`, { flag: 'wx' });
106
+ }
107
+ return 'created';
108
+ }
109
+ let settings;
110
+ try {
111
+ settings = JSON.parse(text);
112
+ } catch {
113
+ // Un settings.json que no es JSON válido no lo arregla el kit: se deja como está y se avisa.
114
+ return 'invalid';
115
+ }
116
+ if (!isObject(settings)) return 'invalid';
117
+ const merged = mergeKitHooks(settings, template);
118
+ if (merged === null) return 'invalid';
119
+ if (!merged.changed) return 'current';
120
+ if (dryRun) return 'added';
121
+ if (backup) backup(file);
122
+ const tmp = `${file}.omk-${process.pid}.tmp`;
123
+ fs.writeFileSync(tmp, `${JSON.stringify(merged.settings, null, 2)}\n`, { flag: 'wx' });
124
+ try {
125
+ fs.renameSync(tmp, file);
126
+ } catch (e) {
127
+ fs.rmSync(tmp, { force: true });
128
+ throw e;
129
+ }
130
+ return 'added';
131
+ }
132
+
133
+ /**
134
+ * Pone los hooks de reparto en la configuración global de Claude Code (`global`) y en la del
135
+ * proyecto, si tiene `.claude/settings.json`. Sin Claude Code no hace ni dice nada. Devuelve
136
+ * `false` solo si algo falló. `OMK_NO_HOOKS=1` (o `--no-hooks`, que llega como `skip`) lo desactiva.
137
+ */
138
+ function applyHooks({ kit, agentsHome, project = null, global = true, dryRun = false, skip = false, omkBinary = null }) {
139
+ if (skip || process.env.OMK_NO_HOOKS === '1') return true;
140
+ const { c, sym } = require('./ui');
141
+ const { makeBackup } = require('./backup');
142
+ const out = (s = '') => process.stdout.write(s + '\n');
143
+ const template = JSON.parse(fs.readFileSync(path.join(kit, 'templates', 'claude-settings.json'), 'utf8'));
144
+ const targets = [];
145
+ const dir = claudeDir();
146
+ let gateMissing = false;
147
+ if (global && fs.existsSync(dir)) {
148
+ const command = gateCommand({ agentsHome, omkBinary });
149
+ gateMissing = command === null;
150
+ targets.push({ file: path.join(dir, 'settings.json'), label: 'Claude Code', create: true, template: command ? globalTemplate(template, command) : template });
151
+ }
152
+ if (project && fs.existsSync(path.join(project, '.claude', 'settings.json'))) {
153
+ targets.push({ file: path.join(project, '.claude', 'settings.json'), label: `Proyecto ${path.basename(project)}`, create: false, template });
154
+ }
155
+ if (targets.length === 0) return true;
156
+ const { stamp, backup } = makeBackup(agentsHome);
157
+ let good = true;
158
+ let touched = false;
159
+ out();
160
+ out(` ${c.lime('◆')} ${c.bold('Puerta de reparto en Claude Code')}`);
161
+ for (const { file, label, create, template: wanted } of targets) {
162
+ let result;
163
+ try {
164
+ result = syncClaudeHooks(file, wanted, { dryRun, create, backup });
165
+ } catch (e) {
166
+ out(` ${sym.fail} ${c.red(`${label}: no pude poner los hooks en ${file} (${e.message})`)}`);
167
+ good = false;
168
+ continue;
169
+ }
170
+ if (result === 'current') out(` ${sym.ok} ${label}: hooks de reparto al día`);
171
+ else if (result === 'invalid') {
172
+ out(` ${sym.warn} ${label}: ${file} no es un JSON con la forma esperada: no lo toco`);
173
+ out(` ${sym.todo} Copia a mano la clave "hooks" de ~/.agents/templates/claude-settings.json.`);
174
+ } else {
175
+ touched = touched || result === 'added';
176
+ out(` ${sym.ok} ${label}: hooks de reparto ${dryRun ? 'se añadirían a' : 'en'} ${file}`);
177
+ }
178
+ }
179
+ out(` ${sym.info} ${c.grey('Recuerdan en cada mensaje y al aprobar un plan que un trabajo con 2 o más entregables pasa por la skill orca; en la configuración global, además, no dejan editar hasta que su veredicto esté en el chat y, si reparte, hasta que respondas al plan.')}`);
180
+ if (gateMissing) out(` ${sym.warn} Sin node en el PATH ni ejecutable de omk: la puerta obligatoria no se instala, solo los recordatorios.`);
181
+ out(` ${sym.info} ${c.grey('Apagar solo la puerta obligatoria: omk gate off (u OMK_NO_GATE=1).')}`);
182
+ out(` ${sym.info} ${c.grey('Para que omk no los ponga: OMK_NO_HOOKS=1 (o --no-hooks) y bórralos de settings.json.')}`);
183
+ if (touched && !dryRun) out(` ${sym.info} ${c.grey(`Copia anterior: omk restore ${stamp}`)}`);
184
+ return good;
185
+ }
186
+
187
+ module.exports = { KIT_MARK, GATE_MATCHER, claudeDir, gateCommand, globalTemplate, mergeKitHooks, syncClaudeHooks, applyHooks };
package/bin/omk.js CHANGED
@@ -9,11 +9,12 @@ const path = require('node:path');
9
9
 
10
10
  const KIT = path.resolve(__dirname, '..');
11
11
  const VERSION = fs.readFileSync(path.join(KIT, 'VERSION'), 'utf8').trim();
12
- const REPO = 'orca-multiagent-kit';
13
12
  const AGENTS_HOME = process.env.AGENT_KIT_HOME || path.join(os.homedir(), '.agents');
14
- const RELEASES = 'https://github.com/FernandoBaqueroo/orca-multiagent-kit/releases/latest';
15
13
  // Ejecutable autónomo (Node SEA, bin/sea.js)
16
14
  const STANDALONE = require('./orca').isSea;
15
+ // Con esta opción, omk escribe al salir «[omk:fin] <comando> salida=<código>». La pasa el plugin de
16
+ // Orca, que lanza omk en un terminal y lee su salida: así sabe que ha terminado y cómo.
17
+ const EXIT_MARKER = '--exit-marker';
17
18
 
18
19
  const color = process.stdout.isTTY && !process.env.NO_COLOR;
19
20
  const lime = (s) => (color ? `\x1b[38;5;154m${s}\x1b[0m` : s);
@@ -27,15 +28,20 @@ ${bold('Uso')}
27
28
  omk <comando> [opciones]
28
29
 
29
30
  ${bold('Comandos')}
30
- ${lime('setup')} [--yes] [--dry-run] Prepara Orca entero: kit, plugins, plugin del kit y su panel
31
- ${lime('install')} [--agents a,b] [--dry-run] Instala o migra la fuente única en ~/.agents
31
+ ${lime('setup')} [--yes] [--dry-run] Lo instala todo: reglas y skills, omk en el PATH, plugin de Orca y su panel
32
+ [--no-plugin] [--no-path] [--no-hooks]
33
+ ${lime('install')} [--agents a,b] [--dry-run] Solo la fuente única en ~/.agents (y el plugin de Orca, si ya lo tienes)
32
34
  ${lime('init')} [ruta] Prepara un proyecto (por defecto, la carpeta actual)
33
35
  ${lime('verify')} Comprueba enlaces, imports y copias divergentes
34
36
  ${lime('plugin')} install|status|uninstall El plugin de Orca del kit (install pide tu aprobación)
37
+ ${lime('team')} [set …] Enseña o cambia el equipo de roles y la autonomía de ORCHESTRATION.md
38
+ ${lime('gate')} on|off|status La puerta de reparto obligatoria de Claude Code (hooks/orca-gate.cjs)
39
+ ${lime('run')} <subcomando> El motor de los runs de la skill orca: estado, rondas, worktrees, merge y limpieza (omk run help)
35
40
  ${lime('adopt')} <carpeta-skill> Comparte una skill externa con todos los agentes
36
41
  ${lime('backups')} Lista las copias de seguridad
37
42
  ${lime('restore')} <fecha> Deshace una instalación (fecha de "omk backups")
38
- ${lime('update')} Actualiza a la última versión de npm y reinstala
43
+ ${lime('update')} [--yes] [--offline] Lo actualiza todo: el kit, ~/.agents, el proyecto de esta carpeta y el plugin de Orca
44
+ [--no-project] [--no-plugin] [--no-hooks] [--dry-run] [--force]
39
45
  ${lime('where')} Muestra dónde está cada cosa
40
46
  ${lime('version')} Muestra la versión
41
47
  ${lime('help')} Esta ayuda
@@ -43,10 +49,12 @@ ${bold('Comandos')}
43
49
  ${bold('Agentes')} claude · antigravity · codex · copilot · cursor · devin (opcional)
44
50
 
45
51
  ${bold('Ejemplos')}
46
- omk setup ${dim('todo de una vez; pregunta antes de aprobar el plugin')}
47
- npx orca-multiagent-kit install --dry-run
48
- omk install
52
+ npx orca-multiagent-kit setup ${dim('instalar todo de una vez; pregunta antes de aprobar el plugin')}
53
+ omk update ${dim('actualizar todo de una vez: kit, ~/.agents, el proyecto de esta carpeta y el plugin')}
54
+ omk install --dry-run
49
55
  omk init ~/Dev/mi-app
56
+ omk team set --provider claude --provider codex --role casandra=codex
57
+ omk update --offline ${dim('sin descargar nada: reaplica esta versión al kit, al proyecto y al plugin')}
50
58
  omk adopt ~/.gemini/config/plugins/user-workflows/skills/impeccable
51
59
  `;
52
60
 
@@ -100,32 +108,129 @@ function finish(promise) {
100
108
  .then((code) => process.exit(code));
101
109
  }
102
110
 
111
+ /**
112
+ * omk gate: la puerta de reparto obligatoria de Claude Code. `hook` es el propio hook (lee la entrada de
113
+ * Claude Code por stdin); lo usa el ejecutable autónomo cuando no hay node en el PATH.
114
+ */
115
+ function gate([sub = 'status']) {
116
+ const gateModule = require(path.join(KIT, 'hooks', 'orca-gate.cjs'));
117
+ const off = path.join(gateModule.stateDir(), 'off');
118
+ if (sub === 'hook') {
119
+ const chunks = [];
120
+ process.stdin.on('data', (chunk) => chunks.push(chunk));
121
+ process.stdin.on('end', () => {
122
+ const output = gateModule.run(Buffer.concat(chunks).toString('utf8'));
123
+ if (output) process.stdout.write(output);
124
+ });
125
+ return 0;
126
+ }
127
+ if (sub === 'off') {
128
+ fs.mkdirSync(path.dirname(off), { recursive: true });
129
+ fs.writeFileSync(off, '');
130
+ console.log(`${lime('✓')} Puerta de reparto apagada: Claude Code edita sin esperar al veredicto de la skill orca. Volver a encenderla: omk gate on`);
131
+ return 0;
132
+ }
133
+ if (sub === 'on') {
134
+ fs.rmSync(off, { force: true });
135
+ console.log(`${lime('✓')} Puerta de reparto encendida.`);
136
+ return 0;
137
+ }
138
+ if (sub !== 'status') die(`subcomando desconocido: ${sub} (on, off, status)`, 2);
139
+ const { claudeDir, KIT_MARK } = require('./hooks');
140
+ const settings = path.join(claudeDir(), 'settings.json');
141
+ let installed = false;
142
+ try {
143
+ const hooks = (JSON.parse(fs.readFileSync(settings, 'utf8')).hooks || {}).PreToolUse || [];
144
+ installed = hooks.some((entry) => (entry.hooks || []).some((hook) => String(hook.command || '').includes(KIT_MARK)));
145
+ } catch (e) {
146
+ if (e.code !== 'ENOENT') console.log(`${dim('·')} No pude leer ${settings}: ${e.message}`);
147
+ }
148
+ const disabled = process.env.OMK_NO_GATE === '1' || fs.existsSync(off);
149
+ console.log(`${bold('hook')} ${installed ? 'instalado en ' + settings : 'no instalado: omk update (o omk setup)'}`);
150
+ console.log(`${bold('estado')} ${disabled ? 'apagada (omk gate on para encenderla)' : 'encendida'}`);
151
+ console.log(`${bold('script')} ${path.join(AGENTS_HOME, 'hooks', 'orca-gate.cjs')}${fs.existsSync(path.join(AGENTS_HOME, 'hooks', 'orca-gate.cjs')) ? '' : ' (falta: omk install)'}`);
152
+ return installed && !disabled ? 0 : 1;
153
+ }
154
+
103
155
  function listBackups() {
104
156
  const dir = path.join(AGENTS_HOME, 'backups');
105
157
  if (!fs.existsSync(dir)) return [];
106
158
  return fs.readdirSync(dir).filter((d) => /^\d{8}-\d{6}$/.test(d)).sort();
107
159
  }
108
160
 
109
- const [cmd = 'help', ...rest] = process.argv.slice(2);
161
+ const argv = process.argv.slice(2);
162
+ const [cmd = 'help', ...rest] = argv.filter((a) => a !== EXIT_MARKER);
163
+
164
+ if (argv.includes(EXIT_MARKER)) {
165
+ // En «exit» ya no corre nada asíncrono: la línea se escribe de forma síncrona o se pierde.
166
+ process.on('exit', (code) => {
167
+ const line = `\n[omk:fin] ${cmd.replace(/[^\w-]/g, '')} salida=${code}\n`;
168
+ try {
169
+ fs.writeSync(process.stdout.fd, line);
170
+ } catch {
171
+ // Una tubería que no admite escritura síncrona (EAGAIN): se deja en la cola normal de stdout.
172
+ process.stdout.write(line);
173
+ }
174
+ });
175
+ }
110
176
 
111
177
  switch (cmd) {
112
- case 'setup':
113
- finish(require('./setup').setup({ kit: KIT, args: rest, installer, standalone: STANDALONE }));
178
+ case 'setup': {
179
+ const { isTransientCopy, installGlobal, REPO } = require('./fetch');
180
+ // Con npx el kit corre desde una caché que npm borra cuando quiere, y el plugin de Orca necesita
181
+ // omk en el PATH y una carpeta del kit que siga ahí: se instala de forma permanente y sigue desde ella.
182
+ if (!STANDALONE && isTransientCopy(KIT) && !rest.includes('--dry-run')) {
183
+ console.log(`${lime('›')} Dejo omk instalado (npm install -g ${REPO}@${VERSION}): el plugin de Orca lo usa desde el PATH.`);
184
+ let entry;
185
+ try {
186
+ entry = installGlobal(VERSION);
187
+ } catch (e) {
188
+ die(e.message);
189
+ }
190
+ const r = spawnSync(process.execPath, [entry, 'setup', ...rest], { stdio: 'inherit' });
191
+ process.exit(r.status === null ? 1 : r.status);
192
+ }
193
+ finish(require('./setup').setup({ kit: KIT, args: rest, installer, standalone: STANDALONE, agentsHome: AGENTS_HOME }));
114
194
  break;
195
+ }
115
196
 
116
197
  case 'plugin':
117
198
  finish(require('./setup').plugin({ kit: KIT, args: rest }));
118
199
  break;
119
200
 
201
+ case 'team':
202
+ // exitCode y no exit(): deja terminar de escribir la salida cuando va a una tubería.
203
+ process.exitCode = require('./team').main(rest);
204
+ break;
205
+
120
206
  case 'install':
121
- case 'i':
122
- runInstaller(rest);
207
+ case 'i': {
208
+ // ~/.agents, los hooks de reparto de Claude Code y, si el plugin de Orca ya está instalado, su
209
+ // versión de este kit: quien actualiza desde un omk anterior (que al acabar solo llama a
210
+ // «omk install») también se lleva el plugin.
211
+ const { parseOptions, refreshPlugin } = require('./setup');
212
+ const { applyHooks } = require('./hooks');
213
+ const opts = parseOptions(rest);
214
+ finish(installer(opts.rest).then(async (code) => {
215
+ if (code !== 0) return code;
216
+ const omkBinary = STANDALONE ? require('./setup').installedOmk() : null;
217
+ const hooked = applyHooks({ kit: KIT, agentsHome: AGENTS_HOME, dryRun: opts.dryRun, skip: opts.noHooks, omkBinary });
218
+ if (opts.noPlugin) return hooked ? 0 : 1;
219
+ return (await refreshPlugin({ kit: KIT, yes: opts.yes, dryRun: opts.dryRun, quiet: true })) && hooked ? 0 : 1;
220
+ }));
123
221
  break;
222
+ }
124
223
 
125
224
  case 'init': {
126
225
  const target = path.resolve(rest[0] || process.cwd());
127
226
  if (!fs.existsSync(target)) die(`no existe la carpeta ${target}`);
128
- runInstaller(['--project-only', target, ...rest.slice(1)]);
227
+ // Un .claude/settings.json que ya existía no lo pisa el instalador: se le añaden los hooks de reparto.
228
+ finish(installer(['--project-only', target, ...rest.slice(1).filter((a) => a !== '--no-hooks')]).then((code) => {
229
+ if (code !== 0) return code;
230
+ const { applyHooks } = require('./hooks');
231
+ const dryRun = rest.includes('--dry-run');
232
+ return applyHooks({ kit: KIT, agentsHome: AGENTS_HOME, project: target, global: false, dryRun, skip: rest.includes('--no-hooks') }) ? 0 : 1;
233
+ }));
129
234
  break;
130
235
  }
131
236
 
@@ -152,43 +257,21 @@ switch (cmd) {
152
257
  runInstaller(['--restore', rest[0]]);
153
258
  break;
154
259
 
155
- case 'update': {
156
- if (STANDALONE) {
157
- // El ejecutable no se actualiza solo: la versión nueva es otro binario que se descarga.
158
- console.log(`${lime('›')} Este omk es el ejecutable autónomo v${VERSION}. La última versión está en ${RELEASES}`);
159
- console.log(dim(' Descárgala y ejecútala (o «omk setup» con ella). Reaplicando ahora la instalación de esta versión…'));
160
- runInstaller(rest.filter((a) => a !== '--force'));
161
- break;
162
- }
163
- const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
164
- const sh = { encoding: 'utf8', shell: process.platform === 'win32' };
165
- const latest = (spawnSync(npm, ['view', REPO, 'version'], sh).stdout || '').trim();
166
- if (!latest) die('no se pudo consultar npm. ¿Hay conexión?');
167
- if (latest === VERSION && !rest.includes('--force')) {
168
- console.log(`${lime('✓')} Ya tienes la última versión (${VERSION}). Reaplicando la instalación…`);
169
- } else {
170
- console.log(`${lime('›')} Actualizando ${dim(VERSION)} → ${lime(latest)}`);
171
- const prefix = (spawnSync(npm, ['prefix', '-g'], sh).stdout || '').trim();
172
- const libdir = process.platform === 'win32' ? prefix : path.join(prefix, 'lib', 'node_modules');
173
- let writable = true;
174
- try {
175
- fs.accessSync(libdir, fs.constants.W_OK);
176
- if (fs.existsSync(path.join(libdir, REPO))) fs.accessSync(path.join(libdir, REPO), fs.constants.W_OK);
177
- } catch { writable = false; }
178
- if (!writable) {
179
- die(`no tienes permiso para escribir en ${libdir} (instalaste omk con sudo o Node está en una carpeta del sistema).
180
-
181
- Rápido: sudo npm i -g ${REPO}@latest && omk install
182
- Recomendado: que npm instale en tu carpeta de usuario, una sola vez:
183
- mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global
184
- echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
185
- sudo npm rm -g ${REPO} && npm i -g ${REPO}`);
186
- }
187
- const u = spawnSync(npm, ['install', '-g', `${REPO}@latest`], { stdio: 'inherit', shell: sh.shell });
188
- if (u.status !== 0) die('no se pudo actualizar con npm. Prueba: npx ' + REPO + '@latest install');
189
- }
190
- const r = spawnSync('omk', ['install', ...rest.filter((a) => a !== '--force')], { stdio: 'inherit', shell: process.platform === 'win32' });
191
- process.exit(r.status === null ? 1 : r.status);
260
+ case 'update':
261
+ finish(require('./update').update({
262
+ kit: KIT, version: VERSION, args: rest, installer, standalone: STANDALONE, agentsHome: AGENTS_HOME,
263
+ }));
264
+ break;
265
+
266
+ case 'gate':
267
+ process.exitCode = gate(rest);
268
+ break;
269
+
270
+ case 'run': {
271
+ const code = require('./run').main(rest);
272
+ if (code && typeof code.then === 'function') code.then((c) => { process.exitCode = c; });
273
+ else process.exitCode = code;
274
+ break;
192
275
  }
193
276
 
194
277
  case 'where':