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
@@ -39,6 +39,27 @@ export function withContractHint(
39
39
  return `${prompt.trimEnd()}\n\n${CONTRACT_HINT}`
40
40
  }
41
41
 
42
+ export const ORCHESTRATE_HINT =
43
+ '[Orca Multiagent Kit] Antes de empezar, y antes de la primera edición, carga la skill orca ' +
44
+ '(~/.agents/skills/orca/SKILL.md) y escribe en el chat su veredicto en una línea `ORCA: …`: si la tarea tiene ' +
45
+ '2 o más entregables separables, repártela entre agentes. La entrada es este prompt (adaptador de chat): ' +
46
+ 'no hace falta spec-kit. Si es un solo entregable, hazla tú directamente.'
47
+
48
+ // Prompts que ya pasan por la skill orca (Repartir del panel, un despacho, el propio aviso) o que
49
+ // son de kit-init: no se les añade nada. «orca-cli» u «orchestration» no cuentan como la skill orca.
50
+ const ALREADY_ROUTED = /skill\s+`?orca`?(?![\w-])|kit-init|^inicializa el proyecto$|\[Orca Multiagent Kit\] Antes de empezar/im
51
+
52
+ /**
53
+ * Devuelve el prompt de arranque con la indicación de pasar por la skill orca, o `null` si no
54
+ * hay que tocarlo: solo prompts con los que Orca arranca un agente (crear un worktree con tarea,
55
+ * una pestaña nueva, una issue), nunca lo que escribe una persona ni los despachos.
56
+ */
57
+ export function withOrchestrateHint(prompt: string, inputKind: string, enabled: boolean): string | null {
58
+ if (!enabled || inputKind !== 'launch' || prompt.trim() === '') return null
59
+ if (isKitDispatch(prompt) || ALREADY_ROUTED.test(prompt.trim())) return null
60
+ return `${prompt.trimEnd()}\n\n${ORCHESTRATE_HINT}`
61
+ }
62
+
42
63
  // Mensajes de "comando no encontrado" de bash, zsh, fish, cmd y PowerShell (inglés y español).
43
64
  const MISSING_COMMAND =
44
65
  /command not found|not recognized|unknown command|no se reconoce|orden no encontrada|no se encontr[oó] la orden/i
@@ -49,28 +70,72 @@ export function isMissingCommand(lines: readonly string[], command = 'omk'): boo
49
70
  return lines.some((line) => name.test(line) && MISSING_COMMAND.test(line))
50
71
  }
51
72
 
52
- export type PollOptions = {
53
- attempts: number
54
- delayMs: number
55
- sleep: (ms: number) => Promise<void>
73
+ export const INSTALL_HINT =
74
+ 'Instálalo con `npm install -g orca-multiagent-kit` o con el ejecutable de la última release (lo deja en el PATH), ' +
75
+ 'reinicia Orca y vuelve a lanzar el comando.'
76
+
77
+ /**
78
+ * Opción con la que `omk` escribe al salir una línea `[omk:fin] <comando> salida=<código>`
79
+ * (bin/omk.js): es como el plugin sabe que el comando de un terminal ha terminado y cómo.
80
+ */
81
+ export const EXIT_MARKER_FLAG = '--exit-marker'
82
+
83
+ const EXIT_MARKER = /\[omk:fin\] \S+ salida=(\d{1,3})(?!\d)/
84
+ // Un omk anterior a la opción la rechaza: «Opcion desconocida: --exit-marker».
85
+ const UNKNOWN_EXIT_MARKER = /desconocid[ao][^\n]*--exit-marker/i
86
+ // La pregunta de aprobación de `omk` (bin/setup.js): «¿Apruebas este acceso? [s/N]».
87
+ const YES_NO_PROMPT = /\[s\/N\]\s*$/
88
+
89
+ export const OLD_OMK_HINT =
90
+ 'El omk instalado es anterior a este plugin y no avisa cuando termina. Actualízalo en un terminal con ' +
91
+ '`npm install -g orca-multiagent-kit@latest` (o con el ejecutable de la última release) y repite.'
92
+
93
+ /** El código con el que terminó `omk`, si su línea de cierre ya está en la salida; si no, `null`. */
94
+ export function exitCodeOf(lines: readonly string[]): number | null {
95
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
96
+ const code = EXIT_MARKER.exec(lines[i] ?? '')?.[1]
97
+ if (code !== undefined) return Number(code)
98
+ }
99
+ return null
100
+ }
101
+
102
+ /** Si la salida dice que este `omk` no conoce la opción de la línea de cierre. */
103
+ export function lacksExitMarker(lines: readonly string[]): boolean {
104
+ return lines.some((line) => UNKNOWN_EXIT_MARKER.test(line))
56
105
  }
57
106
 
58
- /** Lee la salida hasta `attempts` veces, esperando `delayMs` antes de cada lectura. */
59
- export async function pollUntil(
60
- read: () => Promise<readonly string[]>,
61
- matches: (lines: readonly string[]) => boolean,
62
- options: PollOptions
63
- ): Promise<boolean> {
64
- for (let attempt = 0; attempt < options.attempts; attempt += 1) {
65
- await options.sleep(options.delayMs)
66
- if (matches(await read())) return true
107
+ /** Si lo último que hay en la salida es una pregunta de sí o no de `omk`. */
108
+ export function isYesNoPrompt(lines: readonly string[]): boolean {
109
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
110
+ const line = lines[i] ?? ''
111
+ if (line.trim() !== '') return YES_NO_PROMPT.test(line)
67
112
  }
68
113
  return false
69
114
  }
70
115
 
71
- export const INSTALL_HINT =
72
- 'Instálalo con `npm install -g orca-multiagent-kit` o con el ejecutable de la última release (lo deja en el PATH), ' +
73
- 'reinicia Orca y vuelve a lanzar el comando.'
116
+ // Códigos de escape de terminal (CSI y OSC); se quitan antes que los demás caracteres de control.
117
+ export const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g
118
+
119
+ export const OUTPUT_LINES = 80
120
+ export const OUTPUT_LINE_MAX = 240
121
+
122
+ /**
123
+ * La salida de un terminal lista para enseñarla: sin códigos de escape, caracteres de control ni
124
+ * de formato, sin la línea de cierre de `omk` ni huecos al final, con su sangría, y acotada a las
125
+ * últimas `max` líneas de hasta `OUTPUT_LINE_MAX` caracteres. De una línea repintada con retornos
126
+ * de carro (un spinner, si Orca da la salida acumulada y no la pantalla) queda lo último pintado.
127
+ */
128
+ export function outputLines(lines: readonly string[], max = OUTPUT_LINES): string[] {
129
+ const clean: string[] = []
130
+ for (const line of lines) {
131
+ const painted = line.replace(ANSI, '').split('\r').filter((part) => part.trim() !== '')
132
+ const text = (painted[painted.length - 1] ?? '').replace(/[\p{Cc}\p{Cf}]/gu, ' ').trimEnd()
133
+ if (EXIT_MARKER.test(text)) continue
134
+ clean.push(text.length > OUTPUT_LINE_MAX ? `${text.slice(0, OUTPUT_LINE_MAX - 1)}…` : text)
135
+ }
136
+ while (clean.length > 0 && clean[clean.length - 1] === '') clean.pop()
137
+ return clean.slice(-max)
138
+ }
74
139
 
75
140
  export type FocusedWorkspace = { branch: string; displayName: string }
76
141
  export type WorkspaceEntry = { id: string; name: string; branch: string | null }
@@ -85,8 +150,10 @@ export function resolveFocusedWorkspaceId(
85
150
  workspaces: readonly WorkspaceEntry[]
86
151
  ): string | null {
87
152
  if (!focused) return null
153
+ // Orca da la rama unas veces como `main` y otras como `refs/heads/main`.
154
+ const branch = (name: string | null) => (name ?? '').replace(/^refs\/heads\//, '')
88
155
  const matches = workspaces.filter(
89
- (w) => w.name === focused.displayName && (w.branch ?? '') === focused.branch
156
+ (w) => w.name === focused.displayName && branch(w.branch) === branch(focused.branch)
90
157
  )
91
158
  return matches.length === 1 ? (matches[0]?.id ?? null) : null
92
159
  }
@@ -106,8 +173,158 @@ export function isValidAgentId(value: unknown): value is string {
106
173
  return typeof value === 'string' && AGENT_ID.test(value)
107
174
  }
108
175
 
176
+ /**
177
+ * Agentes del catálogo de Orca que ofrecen los desplegables del panel: ids que acepta
178
+ * `agent.launch` (los de `orca agent launch --agent`). Orca tiene más; estos son los habituales.
179
+ */
180
+ export const KNOWN_AGENTS: readonly { id: string; label: string }[] = [
181
+ { id: 'claude', label: 'Claude Code' },
182
+ { id: 'codex', label: 'Codex' },
183
+ { id: 'gemini', label: 'Gemini CLI' },
184
+ { id: 'antigravity', label: 'Antigravity' },
185
+ { id: 'copilot', label: 'GitHub Copilot' },
186
+ { id: 'cursor', label: 'Cursor' },
187
+ { id: 'opencode', label: 'OpenCode' },
188
+ { id: 'amp', label: 'Amp' },
189
+ { id: 'droid', label: 'Droid' },
190
+ { id: 'grok', label: 'Grok' },
191
+ { id: 'kimi', label: 'Kimi' },
192
+ { id: 'qwen-code', label: 'Qwen Code' },
193
+ { id: 'aider', label: 'Aider' },
194
+ { id: 'goose', label: 'Goose' },
195
+ { id: 'cline', label: 'Cline' },
196
+ { id: 'kiro', label: 'Kiro' },
197
+ { id: 'devin', label: 'Devin' }
198
+ ]
199
+
200
+ export function agentLabel(id: string): string {
201
+ return KNOWN_AGENTS.find((agent) => agent.id === id)?.label ?? id
202
+ }
203
+
204
+ /** Opciones de un desplegable de agentes: el catálogo y, si no están en él, los valores actuales. */
205
+ export function agentOptions(current: readonly string[] = []): { value: string; label: string }[] {
206
+ const options = KNOWN_AGENTS.map(({ id, label }) => ({ value: id, label }))
207
+ for (const id of current) {
208
+ if (isValidAgentId(id) && !options.some((option) => option.value === id)) options.push({ value: id, label: id })
209
+ }
210
+ return options
211
+ }
212
+
109
213
  export type AgentState = 'working' | 'blocked' | 'waiting' | 'done'
110
- export type TrackedAgent = { workspaceId: string | null; title: string | null; state: AgentState }
214
+
215
+ /** Lo que el despacho de la skill `orca` dice de su unidad: cabecera UNIT/RUN y línea ROL. */
216
+ export type UnitInfo = { unit: string; title: string | null; run: string; role: string | null }
217
+
218
+ /** Un agente tal como lo sigue el worker: lo que cuenta Orca más lo aprendido de sus hooks. */
219
+ export type TrackedAgent = {
220
+ workspaceId: string | null
221
+ /** El título que da Orca, si da alguno. */
222
+ title: string | null
223
+ state: AgentState
224
+ /** Id del agente (claude, codex…), de `agents.list` o de los hooks. */
225
+ agent?: string | null
226
+ unit?: UnitInfo | null
227
+ /** Desde cuándo está en este estado, en ms desde epoch. */
228
+ since?: number | null
229
+ /** Su terminal; `null` en un chat de Orca. */
230
+ terminalId?: string | null
231
+ /** Cómo acabó el último turno del agente principal, si Orca lo dice. */
232
+ outcome?: string | null
233
+ /** Cuándo llegó el último evento suyo. */
234
+ updatedAt?: number | null
235
+ }
236
+
237
+ const LABEL_MAX = 80
238
+ const UNIT_HEADER = /^[ \t]*UNIT:[ \t]*(U\d+)\b([^\n]*)/m
239
+ const RUN_VALUE = /\bRUN:[ \t]*(\S+)/
240
+ // «ROL: Ariadna · código sensible · nivel alto — …»: el nombre del rol abre la línea.
241
+ const ROLE_LINE = /^[ \t]*ROL:[ \t]*(\p{L}[\p{L}\p{M}-]*)/mu
242
+
243
+ /**
244
+ * Texto apto para una etiqueta: una línea, sin caracteres de control ni de formato (el título
245
+ * de un terminal y los despachos los escribe un agente) y acotado. `null` si no queda nada.
246
+ */
247
+ export function cleanLabel(text: string, max = LABEL_MAX): string | null {
248
+ const clean = text.replace(/[\p{Cc}\p{Cf}]+/gu, ' ').replace(/\s+/g, ' ').trim()
249
+ if (clean === '') return null
250
+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean
251
+ }
252
+
253
+ /** La unidad de un despacho de la skill `orca` (skills/orca/SKILL.md §5), o `null` si no lo es. */
254
+ export function parseDispatch(prompt: string): UnitInfo | null {
255
+ const header = UNIT_HEADER.exec(prompt)
256
+ if (!header) return null
257
+ const [, unit = '', rest = ''] = header
258
+ const runInHeader = RUN_VALUE.exec(rest)
259
+ const run = cleanLabel((runInHeader ?? RUN_VALUE.exec(prompt))?.[1] ?? '', 60)
260
+ if (run === null) return null
261
+ const title = runInHeader ? rest.slice(0, runInHeader.index) : rest
262
+ const role = ROLE_LINE.exec(prompt)?.[1]
263
+ return {
264
+ unit,
265
+ title: cleanLabel(title.replace(/^\s*[—–-]\s*/, '')),
266
+ run,
267
+ role: role === undefined ? null : cleanLabel(role, 30)
268
+ }
269
+ }
270
+
271
+ /** Una ruta comparable entre las formas que usa Orca (`C:\x`, `C:/x/`). */
272
+ export function normalizePath(path: string): string {
273
+ const slashes = path.replace(/\\/g, '/').replace(/\/+$/, '')
274
+ return /^[a-z]:\//i.test(slashes) ? slashes.toLowerCase() : slashes
275
+ }
276
+
277
+ export type WorkspaceInfo = { name: string; path: string; branch: string | null; kind: string | null }
278
+
279
+ /** Los workspaces de `workspace.list`: sus datos por id y el id por ruta. */
280
+ export type WorkspaceIndex = { byId: Map<string, WorkspaceInfo>; byPath: Map<string, string> }
281
+
282
+ export function indexWorkspaces(
283
+ workspaces: readonly { id: string; name: string; path: string; branch?: string | null; kind?: string | null }[]
284
+ ): WorkspaceIndex {
285
+ const index: WorkspaceIndex = { byId: new Map(), byPath: new Map() }
286
+ for (const { id, name, path, branch = null, kind = null } of workspaces) {
287
+ index.byId.set(id, {
288
+ name: cleanLabel(name, 60) ?? id,
289
+ path,
290
+ branch: branch ? branch.replace(/^refs\/heads\//, '') : null,
291
+ kind
292
+ })
293
+ index.byPath.set(normalizePath(path), id)
294
+ }
295
+ return index
296
+ }
297
+
298
+ /**
299
+ * El id con el que `workspace.list` conoce un workspace. Los eventos de agentes lo dan a veces
300
+ * como `<repo>::<ruta>` y la lista como `identity:…`: entonces se cruzan por la ruta. Sin
301
+ * coincidencia, el id tal cual.
302
+ */
303
+ export function canonicalWorkspaceId(id: string, index: WorkspaceIndex): string {
304
+ if (index.byId.has(id)) return id
305
+ const separator = id.indexOf('::')
306
+ if (separator === -1) return id
307
+ return index.byPath.get(normalizePath(id.slice(separator + 2))) ?? id
308
+ }
309
+
310
+ // Los chats de agente de Orca no tienen terminal; su panel se llama
311
+ // «structured-agent-session-<agente>_<sesión>:…». Si Orca cambia el formato, no se reconoce y ya.
312
+ const STRUCTURED_SESSION = /^structured-agent-session-([a-z0-9][a-z0-9-]*?)_/
313
+
314
+ /** El agente de un chat de Orca, sacado de su panel, o `null`. */
315
+ export function agentFromPaneKey(paneKey: string): string | null {
316
+ return STRUCTURED_SESSION.exec(paneKey)?.[1] ?? null
317
+ }
318
+
319
+ /** El nombre de un agente: su unidad del kit, el título de Orca o, como mínimo, qué agente es. */
320
+ export function agentName(agent: TrackedAgent): string {
321
+ const { unit } = agent
322
+ if (unit) {
323
+ const head = unit.role ? `${unit.unit} · ${unit.role}` : unit.unit
324
+ return unit.title ? `${head} — ${unit.title}` : head
325
+ }
326
+ return agent.title ?? agent.agent ?? 'agente sin título'
327
+ }
111
328
 
112
329
  export type AgentSummary = {
113
330
  text: string
@@ -115,13 +332,112 @@ export type AgentSummary = {
115
332
  tooltip: string
116
333
  }
117
334
 
118
- const STATE_LABEL: Record<Exclude<AgentState, 'done'>, [string, string]> = {
335
+ export type AgentLine = {
336
+ /** Clave del agente en el worker: el panel la devuelve para abrir su workspace. */
337
+ id: string
338
+ title: string
339
+ /** Id del agente (claude, codex…), para su icono; `null` si no se sabe. */
340
+ agent?: string | null
341
+ state: string
342
+ blocked: boolean
343
+ /** Qué agente es y en qué workspace, lo que se sepa: «codex · palolo». */
344
+ detail: string
345
+ since: number | null
346
+ canOpen: boolean
347
+ /** Todo lo que se sabe del agente, para su ficha en el panel. */
348
+ facts: { label: string; value: string }[]
349
+ }
350
+
351
+ /** Agentes de un mismo run del kit o, fuera del kit, de un mismo workspace. */
352
+ export type AgentGroup = { title: string; agents: AgentLine[] }
353
+
354
+ type ActiveState = Exclude<AgentState, 'done'>
355
+
356
+ const STATE_LABEL: Record<ActiveState, [string, string]> = {
119
357
  working: ['trabajando', 'trabajando'],
120
358
  blocked: ['bloqueado', 'bloqueados'],
121
359
  waiting: ['esperando', 'esperando']
122
360
  }
123
361
 
124
- export function summarizeAgents(agents: Iterable<TrackedAgent>): AgentSummary {
362
+ // Primero lo que necesita a la persona.
363
+ const STATE_RANK: Record<ActiveState, number> = { blocked: 0, waiting: 1, working: 2 }
364
+
365
+ const TOOLTIP_AGENTS = 6
366
+
367
+ const OUTCOME_LABEL: Record<string, string> = {
368
+ success: 'terminó bien',
369
+ failure: 'falló',
370
+ cancellation: 'cancelado',
371
+ superseded: 'sustituido',
372
+ interruption: 'interrumpido',
373
+ unconfirmed: 'sin confirmar'
374
+ }
375
+
376
+ /** La ficha de un agente: solo lo que se sabe, en el orden en que se lee. */
377
+ function agentFacts(agent: TrackedAgent, title: string, workspace: WorkspaceInfo | null): AgentLine['facts'] {
378
+ const { unit } = agent
379
+ const level = unit?.role ? TEAM_ROLES.find(({ name }) => name === unit.role)?.level : undefined
380
+ const facts: [string, string | null | undefined][] = [
381
+ ['Agente', agent.agent ? agentLabel(agent.agent) : null],
382
+ ['Unidad', unit ? (unit.title ? `${unit.unit} — ${unit.title}` : unit.unit) : null],
383
+ ['Rol', unit?.role ? (level ? `${unit.role} · nivel ${level}` : unit.role) : null],
384
+ ['Run', unit?.run],
385
+ ['Título en Orca', agent.title && agent.title !== title ? agent.title : null],
386
+ ['Workspace', workspace?.name],
387
+ ['Rama', workspace?.branch],
388
+ ['Carpeta', workspace?.path],
389
+ ['Dónde corre', agent.terminalId ? `terminal ${agent.terminalId}` : agent.terminalId === null ? 'chat de Orca' : null],
390
+ ['Último turno', agent.outcome ? (OUTCOME_LABEL[agent.outcome] ?? agent.outcome) : null]
391
+ ]
392
+ return facts.flatMap(([label, value]) => (value ? [{ label, value }] : []))
393
+ }
394
+
395
+ /** Los agentes activos por run o workspace; los grupos y sus agentes, primero los bloqueados. */
396
+ export function groupAgents(
397
+ agents: Iterable<readonly [string, TrackedAgent]>,
398
+ workspaces: ReadonlyMap<string, WorkspaceInfo>
399
+ ): AgentGroup[] {
400
+ const rows: { group: string; rank: number; line: AgentLine }[] = []
401
+ for (const [id, agent] of agents) {
402
+ if (agent.state === 'done') continue
403
+ const info = agent.workspaceId ? (workspaces.get(agent.workspaceId) ?? null) : null
404
+ const workspace = info?.name ?? null
405
+ const title = agentName(agent)
406
+ const detail = [agent.agent === title ? null : agent.agent, workspace]
407
+ .filter((part): part is string => Boolean(part))
408
+ .join(' · ')
409
+ rows.push({
410
+ group: agent.unit
411
+ ? `RUN ${agent.unit.run}`
412
+ : (workspace ?? (agent.workspaceId ? 'Workspace sin nombre' : 'Sin workspace')),
413
+ rank: STATE_RANK[agent.state],
414
+ line: {
415
+ id,
416
+ title,
417
+ agent: agent.agent ?? null,
418
+ state: STATE_LABEL[agent.state][0],
419
+ blocked: agent.state === 'blocked',
420
+ detail,
421
+ since: agent.since ?? null,
422
+ canOpen: agent.workspaceId !== null,
423
+ facts: agentFacts(agent, title, info)
424
+ }
425
+ })
426
+ }
427
+ rows.sort((a, b) => a.rank - b.rank || a.line.title.localeCompare(b.line.title, 'es'))
428
+ const groups = new Map<string, AgentLine[]>()
429
+ for (const { group, line } of rows) {
430
+ const lines = groups.get(group)
431
+ if (lines) lines.push(line)
432
+ else groups.set(group, [line])
433
+ }
434
+ return [...groups].map(([title, lines]) => ({ title, agents: lines }))
435
+ }
436
+
437
+ export function summarizeAgents(
438
+ agents: Iterable<TrackedAgent>,
439
+ groups: readonly AgentGroup[] = []
440
+ ): AgentSummary {
125
441
  const counts = { working: 0, blocked: 0, waiting: 0 }
126
442
  for (const agent of agents) {
127
443
  if (agent.state !== 'done') counts[agent.state] += 1
@@ -130,30 +446,364 @@ export function summarizeAgents(agents: Iterable<TrackedAgent>): AgentSummary {
130
446
  .filter((state) => counts[state] > 0)
131
447
  .map((state) => `${counts[state]} ${STATE_LABEL[state][counts[state] === 1 ? 0 : 1]}`)
132
448
  const tone = counts.blocked > 0 ? 'warning' : counts.working > 0 ? 'accent' : 'neutral'
449
+ if (parts.length === 0) {
450
+ return { text: 'MAW', tone, tooltip: 'Orca Multiagent Kit: ningún agente activo' }
451
+ }
452
+ const named = groups.flatMap((group) => group.agents).map(({ title, state }) => `${title}: ${state}`)
453
+ const more = named.length > TOOLTIP_AGENTS ? [`… y ${named.length - TOOLTIP_AGENTS} más`] : []
133
454
  return {
134
- text: parts.length > 0 ? `MAW · ${parts.join(' · ')}` : 'MAW',
455
+ text: `MAW · ${parts.join(' · ')}`,
135
456
  tone,
136
- tooltip:
137
- parts.length > 0
138
- ? `Orca Multiagent Kit: ${parts.join(', ')} en todos los workspaces`
139
- : 'Orca Multiagent Kit: ningún agente activo'
457
+ tooltip: [
458
+ `Orca Multiagent Kit: ${parts.join(', ')} en todos los workspaces`,
459
+ ...named.slice(0, TOOLTIP_AGENTS),
460
+ ...more
461
+ ].join('\n')
140
462
  }
141
463
  }
142
464
 
143
- export type AgentLine = { title: string; state: string }
465
+ /** Una línea por agente activo, para el comando «estado de los agentes». */
466
+ export function describeAgents(groups: readonly AgentGroup[]): string {
467
+ const lines = groups.flatMap(({ agents }) =>
468
+ agents.map(({ title, state, detail }) => `- ${title}: ${state}${detail ? ` (${detail})` : ''}`)
469
+ )
470
+ return lines.length > 0 ? lines.join('\n') : 'Ningún agente activo.'
471
+ }
144
472
 
145
- /** Los agentes activos con su estado en texto, para el panel y el comando. */
146
- export function agentLines(agents: Iterable<TrackedAgent>): AgentLine[] {
147
- const lines: AgentLine[] = []
148
- for (const agent of agents) {
149
- if (agent.state === 'done') continue
150
- lines.push({ title: agent.title ?? 'agente sin título', state: STATE_LABEL[agent.state][0] })
473
+ export type Notice = { title: string; body: string }
474
+
475
+ /** El aviso de un agente que acaba de bloquearse, o `null` si ya lo estaba o no lo está. */
476
+ export function blockedNotice(
477
+ previous: AgentState | undefined,
478
+ agent: TrackedAgent,
479
+ workspace: string | null
480
+ ): Notice | null {
481
+ if (agent.state !== 'blocked' || previous === 'blocked') return null
482
+ return {
483
+ title: `${agentName(agent)}: bloqueado`,
484
+ body: workspace ? `En ${workspace}. Necesita tu respuesta en Orca.` : 'Necesita tu respuesta en Orca.'
151
485
  }
152
- return lines
153
486
  }
154
487
 
155
- /** Una línea por agente activo, para el comando «estado de los agentes». */
156
- export function describeAgents(agents: Iterable<TrackedAgent>): string {
157
- const lines = agentLines(agents).map(({ title, state }) => `- ${title}: ${state}`)
158
- return lines.length > 0 ? lines.join('\n') : 'Ningún agente activo.'
488
+ /** Por run del kit: las unidades que siguen activas y las que ya terminaron en esta tanda. */
489
+ export type RunProgress = Map<string, { active: Set<string>; finished: number }>
490
+
491
+ /**
492
+ * Anota el estado de una unidad. Si con ella terminan todas las lanzadas del run, devuelve el
493
+ * aviso y la tanda vuelve a cero: la ronda siguiente avisa otra vez.
494
+ */
495
+ export function trackRun(runs: RunProgress, run: string, id: string, state: AgentState): Notice | null {
496
+ const progress = runs.get(run)
497
+ if (state !== 'done') {
498
+ if (progress) progress.active.add(id)
499
+ else runs.set(run, { active: new Set([id]), finished: 0 })
500
+ return null
501
+ }
502
+ if (!progress?.active.delete(id)) return null
503
+ progress.finished += 1
504
+ if (progress.active.size > 0) return null
505
+ runs.delete(run)
506
+ const { finished } = progress
507
+ return {
508
+ title: `RUN ${run}: unidades terminadas`,
509
+ body:
510
+ `${finished === 1 ? 'La unidad lanzada ha' : `Las ${finished} unidades lanzadas han`} terminado. ` +
511
+ 'Vuelve al coordinador para revisar e integrar.'
512
+ }
513
+ }
514
+
515
+ /** Olvida una unidad sin avisar: su workspace ya no existe. */
516
+ export function forgetRunUnit(runs: RunProgress, id: string): void {
517
+ for (const [run, progress] of runs) {
518
+ progress.active.delete(id)
519
+ if (progress.active.size === 0) runs.delete(run)
520
+ }
521
+ }
522
+
523
+ /** Roles de Olimpo que se fijan a un proveedor (skills/orca/references/olimpo.md); Hefesto es el coordinador. */
524
+ export const TEAM_ROLES = [
525
+ { id: 'dedalo', name: 'Dédalo', work: 'arquitectura', level: 'alto' },
526
+ { id: 'casandra', name: 'Casandra', work: 'seguridad', level: 'alto' },
527
+ { id: 'temis', name: 'Temis', work: 'normativa', level: 'alto' },
528
+ { id: 'ariadna', name: 'Ariadna', work: 'código sensible', level: 'alto' },
529
+ { id: 'persefone', name: 'Perséfone', work: 'datos', level: 'medio' },
530
+ { id: 'proteo', name: 'Proteo', work: 'implementación', level: 'medio' },
531
+ { id: 'narciso', name: 'Narciso', work: 'interfaz', level: 'medio' },
532
+ { id: 'icaro', name: 'Ícaro', work: 'integraciones', level: 'medio' },
533
+ { id: 'argos', name: 'Argos', work: 'verificación', level: 'medio' },
534
+ { id: 'atlas', name: 'Atlas', work: 'plataforma', level: 'medio' },
535
+ { id: 'clio', name: 'Clío', work: 'mecánico', level: 'bajo' }
536
+ ] as const
537
+
538
+ export type RoleId = (typeof TEAM_ROLES)[number]['id']
539
+
540
+ /** Qué unidades revisa otro proveedor: `ORCHESTRATION.md` §1 «Revisión cruzada». */
541
+ export type CrossReview = 'sensibles' | 'todas' | 'nunca'
542
+
543
+ export const CROSS_REVIEW: readonly CrossReview[] = ['sensibles', 'todas', 'nunca']
544
+
545
+ export type RoleLevel = 'alto' | 'medio' | 'bajo'
546
+
547
+ export const ROLE_LEVELS: readonly RoleLevel[] = ['alto', 'medio', 'bajo']
548
+
549
+ /** Quién revisa lo que hace un rol propio (columna «Revisión» de `olimpo.md`). */
550
+ export type CustomReview = 'propia' | 'cross' | 'argos' | 'casandra'
551
+
552
+ export const CUSTOM_REVIEWS: readonly { id: CustomReview; label: string }[] = [
553
+ { id: 'propia', label: 'Propia' },
554
+ { id: 'cross', label: 'Cruzada (otro proveedor)' },
555
+ { id: 'argos', label: 'Argos (verificación)' },
556
+ { id: 'casandra', label: 'Casandra (seguridad)' }
557
+ ]
558
+
559
+ /** Un rol propio del proyecto: va a la tabla «Roles propios del proyecto» de `ORCHESTRATION.md` §1. */
560
+ export type CustomRole = {
561
+ name: string
562
+ work: string
563
+ level: RoleLevel
564
+ review: CustomReview
565
+ guard: string
566
+ /** Proveedor fijado, o `null` para que lo elija el coordinador. */
567
+ provider: string | null
568
+ }
569
+
570
+ export const CUSTOM_ROLES_MAX = 10
571
+ export const ROLE_WORK_MAX = 80
572
+ export const ROLE_GUARD_MAX = 120
573
+ const ROLE_NAME = /^\p{L}[\p{L}\p{M}\p{N} -]{0,29}$/u
574
+ const RESERVED_ROLE_NAMES = ['Hefesto', ...TEAM_ROLES.map(({ name }) => name)].map((name) => name.toLocaleLowerCase('es'))
575
+
576
+ /** Si `name` vale como nombre de un rol nuevo: letras, números, espacios y guiones, y que no exista ya. */
577
+ export function isValidRoleName(name: string, others: readonly string[] = []): boolean {
578
+ const key = name.trim().toLocaleLowerCase('es')
579
+ return (
580
+ ROLE_NAME.test(name.trim()) &&
581
+ !RESERVED_ROLE_NAMES.includes(key) &&
582
+ !others.some((other) => other.trim().toLocaleLowerCase('es') === key)
583
+ )
584
+ }
585
+
586
+ /** Texto libre para una celda de tabla Markdown: una línea, sin `|`, `<` ni `>`, acotado. */
587
+ export function cellText(text: string, max: number): string | null {
588
+ return cleanLabel(text.replace(/[|<>]/g, ' '), max)
589
+ }
590
+
591
+ function parseCustomRole(value: unknown, providers: readonly string[], others: readonly string[]): CustomRole | null {
592
+ if (typeof value !== 'object' || value === null) return null
593
+ const { name, work, level, review, guard, provider } = value as Record<string, unknown>
594
+ if (typeof name !== 'string' || !isValidRoleName(name, others)) return null
595
+ const cleanWork = typeof work === 'string' ? cellText(work, ROLE_WORK_MAX) : null
596
+ const cleanGuard = typeof guard === 'string' ? (cellText(guard, ROLE_GUARD_MAX) ?? '') : null
597
+ const roleLevel = ROLE_LEVELS.find((candidate) => candidate === level)
598
+ const roleReview = CUSTOM_REVIEWS.find((candidate) => candidate.id === review)?.id
599
+ if (!cleanWork || cleanGuard === null || !roleLevel || !roleReview) return null
600
+ if (provider !== null && (!isValidAgentId(provider) || !providers.includes(provider))) return null
601
+ return { name: name.trim(), work: cleanWork, level: roleLevel, review: roleReview, guard: cleanGuard, provider }
602
+ }
603
+
604
+ export type Team = {
605
+ /** Quién coordina (Hefesto) al orquestar desde el panel. No va a ORCHESTRATION.md. */
606
+ coordinator: string
607
+ providers: string[]
608
+ cross: CrossReview
609
+ /** Proveedor fijado por rol; un rol ausente lo elige el coordinador. */
610
+ roles: Partial<Record<RoleId, string>>
611
+ custom: CustomRole[]
612
+ }
613
+
614
+ export type TeamPreset = 'claude' | 'claude-codex' | 'codex-claude'
615
+
616
+ const everyRole = (provider: string, overrides: Partial<Record<RoleId, string>>) =>
617
+ Object.fromEntries(TEAM_ROLES.map(({ id }) => [id, overrides[id] ?? provider])) as Record<RoleId, string>
618
+
619
+ export const TEAM_PRESETS: Readonly<Record<TeamPreset, { label: string; team: Team }>> = {
620
+ claude: {
621
+ label: 'Solo Claude',
622
+ team: { coordinator: 'claude', providers: ['claude'], cross: 'sensibles', roles: {}, custom: [] }
623
+ },
624
+ 'claude-codex': {
625
+ label: 'Claude + Codex revisor',
626
+ team: {
627
+ coordinator: 'claude',
628
+ providers: ['claude', 'codex'],
629
+ cross: 'sensibles',
630
+ roles: everyRole('claude', { casandra: 'codex' }),
631
+ custom: []
632
+ }
633
+ },
634
+ 'codex-claude': {
635
+ label: 'Codex + Claude revisor',
636
+ team: {
637
+ coordinator: 'codex',
638
+ providers: ['codex', 'claude'],
639
+ cross: 'sensibles',
640
+ roles: everyRole('codex', { casandra: 'claude' }),
641
+ custom: []
642
+ }
643
+ }
644
+ }
645
+
646
+ export function isRoleId(value: unknown): value is RoleId {
647
+ return TEAM_ROLES.some(({ id }) => id === value)
648
+ }
649
+
650
+ const MAX_PROVIDERS = 8
651
+
652
+ /**
653
+ * Un equipo que llega del panel, validado entero: ids de agente, revisión cruzada conocida,
654
+ * cada rol con un proveedor activo y roles propios bien formados. `null` ante cualquier otra cosa.
655
+ */
656
+ export function parseTeam(value: unknown): Team | null {
657
+ if (typeof value !== 'object' || value === null) return null
658
+ const { coordinator, providers, cross, roles, custom } = value as Record<string, unknown>
659
+ if (!isValidAgentId(coordinator)) return null
660
+ if (!Array.isArray(providers) || providers.length === 0 || providers.length > MAX_PROVIDERS) return null
661
+ if (!providers.every(isValidAgentId) || new Set(providers).size !== providers.length) return null
662
+ const crossReview = CROSS_REVIEW.find((mode) => mode === cross)
663
+ if (!crossReview) return null
664
+ if (typeof roles !== 'object' || roles === null || Array.isArray(roles)) return null
665
+ const fixed: Partial<Record<RoleId, string>> = {}
666
+ for (const [role, provider] of Object.entries(roles)) {
667
+ if (!isRoleId(role) || !isValidAgentId(provider) || !providers.includes(provider)) return null
668
+ fixed[role] = provider
669
+ }
670
+ if (!Array.isArray(custom) || custom.length > CUSTOM_ROLES_MAX) return null
671
+ const own: CustomRole[] = []
672
+ for (const role of custom) {
673
+ const parsed = parseCustomRole(role, providers, own.map(({ name }) => name))
674
+ if (!parsed) return null
675
+ own.push(parsed)
676
+ }
677
+ return { coordinator, providers: [...providers], cross: crossReview, roles: fixed, custom: own }
678
+ }
679
+
680
+ /** El equipo tal como se edita en el panel. */
681
+ export type TeamDraft = Team & { preset: TeamPreset | 'custom' }
682
+
683
+ export function draftFromPreset(id: TeamPreset): TeamDraft {
684
+ const { team } = TEAM_PRESETS[id]
685
+ return { ...team, preset: id, providers: [...team.providers], roles: { ...team.roles }, custom: [] }
686
+ }
687
+
688
+ /**
689
+ * Un borrador guardado por una versión anterior del panel (proveedores como texto, sin roles
690
+ * propios) o dañado, convertido al formato de ahora. Lo que no se entiende vuelve a «Solo Claude».
691
+ */
692
+ export function normalizeDraft(value: unknown): TeamDraft {
693
+ const base = draftFromPreset('claude')
694
+ if (typeof value !== 'object' || value === null) return base
695
+ const old = value as Record<string, unknown>
696
+ const providers = (
697
+ Array.isArray(old.providers) ? old.providers : typeof old.providers === 'string' ? old.providers.split(/[\s,]+/) : []
698
+ ).filter(isValidAgentId)
699
+ const active = providers.length > 0 ? [...new Set(providers)] : base.providers
700
+ const roles = typeof old.roles === 'object' && old.roles !== null ? Object.entries(old.roles) : []
701
+ const draft: TeamDraft = {
702
+ ...base,
703
+ preset: 'custom',
704
+ coordinator: isValidAgentId(old.coordinator) ? old.coordinator : base.coordinator,
705
+ providers: active,
706
+ cross: CROSS_REVIEW.find((mode) => mode === old.cross) ?? base.cross,
707
+ roles: Object.fromEntries(
708
+ roles.filter(([role, provider]) => isRoleId(role) && typeof provider === 'string' && active.includes(provider))
709
+ ),
710
+ custom: Array.isArray(old.custom) ? (old.custom as CustomRole[]) : []
711
+ }
712
+ return teamFromDraft(draft) ? draft : base
713
+ }
714
+
715
+ export function emptyCustomRole(): CustomRole {
716
+ return { name: '', work: '', level: 'medio', review: 'propia', guard: '', provider: null }
717
+ }
718
+
719
+ /**
720
+ * El equipo de un borrador, o `null` si no es válido. Un rol cuyo proveedor ya no está entre
721
+ * los activos vuelve a «lo elige el coordinador».
722
+ */
723
+ export function teamFromDraft(draft: TeamDraft): Team | null {
724
+ const { providers } = draft
725
+ const roles = Object.fromEntries(
726
+ Object.entries(draft.roles).filter(([, provider]) => provider !== undefined && providers.includes(provider))
727
+ )
728
+ const custom = draft.custom.map((role) => ({
729
+ ...role,
730
+ provider: role.provider !== null && providers.includes(role.provider) ? role.provider : null
731
+ }))
732
+ return parseTeam({ coordinator: draft.coordinator, providers, cross: draft.cross, roles, custom })
733
+ }
734
+
735
+ /** El equipo en JSON y base64url: llega al terminal sin un solo carácter que un shell interprete. */
736
+ export function encodeTeam(team: Team): string {
737
+ const { providers, cross, roles, custom } = team
738
+ const bytes = new TextEncoder().encode(JSON.stringify({ v: 1, providers, cross, roles, custom }))
739
+ let binary = ''
740
+ for (const byte of bytes) binary += String.fromCharCode(byte)
741
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
742
+ }
743
+
744
+ // cmd.exe corta las órdenes de más de 8191 caracteres.
745
+ export const TEAM_COMMAND_MAX = 7000
746
+
747
+ /**
748
+ * La orden que deja el equipo en `ORCHESTRATION.md` §1 del proyecto, o `null` si no cabe en un
749
+ * terminal. Solo lleva base64url de un equipo que `parseTeam` ya validó; `omk team` lo valida otra vez.
750
+ */
751
+ export function teamCommand(team: Team): string | null {
752
+ const command = `omk team set --data ${encodeTeam(team)}`
753
+ return command.length > TEAM_COMMAND_MAX ? null : command
754
+ }
755
+
756
+ /** Cuántas confirmaciones pide la skill `orca` antes de seguir sola (`ORCHESTRATION.md` §0). */
757
+ export type Autonomy = 'manual' | 'semi' | 'auto'
758
+
759
+ export const AUTONOMY_LEVELS: readonly { id: Autonomy; label: string; hint: string }[] = [
760
+ { id: 'manual', label: 'Manual', hint: 'Confirmas el plan, cada ronda, cada merge y la limpieza.' },
761
+ { id: 'semi', label: 'Semi', hint: 'Confirmas el plan, el merge final y la limpieza.' },
762
+ { id: 'auto', label: 'Auto', hint: 'Solo confirmas el merge final y la limpieza; el plan se enseña sin esperar.' }
763
+ ]
764
+
765
+ export function isAutonomy(value: unknown): value is Autonomy {
766
+ return AUTONOMY_LEVELS.some(({ id }) => id === value)
767
+ }
768
+
769
+ /** La orden que deja el nivel en `ORCHESTRATION.md` §0: un literal por nivel, nada más. */
770
+ export function autonomyCommand(level: Autonomy): string {
771
+ return `omk team set --autonomy ${level}`
772
+ }
773
+
774
+ export const TASK_MAX = 4000
775
+
776
+ /** De dónde sale el trabajo que se reparte. spec-kit es una opción, nunca un requisito. */
777
+ export type TaskSource = 'chat' | 'plan' | 'speckit'
778
+
779
+ export const TASK_SOURCES: readonly { id: TaskSource; label: string }[] = [
780
+ { id: 'chat', label: 'Lo que escribo aquí' },
781
+ { id: 'plan', label: 'Un plan del repo (planes/*.md)' },
782
+ { id: 'speckit', label: 'Tareas de spec-kit (specs/…/tasks.md)' }
783
+ ]
784
+
785
+ const SOURCE_PROMPT: Record<TaskSource, string> = {
786
+ chat: 'Usa la skill orca para repartir esta tarea entre agentes. La entrada es este texto (adaptador de chat): no hace falta spec-kit.',
787
+ plan: 'Usa la skill orca para repartir entre agentes el plan del repo (planes/*.md o .plans/*.md, adaptador plan-file): no hace falta spec-kit.',
788
+ speckit: 'Usa la skill orca para repartir entre agentes las tareas de spec-kit (specs/<feature>/tasks.md, adaptador speckit).'
789
+ }
790
+
791
+ /**
792
+ * El prompt para que el coordinador orqueste, o `null` si no vale. Con «lo que escribo aquí» la
793
+ * tarea es obligatoria; con un plan o spec-kit es una indicación opcional (qué plan, qué feature).
794
+ * Un nivel de autonomía cambia el de `ORCHESTRATION.md` solo para ese run; sin él, manda el fichero.
795
+ */
796
+ export function orchestratePrompt(task: unknown, source: unknown = 'chat', autonomy: unknown = null): string | null {
797
+ if (typeof task !== 'string') return null
798
+ const from = TASK_SOURCES.find(({ id }) => id === source)?.id
799
+ if (!from) return null
800
+ if (autonomy !== null && autonomy !== undefined && !isAutonomy(autonomy)) return null
801
+ // Saltos de línea y tabuladores sí; el resto de caracteres de control, no.
802
+ const clean = task.replace(/\r\n?/g, '\n').replace(/[^\P{Cc}\n\t]/gu, ' ').trim()
803
+ if (clean.length > TASK_MAX || (from === 'chat' && clean === '')) return null
804
+ const head = isAutonomy(autonomy)
805
+ ? `${SOURCE_PROMPT[from]} Autonomía de este run: ${autonomy} (manda sobre ORCHESTRATION.md §0 solo en este run).`
806
+ : SOURCE_PROMPT[from]
807
+ if (clean === '') return head
808
+ return `${head}\n\n${from === 'chat' ? clean : `Indicaciones: ${clean}`}`
159
809
  }