orca-multiagent-kit 1.4.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -1
- package/README.md +13 -7
- package/VERSION +1 -1
- package/bin/omk.js +47 -4
- package/bin/orca.js +170 -0
- package/bin/sea.js +95 -0
- package/bin/setup.js +326 -0
- package/bin/team.js +353 -0
- package/core/AGENTS.md +1 -1
- package/docs/EJECUTABLE.md +70 -0
- package/docs/PLUGIN-ORCA.md +126 -28
- package/orca-plugin/README.md +5 -1
- package/orca-plugin/assets/logos/README.md +10 -0
- package/orca-plugin/assets/logos/agent.png +0 -0
- package/orca-plugin/assets/logos/aider.png +0 -0
- package/orca-plugin/assets/logos/amp.png +0 -0
- package/orca-plugin/assets/logos/antigravity.png +0 -0
- package/orca-plugin/assets/logos/claude.png +0 -0
- package/orca-plugin/assets/logos/cline.png +0 -0
- package/orca-plugin/assets/logos/codex.png +0 -0
- package/orca-plugin/assets/logos/copilot.png +0 -0
- package/orca-plugin/assets/logos/cursor.png +0 -0
- package/orca-plugin/assets/logos/devin.png +0 -0
- package/orca-plugin/assets/logos/droid.png +0 -0
- package/orca-plugin/assets/logos/gemini.png +0 -0
- package/orca-plugin/assets/logos/goose.png +0 -0
- package/orca-plugin/assets/logos/grok.png +0 -0
- package/orca-plugin/assets/logos/kimi.png +0 -0
- package/orca-plugin/assets/logos/kiro.png +0 -0
- package/orca-plugin/assets/logos/opencode.png +0 -0
- package/orca-plugin/assets/logos/qwen-code.png +0 -0
- package/orca-plugin/orca-plugin.json +28 -7
- package/orca-plugin/src/icons.test.ts +14 -0
- package/orca-plugin/src/icons.ts +30 -0
- package/orca-plugin/src/kit.test.ts +456 -9
- package/orca-plugin/src/kit.ts +639 -16
- package/orca-plugin/src/models.test.ts +28 -0
- package/orca-plugin/src/models.ts +29 -0
- package/orca-plugin/src/node.d.ts +40 -0
- package/orca-plugin/src/panel-state.ts +28 -0
- package/orca-plugin/src/panel.test.tsx +298 -0
- package/orca-plugin/src/panel.tsx +609 -0
- package/orca-plugin/src/plan-card.test.ts +99 -0
- package/orca-plugin/src/plan-card.ts +107 -0
- package/orca-plugin/src/protocol.ts +179 -0
- package/orca-plugin/src/tabs/autonomy.tsx +70 -0
- package/orca-plugin/src/tabs/history.test.tsx +78 -0
- package/orca-plugin/src/tabs/history.tsx +118 -0
- package/orca-plugin/src/tabs/notices.test.tsx +183 -0
- package/orca-plugin/src/tabs/notices.tsx +274 -0
- package/orca-plugin/src/tabs/worktrees.test.tsx +130 -0
- package/orca-plugin/src/tabs/worktrees.tsx +138 -0
- package/orca-plugin/src/ui/agent-icon.tsx +13 -0
- package/orca-plugin/src/worker/context.test.ts +32 -0
- package/orca-plugin/src/worker/context.ts +92 -0
- package/orca-plugin/src/worker/history.test.ts +149 -0
- package/orca-plugin/src/worker/history.ts +181 -0
- package/orca-plugin/src/worker/notices.test.ts +356 -0
- package/orca-plugin/src/worker/notices.ts +291 -0
- package/orca-plugin/src/worker/system.test.ts +58 -0
- package/orca-plugin/src/worker/system.ts +122 -0
- package/orca-plugin/src/worker/worktrees.test.ts +177 -0
- package/orca-plugin/src/worker/worktrees.ts +188 -0
- package/orca-plugin/src/worker.test.ts +297 -15
- package/orca-plugin/src/worker.ts +353 -32
- package/package.json +3 -2
- package/skills/orca/SKILL.md +1 -0
- package/skills/orca/references/engine-orca.md +1 -0
- package/skills/orca/references/olimpo.md +1 -0
- package/skills/orca/references/plan-card.md +45 -0
package/bin/setup.js
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// omk setup y omk plugin: deja Orca listo para el kit (kit instalado, plugins encendidos, plugin del
|
|
2
|
+
// kit instalado y su panel abierto) y, en el ejecutable autónomo, pone omk en el PATH.
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const { spawnSync } = require('node:child_process');
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const os = require('node:os');
|
|
8
|
+
const path = require('node:path');
|
|
9
|
+
const readline = require('node:readline');
|
|
10
|
+
const orcaCli = require('./orca');
|
|
11
|
+
const { c, sym } = require('./ui');
|
|
12
|
+
|
|
13
|
+
const out = (s = '') => process.stdout.write(s + '\n');
|
|
14
|
+
const ok = (s) => out(` ${sym.ok} ${s}`);
|
|
15
|
+
const warn = (s) => out(` ${sym.warn} ${s}`);
|
|
16
|
+
const fail = (s) => out(` ${sym.fail} ${c.red(s)}`);
|
|
17
|
+
const todo = (s) => out(` ${sym.todo} ${s}`);
|
|
18
|
+
const detail = (s) => out(` ${sym.info} ${c.grey(s)}`);
|
|
19
|
+
const heading = (s) => { out(); out(` ${c.lime('◆')} ${c.bold(s)}`); };
|
|
20
|
+
|
|
21
|
+
/** Separa las opciones propias de omk setup/plugin de las que van a install.sh. */
|
|
22
|
+
function parseOptions(args) {
|
|
23
|
+
const own = { yes: false, dryRun: false, noPlugin: false, noPath: false };
|
|
24
|
+
const rest = [];
|
|
25
|
+
for (const a of args) {
|
|
26
|
+
if (a === '--yes' || a === '-y') own.yes = true;
|
|
27
|
+
else if (a === '--no-plugin') own.noPlugin = true;
|
|
28
|
+
else if (a === '--no-path') own.noPath = true;
|
|
29
|
+
else { if (a === '--dry-run') own.dryRun = true; rest.push(a); }
|
|
30
|
+
}
|
|
31
|
+
return { ...own, rest };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function ask(question) {
|
|
35
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
36
|
+
try {
|
|
37
|
+
const answer = await new Promise((resolve) => rl.question(question, resolve));
|
|
38
|
+
return /^(s|si|sí|y|yes)$/i.test(String(answer).trim());
|
|
39
|
+
} finally {
|
|
40
|
+
rl.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Orca exige una aprobación explícita del usuario para un plugin que ejecuta código: se enseña lo que
|
|
45
|
+
// concede y se pregunta. --yes es esa aprobación dada de antemano.
|
|
46
|
+
const confirmWith = (yes) => async (grants, data) => {
|
|
47
|
+
out();
|
|
48
|
+
out(` ${c.amber(c.bold('Orca pide tu aprobación'))} ${c.grey(orcaCli.clean(`para ${data.name || 'el plugin'} ${data.version || ''}`))}`);
|
|
49
|
+
for (const g of grants) detail(g);
|
|
50
|
+
if (yes) { ok('Aprobado (--yes)'); return true; }
|
|
51
|
+
if (!process.stdin.isTTY) {
|
|
52
|
+
warn('Sin terminal interactivo no puedo preguntarte. Repite con --yes para aprobarlo.');
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return ask(` ${sym.todo} ¿Apruebas este acceso? [s/N] `);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
function listPlugin(orca) {
|
|
59
|
+
const list = orcaCli.runOrca(orca, ['plugin', 'list']);
|
|
60
|
+
if (list.code !== 0) throw new Error(`no pude listar los plugins de Orca (${list.problem})`);
|
|
61
|
+
return orcaCli.findInstalled(list.json);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const PLAN_ARGS = {
|
|
65
|
+
install: (dir) => ['plugin', 'install', dir],
|
|
66
|
+
update: (dir, installed) => ['plugin', 'update', installed.pluginKey],
|
|
67
|
+
enable: (dir, installed) => ['plugin', 'enable', installed.pluginKey],
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const PLAN_TEXT = {
|
|
71
|
+
install: 'instalaría el plugin',
|
|
72
|
+
update: 'actualizaría el plugin',
|
|
73
|
+
enable: 'pediría la aprobación del plugin',
|
|
74
|
+
current: 'el plugin ya está instalado y activo',
|
|
75
|
+
disabled: 'el plugin está desactivado y se deja así',
|
|
76
|
+
foreign: 'hay otra versión del plugin instalada desde otra carpeta y no se toca',
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** Instala, actualiza o aprueba el plugin del kit. Devuelve su clave, o null si no quedó instalado. */
|
|
80
|
+
async function ensurePlugin(orca, kit, { yes, dryRun }) {
|
|
81
|
+
const dir = path.join(kit, 'orca-plugin');
|
|
82
|
+
const { version } = orcaCli.readManifest(dir);
|
|
83
|
+
const installed = listPlugin(orca);
|
|
84
|
+
const plan = orcaCli.planPlugin(installed, dir, version);
|
|
85
|
+
if (dryRun) { detail(`Simulación: ${PLAN_TEXT[plan]} (v${version}).`); return null; }
|
|
86
|
+
|
|
87
|
+
if (plan === 'disabled') {
|
|
88
|
+
warn(`Plugin ${installed.pluginKey} v${version} desactivado: lo respeto.`);
|
|
89
|
+
todo(`Para activarlo: orca plugin enable ${installed.pluginKey}`);
|
|
90
|
+
return installed.pluginKey;
|
|
91
|
+
}
|
|
92
|
+
if (plan === 'foreign') {
|
|
93
|
+
warn(`Ya hay ${installed.pluginKey} v${installed.version} instalado desde otra carpeta; este kit trae la v${version}.`);
|
|
94
|
+
todo('Para cambiarlo por el de este kit: omk plugin uninstall && omk plugin install');
|
|
95
|
+
return installed.pluginKey;
|
|
96
|
+
}
|
|
97
|
+
if (plan !== 'current') {
|
|
98
|
+
const result = await orcaCli.withApproval(orca, PLAN_ARGS[plan](dir, installed), confirmWith(yes));
|
|
99
|
+
if (result.declined) { fail('Plugin sin instalar: no se aprobó el acceso.'); return null; }
|
|
100
|
+
if (result.code !== 0) { fail(`Orca no instaló el plugin: ${result.problem}`); return null; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const now = listPlugin(orca);
|
|
104
|
+
if (!now || now.version !== version) { fail(`Orca no lista el plugin v${version} después de instalarlo.`); return null; }
|
|
105
|
+
if (now.status === 'errored' || now.status === 'invalid') {
|
|
106
|
+
warn(`Plugin ${now.pluginKey} v${version} instalado, pero Orca lo marca como ${now.status}.`);
|
|
107
|
+
todo(`Detalle: orca plugin logs ${now.pluginKey}`);
|
|
108
|
+
return now.pluginKey;
|
|
109
|
+
}
|
|
110
|
+
ok(`Plugin ${now.pluginKey} v${version} ${plan === 'current' ? 'ya estaba instalado' : 'instalado'} ${c.grey('(' + now.status + ')')}`);
|
|
111
|
+
return now.pluginKey;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function requireOrca(manifestDir) {
|
|
115
|
+
const orca = orcaCli.findOrca();
|
|
116
|
+
if (!orca) {
|
|
117
|
+
fail(process.env.OMK_ORCA ? `OMK_ORCA=${process.env.OMK_ORCA} no responde a «orca --version».` : 'No encuentro el CLI de Orca.');
|
|
118
|
+
todo('Instala Orca (https://www.onorca.dev), ábrelo una vez y vuelve a ejecutar esto. Si ya lo tienes, define OMK_ORCA con la ruta de su CLI.');
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
const need = (orcaCli.readManifest(manifestDir).engines || {}).orca;
|
|
122
|
+
if (!orcaCli.satisfies(orca.version, need)) {
|
|
123
|
+
fail(`Orca ${orca.version}: el plugin necesita ${need}. Actualiza Orca y repite.`);
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
ok(`Orca ${orca.version} ${c.grey(orca.path)}`);
|
|
127
|
+
return orca;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function ensureRuntime(orca) {
|
|
131
|
+
const status = orcaCli.runOrca(orca, ['status']);
|
|
132
|
+
const runtime = status.json && status.json.result && status.json.result.runtime;
|
|
133
|
+
if (runtime && runtime.reachable) return true;
|
|
134
|
+
detail('Orca no está abierto: lo abro y espero a que arranque…');
|
|
135
|
+
const opened = orcaCli.runOrca(orca, ['open'], orcaCli.OPEN_TIMEOUT_MS);
|
|
136
|
+
if (opened.code === 0) { ok('Orca abierto'); return true; }
|
|
137
|
+
fail(`No pude abrir Orca: ${opened.problem}`);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// --------------------------------------------------------------------- ejecutable en el PATH
|
|
142
|
+
|
|
143
|
+
/** Carpeta donde el ejecutable autónomo se copia a sí mismo. */
|
|
144
|
+
function binDir(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
145
|
+
if (env.OMK_BIN_DIR) return path.resolve(env.OMK_BIN_DIR);
|
|
146
|
+
if (platform === 'win32') return path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'Programs', 'orca-multiagent-kit');
|
|
147
|
+
return path.join(home, '.local', 'bin');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const SEA_FUSE = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2';
|
|
151
|
+
|
|
152
|
+
// Solo se reemplaza un `omk` que sea este mismo ejecutable (otra versión): nunca otra herramienta con ese nombre.
|
|
153
|
+
function isKitExecutable(file) {
|
|
154
|
+
try {
|
|
155
|
+
const st = fs.lstatSync(file);
|
|
156
|
+
if (!st.isFile()) return false;
|
|
157
|
+
const bytes = fs.readFileSync(file);
|
|
158
|
+
return bytes.includes(SEA_FUSE) && bytes.includes('orca-multiagent-kit');
|
|
159
|
+
} catch {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const onPath = (dir, envPath = process.env.PATH || '') =>
|
|
165
|
+
envPath.split(path.delimiter).filter(Boolean).some((p) => orcaCli.samePath(p, dir));
|
|
166
|
+
|
|
167
|
+
// Añade la carpeta al Path del usuario (HKCU\Environment) conservando su tipo (REG_EXPAND_SZ) y las
|
|
168
|
+
// variables sin expandir, y avisa a Windows del cambio. La ruta llega por OMK_BIN_DIR, nunca en el script.
|
|
169
|
+
const WIN_ADD_TO_PATH = `
|
|
170
|
+
$ErrorActionPreference = 'Stop'
|
|
171
|
+
$dir = $env:OMK_BIN_DIR
|
|
172
|
+
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
|
173
|
+
try {
|
|
174
|
+
$current = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
|
175
|
+
$parts = @($current -split ';' | Where-Object { $_ })
|
|
176
|
+
if ($parts -contains $dir) { 'present'; exit 0 }
|
|
177
|
+
$kind = if ($current) { $key.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }
|
|
178
|
+
$key.SetValue('Path', (($parts + $dir) -join ';'), $kind)
|
|
179
|
+
} finally { $key.Close() }
|
|
180
|
+
Add-Type -Namespace OmkWin -Name Env -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint msg, System.UIntPtr wParam, string lParam, uint flags, uint timeout, out System.UIntPtr result);'
|
|
181
|
+
$ignored = [UIntPtr]::Zero
|
|
182
|
+
[void][OmkWin.Env]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$ignored)
|
|
183
|
+
'added'
|
|
184
|
+
`;
|
|
185
|
+
|
|
186
|
+
function addToWindowsPath(dir) {
|
|
187
|
+
const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_ADD_TO_PATH], {
|
|
188
|
+
encoding: 'utf8', env: { ...process.env, OMK_BIN_DIR: dir }, timeout: 60000, windowsHide: true,
|
|
189
|
+
});
|
|
190
|
+
if (r.error || r.status !== 0) throw new Error(`no pude añadir ${dir} al PATH del usuario: ${(r.stderr || (r.error && r.error.message) || '').trim()}`);
|
|
191
|
+
return r.stdout.trim();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Copia el ejecutable autónomo a binDir() y se asegura de que esa carpeta está en el PATH. */
|
|
195
|
+
function installSelf({ noPath }) {
|
|
196
|
+
const dir = binDir();
|
|
197
|
+
const target = path.join(dir, process.platform === 'win32' ? 'omk.exe' : 'omk');
|
|
198
|
+
heading('omk en el PATH');
|
|
199
|
+
if (!orcaCli.samePath(process.execPath, target)) {
|
|
200
|
+
if (fs.existsSync(target) && !isKitExecutable(target)) {
|
|
201
|
+
warn(`${target} existe y no es el ejecutable del kit: no lo toco.`);
|
|
202
|
+
todo('Define OMK_BIN_DIR con otra carpeta y repite, o borra ese fichero si es una copia vieja.');
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
206
|
+
const tmp = `${target}.new`;
|
|
207
|
+
fs.copyFileSync(process.execPath, tmp);
|
|
208
|
+
fs.chmodSync(tmp, 0o755);
|
|
209
|
+
fs.renameSync(tmp, target);
|
|
210
|
+
ok(`omk copiado en ${target}`);
|
|
211
|
+
} else {
|
|
212
|
+
ok(`omk ya está en ${target}`);
|
|
213
|
+
}
|
|
214
|
+
if (onPath(dir)) { ok('Su carpeta ya está en el PATH'); return true; }
|
|
215
|
+
if (noPath) { todo(`Añade ${dir} al PATH para usar omk en cualquier terminal.`); return true; }
|
|
216
|
+
if (process.platform === 'win32') {
|
|
217
|
+
const result = addToWindowsPath(dir);
|
|
218
|
+
ok(result === 'present' ? 'Su carpeta ya estaba en el PATH del usuario' : `${dir} añadido al PATH del usuario`);
|
|
219
|
+
todo('Cierra y vuelve a abrir Orca (y los terminales abiertos) para que vean omk.');
|
|
220
|
+
} else {
|
|
221
|
+
todo(`Añade ${dir} al PATH: echo 'export PATH="${dir}:$PATH"' >> ~/.zshrc (o ~/.bashrc)`);
|
|
222
|
+
}
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// --------------------------------------------------------------------------------- comandos
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* omk setup: kit global, Orca abierto, plugins encendidos, plugin del kit instalado y su panel
|
|
230
|
+
* abierto. Devuelve el código de salida.
|
|
231
|
+
*/
|
|
232
|
+
async function setup({ kit, args, installer, standalone }) {
|
|
233
|
+
const opts = parseOptions(args);
|
|
234
|
+
const code = await installer(opts.rest);
|
|
235
|
+
if (code !== 0) return code;
|
|
236
|
+
if (standalone && opts.dryRun) {
|
|
237
|
+
heading('omk en el PATH');
|
|
238
|
+
detail(`Simulación: copiaría omk a ${binDir()} y comprobaría que está en el PATH.`);
|
|
239
|
+
} else if (standalone) {
|
|
240
|
+
try {
|
|
241
|
+
if (!installSelf(opts)) return 1;
|
|
242
|
+
} catch (e) {
|
|
243
|
+
fail(e.message);
|
|
244
|
+
return 1;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (opts.noPlugin) return 0;
|
|
248
|
+
|
|
249
|
+
heading('Orca');
|
|
250
|
+
const orca = requireOrca(path.join(kit, 'orca-plugin'));
|
|
251
|
+
if (!orca) return 1;
|
|
252
|
+
if (opts.dryRun) {
|
|
253
|
+
detail('Simulación: abriría Orca si no está abierto y encendería los plugins.');
|
|
254
|
+
await ensurePlugin(orca, kit, opts);
|
|
255
|
+
out();
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
if (!ensureRuntime(orca)) return 1;
|
|
259
|
+
const on = orcaCli.runOrca(orca, ['plugin', 'system', 'on']);
|
|
260
|
+
if (on.code !== 0) { fail(`No pude encender los plugins de Orca: ${on.problem}`); return 1; }
|
|
261
|
+
ok('Plugins de Orca encendidos');
|
|
262
|
+
|
|
263
|
+
const key = await ensurePlugin(orca, kit, opts);
|
|
264
|
+
if (!key) return 1;
|
|
265
|
+
const shown = orcaCli.runOrca(orca, ['plugin', 'open', key, '--panel', orcaCli.PANEL_ID]);
|
|
266
|
+
if (shown.code === 0) ok('Panel «Multiagent Kit» abierto en la barra lateral derecha de Orca');
|
|
267
|
+
else warn(`No pude abrir el panel (${shown.problem}). Está en la barra lateral derecha de Orca.`);
|
|
268
|
+
|
|
269
|
+
out();
|
|
270
|
+
out(` ${sym.ok} ${c.bold('Entorno de Orca listo')}`);
|
|
271
|
+
for (const [k, v] of [
|
|
272
|
+
['ajustes', 'panel «Multiagent Kit» o Settings → Plugins → Orca Multiagent Kit'],
|
|
273
|
+
['paleta', '«Orca Multiagent Kit: …» (verificar, inicializar, actualizar)'],
|
|
274
|
+
['proyecto', 'en el agente: «inicializa el proyecto»'],
|
|
275
|
+
]) out(` ${c.grey(k.padEnd(10))} ${c.lime(v)}`);
|
|
276
|
+
out();
|
|
277
|
+
return 0;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** omk plugin <install|status|uninstall>. Devuelve el código de salida. */
|
|
281
|
+
async function plugin({ kit, args }) {
|
|
282
|
+
const [sub = 'status', ...rest] = args;
|
|
283
|
+
if (!['install', 'status', 'uninstall'].includes(sub)) {
|
|
284
|
+
fail(`subcomando desconocido: ${sub} (install, status, uninstall)`);
|
|
285
|
+
return 2;
|
|
286
|
+
}
|
|
287
|
+
const opts = parseOptions(rest);
|
|
288
|
+
heading(`Plugin de Orca · ${sub}`);
|
|
289
|
+
const orca = requireOrca(path.join(kit, 'orca-plugin'));
|
|
290
|
+
if (!orca) return 1;
|
|
291
|
+
const installed = listPlugin(orca);
|
|
292
|
+
const { version } = orcaCli.readManifest(path.join(kit, 'orca-plugin'));
|
|
293
|
+
|
|
294
|
+
switch (sub) {
|
|
295
|
+
case 'install': {
|
|
296
|
+
if (!opts.dryRun) {
|
|
297
|
+
const on = orcaCli.runOrca(orca, ['plugin', 'system', 'on']);
|
|
298
|
+
if (on.code !== 0) { fail(`No pude encender los plugins de Orca: ${on.problem}`); return 1; }
|
|
299
|
+
}
|
|
300
|
+
const key = await ensurePlugin(orca, kit, opts);
|
|
301
|
+
return key || opts.dryRun ? 0 : 1;
|
|
302
|
+
}
|
|
303
|
+
case 'status':
|
|
304
|
+
if (!installed) { warn(`No instalado. Este kit trae la v${version}: omk plugin install`); return 1; }
|
|
305
|
+
ok(`${installed.pluginKey} v${installed.version} ${c.grey('(' + installed.status + ')')}`);
|
|
306
|
+
if (installed.version !== version) todo(`Este kit trae la v${version}: omk plugin install`);
|
|
307
|
+
return 0;
|
|
308
|
+
case 'uninstall': {
|
|
309
|
+
if (!installed) { ok('No estaba instalado'); return 0; }
|
|
310
|
+
const r = orcaCli.runOrca(orca, ['plugin', 'uninstall', installed.pluginKey]);
|
|
311
|
+
if (r.code !== 0) { fail(`Orca no lo desinstaló: ${r.problem}`); return 1; }
|
|
312
|
+
ok(`${installed.pluginKey} desinstalado`);
|
|
313
|
+
return 0;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Con el ejecutable abierto con doble clic, espera a Enter para que la ventana no se cierre sola. */
|
|
319
|
+
async function pauseIfAsked(code) {
|
|
320
|
+
if (process.env.OMK_PAUSE === '1' && process.stdin.isTTY) {
|
|
321
|
+
await ask(`\n ${c.grey('Pulsa Enter para cerrar')} `);
|
|
322
|
+
}
|
|
323
|
+
return code;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
module.exports = { setup, plugin, pauseIfAsked, parseOptions, binDir };
|
package/bin/team.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
// omk team: el equipo de roles del proyecto en ORCHESTRATION.md §1 (proveedores activos, revisión
|
|
2
|
+
// cruzada, las filas «Rol <nombre>» de la tabla de excepciones y los roles propios del proyecto) y
|
|
3
|
+
// el nivel de autonomía de §0. El panel Equipo del plugin lo usa con --data y --autonomy.
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
|
|
9
|
+
/** Roles de Olimpo que se fijan a un proveedor (skills/orca/references/olimpo.md); Hefesto coordina. */
|
|
10
|
+
const ROLES = [
|
|
11
|
+
['dedalo', 'Dédalo'], ['casandra', 'Casandra'], ['temis', 'Temis'], ['ariadna', 'Ariadna'],
|
|
12
|
+
['persefone', 'Perséfone'], ['proteo', 'Proteo'], ['narciso', 'Narciso'], ['icaro', 'Ícaro'],
|
|
13
|
+
['argos', 'Argos'], ['atlas', 'Atlas'], ['clio', 'Clío'],
|
|
14
|
+
];
|
|
15
|
+
const ROLE_NAME = new Map(ROLES);
|
|
16
|
+
const RESERVED = new Set(['Hefesto', ...ROLE_NAME.values()].map((name) => name.toLocaleLowerCase('es')));
|
|
17
|
+
const CROSS = { sensibles: 'unidades L y sensibles', todas: 'todas', nunca: 'nunca' };
|
|
18
|
+
const LEVELS = ['alto', 'medio', 'bajo'];
|
|
19
|
+
const AUTONOMY = ['manual', 'semi', 'auto'];
|
|
20
|
+
// Columna «Revisión» de los roles propios, como la escribe olimpo.md.
|
|
21
|
+
const REVIEW = { propia: 'propia', cross: '`cross`', argos: 'Argos', casandra: 'Casandra' };
|
|
22
|
+
const AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
23
|
+
const CUSTOM_NAME = /^\p{L}[\p{L}\p{M}\p{N} -]{0,29}$/u;
|
|
24
|
+
const MAX_PROVIDERS = 8;
|
|
25
|
+
const MAX_CUSTOM = 10;
|
|
26
|
+
const WORK_MAX = 80;
|
|
27
|
+
const GUARD_MAX = 120;
|
|
28
|
+
// Las filas que escribe omk team: las demás son del usuario y no se tocan.
|
|
29
|
+
const MARK = 'equipo (omk team)';
|
|
30
|
+
const CUSTOM_MARK = '<!-- omk team -->';
|
|
31
|
+
|
|
32
|
+
const PROVIDERS_LINE = /^(\s*- Proveedores activos:)[ \t]*(.*?)([ \t]*<!--.*-->)?[ \t]*$/;
|
|
33
|
+
const CROSS_LINE = /^(\s*- Revisión cruzada[^:]*:)[ \t]*(.*?)[ \t]*$/;
|
|
34
|
+
const EXCEPTIONS_LINE = /^\s*- Excepciones al reparto/;
|
|
35
|
+
const CUSTOM_LINE = /^\s*- Roles propios del proyecto/;
|
|
36
|
+
const TABLE_LINE = /^\s*\|/;
|
|
37
|
+
const AUTONOMY_HEADING = /^##\s*0\.\s*Autonom/;
|
|
38
|
+
const AUTONOMY_LINE = /^(\s*- Nivel:)[ \t]*(.*?)([ \t]*<!--.*-->)?[ \t]*$/;
|
|
39
|
+
|
|
40
|
+
const HELP = `Uso:
|
|
41
|
+
omk team [show] [--file ruta] Enseña el equipo de ORCHESTRATION.md
|
|
42
|
+
omk team set [opciones] Lo cambia
|
|
43
|
+
--provider <id> Proveedor activo (repetible; sustituye la lista)
|
|
44
|
+
--cross sensibles|todas|nunca Qué unidades revisa otro proveedor
|
|
45
|
+
--role <rol>=<id>|auto Fija el proveedor de un rol (repetible); auto lo quita
|
|
46
|
+
--reset-roles Quita antes los roles fijados por omk team
|
|
47
|
+
--autonomy manual|semi|auto Cuántas confirmaciones pide la skill orca (§0)
|
|
48
|
+
--data <base64url> El equipo entero en JSON (lo usa el panel del plugin);
|
|
49
|
+
sustituye proveedores, revisión, roles fijados y roles propios
|
|
50
|
+
--file <ruta> Otro ORCHESTRATION.md (por defecto, el de la carpeta actual)
|
|
51
|
+
Roles: ${ROLES.map(([id]) => id).join(', ')}`;
|
|
52
|
+
|
|
53
|
+
class TeamError extends Error {}
|
|
54
|
+
|
|
55
|
+
/** Texto de una celda de tabla: una línea, sin `|`, `<`, `>` ni caracteres de control o formato. */
|
|
56
|
+
function cellText(value, max, field) {
|
|
57
|
+
if (typeof value !== 'string') throw new TeamError(`--data: ${field} no es texto`);
|
|
58
|
+
const clean = value.replace(/[|<>\p{Cc}\p{Cf}]+/gu, ' ').replace(/\s+/g, ' ').trim();
|
|
59
|
+
if (clean.length > max) throw new TeamError(`--data: ${field} pasa de ${max} caracteres`);
|
|
60
|
+
return clean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** El equipo que manda el panel, validado entero; nada que no encaje llega al fichero. */
|
|
64
|
+
function parseData(encoded) {
|
|
65
|
+
if (!/^[A-Za-z0-9_-]{1,8000}$/.test(encoded)) throw new TeamError('--data no es base64url');
|
|
66
|
+
let data;
|
|
67
|
+
try {
|
|
68
|
+
data = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
|
69
|
+
} catch (e) {
|
|
70
|
+
throw new TeamError(`--data no es un equipo en JSON: ${e.message}`);
|
|
71
|
+
}
|
|
72
|
+
if (!data || typeof data !== 'object' || data.v !== 1) throw new TeamError('--data: versión de equipo desconocida');
|
|
73
|
+
const { providers, cross, roles, custom } = data;
|
|
74
|
+
if (!Array.isArray(providers) || !providers.length || providers.length > MAX_PROVIDERS
|
|
75
|
+
|| !providers.every((id) => typeof id === 'string' && AGENT_ID.test(id)) || new Set(providers).size !== providers.length) {
|
|
76
|
+
throw new TeamError('--data: proveedores no válidos');
|
|
77
|
+
}
|
|
78
|
+
if (!Object.hasOwn(CROSS, cross)) throw new TeamError('--data: revisión cruzada no válida');
|
|
79
|
+
if (!roles || typeof roles !== 'object' || Array.isArray(roles)) throw new TeamError('--data: roles no válidos');
|
|
80
|
+
const fixed = new Map();
|
|
81
|
+
for (const [role, provider] of Object.entries(roles)) {
|
|
82
|
+
if (!ROLE_NAME.has(role) || !providers.includes(provider)) throw new TeamError(`--data: rol no válido: ${role}`);
|
|
83
|
+
fixed.set(role, provider);
|
|
84
|
+
}
|
|
85
|
+
if (!Array.isArray(custom) || custom.length > MAX_CUSTOM) throw new TeamError('--data: roles propios no válidos');
|
|
86
|
+
const names = new Set();
|
|
87
|
+
const own = custom.map((role, i) => {
|
|
88
|
+
const field = (name) => `rol propio ${i + 1}: ${name}`;
|
|
89
|
+
if (!role || typeof role !== 'object') throw new TeamError(`--data: ${field('no es un objeto')}`);
|
|
90
|
+
const name = typeof role.name === 'string' ? role.name.trim() : '';
|
|
91
|
+
const key = name.toLocaleLowerCase('es');
|
|
92
|
+
if (!CUSTOM_NAME.test(name) || RESERVED.has(key) || names.has(key)) throw new TeamError(`--data: ${field('nombre no válido o repetido')}`);
|
|
93
|
+
names.add(key);
|
|
94
|
+
const work = cellText(role.work, WORK_MAX, field('qué hace'));
|
|
95
|
+
if (!work) throw new TeamError(`--data: ${field('falta qué hace')}`);
|
|
96
|
+
if (!LEVELS.includes(role.level)) throw new TeamError(`--data: ${field('nivel no válido')}`);
|
|
97
|
+
if (!Object.hasOwn(REVIEW, role.review)) throw new TeamError(`--data: ${field('revisión no válida')}`);
|
|
98
|
+
if (role.provider !== null && !providers.includes(role.provider)) throw new TeamError(`--data: ${field('proveedor no activo')}`);
|
|
99
|
+
return { name, work, level: role.level, review: role.review, guard: cellText(role.guard, GUARD_MAX, field('guardarraíl')), provider: role.provider };
|
|
100
|
+
});
|
|
101
|
+
return { providers, cross, roles: fixed, custom: own };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function parseArgs(args) {
|
|
105
|
+
const [first, ...rest] = args;
|
|
106
|
+
const action = first === 'set' ? 'set' : 'show';
|
|
107
|
+
const opts = { action, file: null, providers: [], cross: null, roles: new Map(), resetRoles: false, custom: null, autonomy: null };
|
|
108
|
+
const list = first === 'set' || first === 'show' ? rest : args;
|
|
109
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
110
|
+
const arg = list[i];
|
|
111
|
+
const value = () => {
|
|
112
|
+
const next = list[i + 1];
|
|
113
|
+
if (next === undefined || next.startsWith('--')) throw new TeamError(`falta el valor de ${arg}`);
|
|
114
|
+
i += 1;
|
|
115
|
+
return next;
|
|
116
|
+
};
|
|
117
|
+
if (arg === '--file') opts.file = value();
|
|
118
|
+
else if (action === 'show') throw new TeamError(`opción desconocida para omk team: ${arg}\n${HELP}`);
|
|
119
|
+
else if (arg === '--reset-roles') opts.resetRoles = true;
|
|
120
|
+
else if (arg === '--data') {
|
|
121
|
+
const data = parseData(value());
|
|
122
|
+
opts.providers = data.providers;
|
|
123
|
+
opts.cross = data.cross;
|
|
124
|
+
opts.roles = data.roles;
|
|
125
|
+
opts.resetRoles = true;
|
|
126
|
+
opts.custom = data.custom;
|
|
127
|
+
} else if (arg === '--provider') {
|
|
128
|
+
const id = value();
|
|
129
|
+
if (!AGENT_ID.test(id)) throw new TeamError(`«${id}» no es un id de agente (minúsculas, números y guiones)`);
|
|
130
|
+
if (!opts.providers.includes(id)) opts.providers.push(id);
|
|
131
|
+
} else if (arg === '--cross') {
|
|
132
|
+
const mode = value();
|
|
133
|
+
if (!Object.hasOwn(CROSS, mode)) throw new TeamError(`--cross admite sensibles, todas o nunca, no «${mode}»`);
|
|
134
|
+
opts.cross = mode;
|
|
135
|
+
} else if (arg === '--autonomy') {
|
|
136
|
+
const level = value();
|
|
137
|
+
if (!AUTONOMY.includes(level)) throw new TeamError(`--autonomy admite manual, semi o auto, no «${level}»`);
|
|
138
|
+
opts.autonomy = level;
|
|
139
|
+
} else if (arg === '--role') {
|
|
140
|
+
const [role, provider, extra] = value().split('=');
|
|
141
|
+
if (!ROLE_NAME.has(role)) throw new TeamError(`rol desconocido: «${role}». Roles: ${ROLES.map(([id]) => id).join(', ')}`);
|
|
142
|
+
if (extra !== undefined || provider === undefined || (provider !== 'auto' && !AGENT_ID.test(provider))) {
|
|
143
|
+
throw new TeamError('--role espera <rol>=<id de agente> o <rol>=auto');
|
|
144
|
+
}
|
|
145
|
+
opts.roles.set(role, provider);
|
|
146
|
+
} else throw new TeamError(`opción desconocida: ${arg}\n${HELP}`);
|
|
147
|
+
}
|
|
148
|
+
if (action === 'set' && !opts.providers.length && !opts.cross && !opts.roles.size && !opts.resetRoles && !opts.autonomy) {
|
|
149
|
+
throw new TeamError(`omk team set sin cambios\n${HELP}`);
|
|
150
|
+
}
|
|
151
|
+
return opts;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const cells = (line) => line.replace(CUSTOM_MARK, '').trim().replace(/^\||\|$/g, '').split('|').map((cell) => cell.trim());
|
|
155
|
+
const isEmptyRow = (line) => cells(line).every((cell) => cell === '');
|
|
156
|
+
|
|
157
|
+
/** La tabla que sigue a la línea `heading` de §1: índices de su primera fila de datos y de su final. */
|
|
158
|
+
function tableAfter(lines, heading) {
|
|
159
|
+
const start = lines.findIndex((line) => heading.test(line));
|
|
160
|
+
if (start === -1) return null;
|
|
161
|
+
let end = start + 1;
|
|
162
|
+
while (end < lines.length && TABLE_LINE.test(lines[end])) end += 1;
|
|
163
|
+
// Cabecera y separador: las filas empiezan detrás.
|
|
164
|
+
if (end - start - 1 < 2) return null;
|
|
165
|
+
return { rows: start + 3, end, indent: lines[start + 1].match(/^\s*/)[0], columns: cells(lines[start + 1]).length };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Una fila de excepción escrita por omk team: «Rol X | X / proveedor | equipo (omk team)». */
|
|
169
|
+
function managedRow(line) {
|
|
170
|
+
const [rol, fixed, reason] = cells(line);
|
|
171
|
+
if (reason !== MARK || !rol || !fixed) return null;
|
|
172
|
+
const [name, provider] = fixed.split('/').map((part) => part.trim());
|
|
173
|
+
return name && provider ? { name, provider } : null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const isCustomRow = (line) => line.includes(CUSTOM_MARK);
|
|
177
|
+
|
|
178
|
+
function customRow(line) {
|
|
179
|
+
const [name, work, level, review, guard = ''] = cells(line);
|
|
180
|
+
return { name: name.replace(/^\*\*|\*\*$/g, ''), work, level, review, guard };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Índice de la línea «- Nivel:» de §0 Autonomía, o -1: solo cuenta la de esa sección. */
|
|
184
|
+
function autonomyLine(lines) {
|
|
185
|
+
const heading = lines.findIndex((line) => AUTONOMY_HEADING.test(line));
|
|
186
|
+
if (heading === -1) return -1;
|
|
187
|
+
for (let i = heading + 1; i < lines.length && !/^##\s/.test(lines[i]); i += 1) {
|
|
188
|
+
if (AUTONOMY_LINE.test(lines[i])) return i;
|
|
189
|
+
}
|
|
190
|
+
return -1;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Lo que dice ORCHESTRATION.md del equipo; `null` en lo que no encuentra. */
|
|
194
|
+
function readTeam(text) {
|
|
195
|
+
const lines = text.split(/\r?\n/);
|
|
196
|
+
const autonomyAt = autonomyLine(lines);
|
|
197
|
+
const providersLine = lines.find((line) => PROVIDERS_LINE.test(line));
|
|
198
|
+
const crossLine = lines.find((line) => CROSS_LINE.test(line));
|
|
199
|
+
const exceptions = tableAfter(lines, EXCEPTIONS_LINE);
|
|
200
|
+
const rows = exceptions ? lines.slice(exceptions.rows, exceptions.end) : [];
|
|
201
|
+
const fixed = rows.map(managedRow).filter(Boolean);
|
|
202
|
+
const customTable = tableAfter(lines, CUSTOM_LINE);
|
|
203
|
+
const custom = customTable ? lines.slice(customTable.rows, customTable.end).filter(isCustomRow).map(customRow) : [];
|
|
204
|
+
return {
|
|
205
|
+
autonomy: autonomyAt === -1 ? null : lines[autonomyAt].match(AUTONOMY_LINE)[2],
|
|
206
|
+
providers: providersLine
|
|
207
|
+
? providersLine.match(PROVIDERS_LINE)[2].split(/[\s,]+/).filter((id) => id !== '')
|
|
208
|
+
: null,
|
|
209
|
+
cross: crossLine ? crossLine.match(CROSS_LINE)[2] : null,
|
|
210
|
+
roles: fixed
|
|
211
|
+
.map(({ name, provider }) => ({ id: ROLES.find(([, roleName]) => roleName === name)?.[0], provider }))
|
|
212
|
+
.filter(({ id }) => id),
|
|
213
|
+
custom: custom.map((role) => ({ ...role, provider: fixed.find(({ name }) => name === role.name)?.provider ?? null })),
|
|
214
|
+
others: rows.filter((line) => !managedRow(line) && !isEmptyRow(line)).length,
|
|
215
|
+
hasTable: exceptions !== null,
|
|
216
|
+
hasCustomTable: customTable !== null,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Sustituye las filas de una tabla por `rows`, o deja la fila vacía de la plantilla si no hay ninguna. */
|
|
221
|
+
function replaceRows(lines, table, rows) {
|
|
222
|
+
const empty = `${table.indent}|${' |'.repeat(table.columns)}`;
|
|
223
|
+
lines.splice(table.rows, table.end - table.rows, ...(rows.length ? rows : [empty]));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** El texto con los cambios de `opts` aplicados; mismo final de línea que el original. */
|
|
227
|
+
function applyTeam(text, opts) {
|
|
228
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
229
|
+
const lines = text.split(/\r?\n/);
|
|
230
|
+
const current = readTeam(text);
|
|
231
|
+
|
|
232
|
+
if (opts.autonomy) {
|
|
233
|
+
const at = autonomyLine(lines);
|
|
234
|
+
if (at === -1) throw new TeamError('ORCHESTRATION.md no tiene la línea «- Nivel:» de §0 Autonomía (regenérala con kit-init)');
|
|
235
|
+
const [, label, , comment = ''] = lines[at].match(AUTONOMY_LINE);
|
|
236
|
+
lines[at] = `${label} ${opts.autonomy}${comment}`;
|
|
237
|
+
}
|
|
238
|
+
if (opts.providers.length) {
|
|
239
|
+
const at = lines.findIndex((line) => PROVIDERS_LINE.test(line));
|
|
240
|
+
if (at === -1) throw new TeamError('ORCHESTRATION.md no tiene la línea «- Proveedores activos:» de §1 (regenérala con kit-init)');
|
|
241
|
+
const [, label, , comment = ''] = lines[at].match(PROVIDERS_LINE);
|
|
242
|
+
lines[at] = `${label} ${opts.providers.join(', ')}${comment}`;
|
|
243
|
+
}
|
|
244
|
+
if (opts.cross) {
|
|
245
|
+
const at = lines.findIndex((line) => CROSS_LINE.test(line));
|
|
246
|
+
if (at === -1) throw new TeamError('ORCHESTRATION.md no tiene la línea «- Revisión cruzada …:» de §1 (regenérala con kit-init)');
|
|
247
|
+
lines[at] = `${lines[at].match(CROSS_LINE)[1]} ${CROSS[opts.cross]}`;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const active = opts.providers.length ? opts.providers : current.providers;
|
|
251
|
+
for (const [role, provider] of opts.roles) {
|
|
252
|
+
if (provider !== 'auto' && active && !active.includes(provider)) {
|
|
253
|
+
throw new TeamError(`${ROLE_NAME.get(role)}: «${provider}» no está entre los proveedores activos (${active.join(', ')})`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Roles propios: la tabla de §1 y, para los que llevan proveedor, su fila de excepción.
|
|
258
|
+
let custom = current.custom.map(({ name, provider }) => ({ name, provider }));
|
|
259
|
+
if (opts.custom) {
|
|
260
|
+
const table = tableAfter(lines, CUSTOM_LINE);
|
|
261
|
+
if (!table) throw new TeamError('ORCHESTRATION.md no tiene la tabla «Roles propios del proyecto» de §1 (regenérala con kit-init)');
|
|
262
|
+
const own = lines.slice(table.rows, table.end).filter((line) => !isCustomRow(line) && !isEmptyRow(line));
|
|
263
|
+
const rows = opts.custom.map(({ name, work, level, review, guard }) =>
|
|
264
|
+
`${table.indent}| **${name}** | ${work} | ${level} | ${REVIEW[review]} | ${guard} | ${CUSTOM_MARK}`);
|
|
265
|
+
replaceRows(lines, table, [...own, ...rows]);
|
|
266
|
+
custom = opts.custom;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (opts.roles.size || opts.resetRoles || opts.custom) {
|
|
270
|
+
const table = tableAfter(lines, EXCEPTIONS_LINE);
|
|
271
|
+
if (!table) throw new TeamError('ORCHESTRATION.md no tiene la tabla «Excepciones al reparto por roles» de §1 (regenérala con kit-init)');
|
|
272
|
+
const fixed = new Map(opts.resetRoles ? [] : current.roles.map(({ id, provider }) => [id, provider]));
|
|
273
|
+
for (const [role, provider] of opts.roles) {
|
|
274
|
+
if (provider === 'auto') fixed.delete(role);
|
|
275
|
+
else fixed.set(role, provider);
|
|
276
|
+
}
|
|
277
|
+
// Las excepciones del usuario se quedan; las de omk team se reescriben: Olimpo y luego los propios.
|
|
278
|
+
const own = lines.slice(table.rows, table.end).filter((line) => !managedRow(line) && !isEmptyRow(line));
|
|
279
|
+
const row = (name, provider) => `${table.indent}| Rol ${name} | ${name} / ${provider} | ${MARK} |`;
|
|
280
|
+
const team = [
|
|
281
|
+
...ROLES.filter(([id]) => fixed.has(id)).map(([id, name]) => row(name, fixed.get(id))),
|
|
282
|
+
...custom.filter(({ provider }) => provider).map(({ name, provider }) => row(name, provider)),
|
|
283
|
+
];
|
|
284
|
+
replaceRows(lines, table, [...own, ...team]);
|
|
285
|
+
}
|
|
286
|
+
return lines.join(eol);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function describe(file, team) {
|
|
290
|
+
const pad = (label) => ` ${label.padEnd(21)}`;
|
|
291
|
+
const out = [`Equipo de ${file}`];
|
|
292
|
+
const autonomy = team.autonomy === null ? 'sin línea en §0'
|
|
293
|
+
: AUTONOMY.includes(team.autonomy) ? team.autonomy : `no válida (${team.autonomy})`;
|
|
294
|
+
out.push(`${pad('Autonomía')}${autonomy}`);
|
|
295
|
+
out.push(`${pad('Proveedores activos')}${team.providers?.length ? team.providers.join(', ') : 'sin línea en §1'}`);
|
|
296
|
+
const cross = team.cross === null ? 'sin línea en §1' : team.cross.includes('|') ? `sin elegir (${team.cross})` : team.cross;
|
|
297
|
+
out.push(`${pad('Revisión cruzada')}${cross}`);
|
|
298
|
+
if (!team.hasTable) out.push(`${pad('Roles fijados')}sin tabla de excepciones en §1`);
|
|
299
|
+
else if (!team.roles.length) out.push(`${pad('Roles fijados')}ninguno: todos los elige el coordinador (olimpo.md)`);
|
|
300
|
+
else {
|
|
301
|
+
const names = team.roles.map(({ id, provider }) => `${ROLE_NAME.get(id)} → ${provider}`).join(', ');
|
|
302
|
+
out.push(`${pad('Roles fijados')}${names}`);
|
|
303
|
+
out.push(`${pad('')}los demás los elige el coordinador (olimpo.md)`);
|
|
304
|
+
}
|
|
305
|
+
if (team.custom.length) {
|
|
306
|
+
team.custom.forEach(({ name, work, level, provider }, i) => {
|
|
307
|
+
out.push(`${pad(i === 0 ? 'Roles propios' : '')}${name} (${level}): ${work}${provider ? ` → ${provider}` : ''}`);
|
|
308
|
+
});
|
|
309
|
+
} else if (team.hasCustomTable) out.push(`${pad('Roles propios')}ninguno de omk team`);
|
|
310
|
+
if (team.others) out.push(`${pad('Otras excepciones')}${team.others} (tuyas; omk team no las toca)`);
|
|
311
|
+
return out.join('\n');
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** omk team: devuelve el código de salida. */
|
|
315
|
+
function main(args, { cwd = process.cwd(), out = console.log, err = console.error } = {}) {
|
|
316
|
+
try {
|
|
317
|
+
if (args[0] === 'help' || args.includes('--help') || args.includes('-h')) {
|
|
318
|
+
out(HELP);
|
|
319
|
+
return 0;
|
|
320
|
+
}
|
|
321
|
+
const opts = parseArgs(args);
|
|
322
|
+
const file = path.resolve(cwd, opts.file || 'ORCHESTRATION.md');
|
|
323
|
+
if (!fs.existsSync(file)) {
|
|
324
|
+
throw new TeamError(`no hay ${path.basename(file)} en ${path.dirname(file)}: prepara el proyecto con «inicializa el proyecto» (kit-init) u «omk init»`);
|
|
325
|
+
}
|
|
326
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
327
|
+
if (opts.action === 'set') {
|
|
328
|
+
const next = applyTeam(text, opts);
|
|
329
|
+
if (next !== text) {
|
|
330
|
+
// Escritura atómica: un corte a medias no deja ORCHESTRATION.md truncado.
|
|
331
|
+
const tmp = `${file}.omk-${process.pid}.tmp`;
|
|
332
|
+
fs.writeFileSync(tmp, next);
|
|
333
|
+
try {
|
|
334
|
+
fs.renameSync(tmp, file);
|
|
335
|
+
} catch (e) {
|
|
336
|
+
fs.rmSync(tmp, { force: true });
|
|
337
|
+
throw e;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
out(next === text ? 'Sin cambios: el equipo ya era ese.' : 'Equipo guardado.');
|
|
341
|
+
out(describe(file, readTeam(next)));
|
|
342
|
+
return 0;
|
|
343
|
+
}
|
|
344
|
+
out(describe(file, readTeam(text)));
|
|
345
|
+
return 0;
|
|
346
|
+
} catch (e) {
|
|
347
|
+
// 2: lo pedido no vale; 1: no se pudo leer o escribir el fichero.
|
|
348
|
+
err(`omk team: ${e.message}`);
|
|
349
|
+
return e instanceof TeamError ? 2 : 1;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
module.exports = { main, parseArgs, readTeam, applyTeam, ROLES, MARK };
|