orca-multiagent-kit 1.2.0 → 1.4.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 (69) hide show
  1. package/AI_INSTALL.md +5 -2
  2. package/CHANGELOG.md +53 -1
  3. package/GUIA.html +34 -9
  4. package/README.md +13 -2
  5. package/VERSION +1 -1
  6. package/bin/omk.js +15 -9
  7. package/core/AGENTS.md +34 -31
  8. package/docs/CSR.md +95 -0
  9. package/docs/INSTALADOR-ORCA-WINDOWS.md +101 -0
  10. package/docs/MANUAL.md +15 -9
  11. package/docs/OLIMPO.md +409 -0
  12. package/docs/ORQUESTADOR.md +123 -0
  13. package/docs/PLUGIN-ORCA.md +103 -0
  14. package/install.sh +138 -20
  15. package/orca-plugin/.gitattributes +1 -0
  16. package/orca-plugin/README.md +12 -0
  17. package/orca-plugin/orca-plugin.json +80 -0
  18. package/orca-plugin/src/kit.test.ts +185 -0
  19. package/orca-plugin/src/kit.ts +141 -0
  20. package/orca-plugin/src/worker.test.ts +155 -0
  21. package/orca-plugin/src/worker.ts +182 -0
  22. package/orca-plugin/tsconfig.json +6 -0
  23. package/package.json +2 -2
  24. package/rules/00-router.md +2 -1
  25. package/rules/10-communication.md +11 -12
  26. package/rules/20-clean-code.md +7 -3
  27. package/rules/30-security.md +1 -1
  28. package/rules/31-security-audit.md +6 -2
  29. package/rules/32-ai-security.md +59 -0
  30. package/rules/40-testing.md +7 -0
  31. package/rules/50-done-gate.md +20 -17
  32. package/rules/60-git-workflow.md +1 -1
  33. package/rules/75-reliability.md +3 -3
  34. package/rules/80-supply-chain.md +18 -11
  35. package/rules/95-multi-agent.md +48 -19
  36. package/rules/lang/cpp.md +1 -1
  37. package/rules/lang/csharp.md +4 -4
  38. package/rules/lang/dart-flutter.md +1 -1
  39. package/rules/lang/infra.md +3 -4
  40. package/rules/lang/kotlin.md +1 -1
  41. package/rules/lang/php.md +1 -1
  42. package/rules/lang/shell.md +17 -1
  43. package/skills/csr-audit/SKILL.md +6 -5
  44. package/skills/csr-gate/SKILL.md +12 -8
  45. package/skills/csr-stack/SKILL.md +6 -3
  46. package/skills/kit-init/SKILL.md +4 -2
  47. package/skills/orca/SKILL.md +60 -24
  48. package/skills/orca/references/adapters/artifact.md +1 -1
  49. package/skills/orca/references/adapters/chat.md +1 -1
  50. package/skills/orca/references/adapters/native-plan.md +1 -1
  51. package/skills/orca/references/adapters/plan-file.md +1 -1
  52. package/skills/orca/references/adapters/speckit.md +3 -1
  53. package/skills/orca/references/engine-manual.md +10 -12
  54. package/skills/orca/references/engine-orca.md +69 -23
  55. package/skills/orca/references/engine-subagents.md +16 -4
  56. package/skills/orca/references/integrate.md +66 -15
  57. package/skills/orca/references/ledger.md +59 -0
  58. package/skills/orca/references/olimpo.md +92 -0
  59. package/skills/orca/references/race.md +1 -0
  60. package/skills/orca/references/setup.md +14 -7
  61. package/skills/orca/references/units.md +13 -1
  62. package/skills/orca/references/worker-contract.md +28 -11
  63. package/skills/speckit-orca-implement/SKILL.md +2 -0
  64. package/speckit-extension/orca/commands/implement.md +2 -0
  65. package/templates/.worktreeinclude +7 -3
  66. package/templates/ORCHESTRATION.md +31 -18
  67. package/templates/STACK.md +2 -2
  68. package/templates/models.md +29 -0
  69. package/templates/orca.yaml +10 -2
@@ -0,0 +1,185 @@
1
+ import { assert, describe, test } from 'orca/testing'
2
+ import {
3
+ CONTRACT_HINT,
4
+ describeAgents,
5
+ isKitDispatch,
6
+ isMissingCommand,
7
+ isValidAgentId,
8
+ parseContractHintMode,
9
+ pollUntil,
10
+ resolveFocusedWorkspaceId,
11
+ summarizeAgents,
12
+ withContractHint
13
+ } from './kit.ts'
14
+
15
+ const KIT_SPEC = 'UNIT: U2 — Endpoint POST /recargas RUN: 20261107-recargas BASE: abc123\n...'
16
+
17
+ describe('withContractHint', () => {
18
+ test('añade la referencia a un despacho de la skill orca', () => {
19
+ assert.equal(withContractHint(KIT_SPEC, 'orchestration', 'kit'), `${KIT_SPEC}\n\n${CONTRACT_HINT}`)
20
+ })
21
+
22
+ test('no toca despachos ajenos al kit en modo kit, sí en modo all', () => {
23
+ const foreign = 'Task T1 · Dispatch D1\nRevisa el PR 42 y responde con worker_done.'
24
+ assert.equal(withContractHint(foreign, 'orchestration', 'kit'), null)
25
+ assert.equal(withContractHint(foreign, 'orchestration', 'all'), `${foreign}\n\n${CONTRACT_HINT}`)
26
+ })
27
+
28
+ test('nunca toca prompts que no son despachos de orquestación', () => {
29
+ assert.equal(withContractHint(KIT_SPEC, 'launch', 'all'), null)
30
+ assert.equal(withContractHint(KIT_SPEC, 'driving', 'all'), null)
31
+ })
32
+
33
+ test('desactivado no cambia nada', () => {
34
+ assert.equal(withContractHint(KIT_SPEC, 'orchestration', 'off'), null)
35
+ })
36
+
37
+ test('es idempotente y respeta un contrato ya citado', () => {
38
+ const once = withContractHint(KIT_SPEC, 'orchestration', 'kit') ?? ''
39
+ assert.equal(withContractHint(once, 'orchestration', 'kit'), null)
40
+ const cited = `${KIT_SPEC}\nContrato: skills/orca/references/worker-contract.md`
41
+ assert.equal(withContractHint(cited, 'orchestration', 'all'), null)
42
+ })
43
+
44
+ test('detecta la cabecera del kit solo con UNIT y RUN', () => {
45
+ assert.equal(isKitDispatch(KIT_SPEC), true)
46
+ assert.equal(isKitDispatch('UNIT: U2 sin run'), false)
47
+ assert.equal(isKitDispatch('RUN: x pero sin unidad'), false)
48
+ assert.equal(isKitDispatch('la UNIT: U2 va en mitad de la línea RUN: x'), false)
49
+ })
50
+
51
+ test('reconoce el despacho con las líneas ROL y SETUP de Olimpo', () => {
52
+ const dispatch = [
53
+ 'UNIT: U2 — Recarga con tarjeta RUN: 20261107-recargas BASE: 5d6e7f8 PUERTO DEV: 3102',
54
+ 'ROL: Ariadna · código sensible · nivel alto — tests de casos límite antes que el código',
55
+ '### UNIT: U2 — Recarga con tarjeta',
56
+ 'SETUP: /repo · copiar .env.local · pnpm install'
57
+ ].join('\n')
58
+ assert.equal(isKitDispatch(dispatch), true)
59
+ assert.equal(withContractHint(dispatch, 'orchestration', 'kit'), `${dispatch}\n\n${CONTRACT_HINT}`)
60
+ })
61
+ })
62
+
63
+ describe('parseContractHintMode', () => {
64
+ test('acepta los tres modos y vuelve a kit ante cualquier otra cosa', () => {
65
+ assert.equal(parseContractHintMode('all'), 'all')
66
+ assert.equal(parseContractHintMode('off'), 'off')
67
+ assert.equal(parseContractHintMode('kit'), 'kit')
68
+ assert.equal(parseContractHintMode('ALL'), 'kit')
69
+ assert.equal(parseContractHintMode(undefined), 'kit')
70
+ assert.equal(parseContractHintMode(3), 'kit')
71
+ })
72
+ })
73
+
74
+ describe('isMissingCommand', () => {
75
+ const cases: [string, string][] = [
76
+ ['bash', 'bash: omk: command not found'],
77
+ ['zsh', 'zsh: command not found: omk'],
78
+ ['fish', 'fish: Unknown command: omk'],
79
+ ['cmd', "'omk' is not recognized as an internal or external command,"],
80
+ ['cmd es', "'omk' no se reconoce como un comando interno o externo,"],
81
+ ['pwsh', "omk: The term 'omk' is not recognized as a name of a cmdlet, function, script file"],
82
+ ['pwsh es', "omk : El término 'omk' no se reconoce como nombre de un cmdlet"],
83
+ ['bash es', 'bash: omk: orden no encontrada']
84
+ ]
85
+ for (const [shell, line] of cases) {
86
+ test(`reconoce el error de ${shell}`, () => {
87
+ assert.equal(isMissingCommand(['$ omk verify', line]), true)
88
+ })
89
+ }
90
+
91
+ test('no confunde la salida normal de omk ni otros comandos', () => {
92
+ assert.equal(isMissingCommand(['$ omk verify', '[kit] OK CLAUDE.md importa AGENTS.md']), false)
93
+ assert.equal(isMissingCommand(['bash: omkx: command not found']), false)
94
+ assert.equal(isMissingCommand(['bash: git: command not found']), false)
95
+ assert.equal(isMissingCommand([]), false)
96
+ })
97
+ })
98
+
99
+ describe('resolveFocusedWorkspaceId', () => {
100
+ const workspaces = [
101
+ { id: 'w1', name: 'app', branch: 'main' },
102
+ { id: 'w2', name: 'app', branch: 'feat/x' },
103
+ { id: 'w3', name: 'notas', branch: null }
104
+ ]
105
+
106
+ test('cruza nombre y rama', () => {
107
+ assert.equal(resolveFocusedWorkspaceId({ displayName: 'app', branch: 'feat/x' }, workspaces), 'w2')
108
+ })
109
+
110
+ test('una carpeta sin rama casa con branch vacío', () => {
111
+ assert.equal(resolveFocusedWorkspaceId({ displayName: 'notas', branch: '' }, workspaces), 'w3')
112
+ })
113
+
114
+ test('sin foco, sin coincidencia o con coincidencia ambigua no adivina', () => {
115
+ assert.equal(resolveFocusedWorkspaceId(null, workspaces), null)
116
+ assert.equal(resolveFocusedWorkspaceId({ displayName: 'otro', branch: 'main' }, workspaces), null)
117
+ const twice = [...workspaces, { id: 'w4', name: 'app', branch: 'main' }]
118
+ assert.equal(resolveFocusedWorkspaceId({ displayName: 'app', branch: 'main' }, twice), null)
119
+ })
120
+ })
121
+
122
+ describe('isValidAgentId', () => {
123
+ test('acepta ids simples y rechaza lo demás', () => {
124
+ assert.equal(isValidAgentId('claude'), true)
125
+ assert.equal(isValidAgentId('cursor-agent'), true)
126
+ assert.equal(isValidAgentId(''), false)
127
+ assert.equal(isValidAgentId('claude; rm -rf ~'), false)
128
+ assert.equal(isValidAgentId('Claude'), false)
129
+ assert.equal(isValidAgentId('a'.repeat(41)), false)
130
+ assert.equal(isValidAgentId(null), false)
131
+ })
132
+ })
133
+
134
+ describe('summarizeAgents', () => {
135
+ test('sin agentes activos', () => {
136
+ const summary = summarizeAgents([{ workspaceId: null, title: 'x', state: 'done' }])
137
+ assert.deepEqual(summary, { text: 'MAW', tone: 'neutral', tooltip: 'Orca Multiagent Kit: ningún agente activo' })
138
+ })
139
+
140
+ test('cuenta por estado, en singular y plural, y avisa si hay bloqueados', () => {
141
+ const summary = summarizeAgents([
142
+ { workspaceId: 'a', title: 'U1', state: 'working' },
143
+ { workspaceId: 'b', title: 'U2', state: 'working' },
144
+ { workspaceId: 'c', title: 'U3', state: 'blocked' }
145
+ ])
146
+ assert.equal(summary.text, 'MAW · 2 trabajando · 1 bloqueado')
147
+ assert.equal(summary.tone, 'warning')
148
+ })
149
+
150
+ test('solo trabajando es accent', () => {
151
+ assert.equal(summarizeAgents([{ workspaceId: null, title: null, state: 'working' }]).tone, 'accent')
152
+ })
153
+ })
154
+
155
+ describe('describeAgents', () => {
156
+ test('una línea por agente activo', () => {
157
+ assert.equal(
158
+ describeAgents([
159
+ { workspaceId: null, title: 'U1 login', state: 'waiting' },
160
+ { workspaceId: null, title: null, state: 'blocked' },
161
+ { workspaceId: null, title: 'viejo', state: 'done' }
162
+ ]),
163
+ '- U1 login: esperando\n- agente sin título: bloqueado'
164
+ )
165
+ assert.equal(describeAgents([]), 'Ningún agente activo.')
166
+ })
167
+ })
168
+
169
+ describe('pollUntil', () => {
170
+ const instant = { attempts: 3, delayMs: 10, sleep: async () => undefined }
171
+
172
+ test('para en cuanto la salida coincide', async () => {
173
+ let reads = 0
174
+ const found = await pollUntil(async () => [String(++reads)], (lines) => lines[0] === '2', instant)
175
+ assert.equal(found, true)
176
+ assert.equal(reads, 2)
177
+ })
178
+
179
+ test('se rinde tras el número de intentos', async () => {
180
+ let reads = 0
181
+ const found = await pollUntil(async () => [String(++reads)], () => false, instant)
182
+ assert.equal(found, false)
183
+ assert.equal(reads, 3)
184
+ })
185
+ })
@@ -0,0 +1,141 @@
1
+ // Lógica pura del plugin: sin llamadas a Orca, para poder probarla sin host.
2
+
3
+ export const CONTRACT_PATH = '~/.agents/skills/orca/references/worker-contract.md'
4
+
5
+ /** Qué despachos de orquestación reciben la referencia al contrato del worker. */
6
+ export type ContractHintMode = 'kit' | 'all' | 'off'
7
+
8
+ export const CONTRACT_HINT_MODES: readonly ContractHintMode[] = ['kit', 'all', 'off']
9
+
10
+ export const CONTRACT_HINT =
11
+ `[Orca Multiagent Kit] Contrato del worker: lee y aplica ${CONTRACT_PATH} ` +
12
+ '(arranque, implementación, verificación y el formato fijo del informe, que va en el body de ' +
13
+ 'worker_done). Si ese fichero no existe en este host, sigue solo las instrucciones de arriba.'
14
+
15
+ // Cabecera del mensaje de despacho que escribe la skill `orca` (skills/orca/SKILL.md §5).
16
+ const KIT_UNIT_LINE = /^\s*UNIT:\s*U\d+\b/m
17
+ const KIT_RUN_FIELD = /\bRUN:\s*\S+/
18
+
19
+ export function parseContractHintMode(value: unknown): ContractHintMode {
20
+ return CONTRACT_HINT_MODES.find((mode) => mode === value) ?? 'kit'
21
+ }
22
+
23
+ export function isKitDispatch(prompt: string): boolean {
24
+ return KIT_UNIT_LINE.test(prompt) && KIT_RUN_FIELD.test(prompt)
25
+ }
26
+
27
+ /**
28
+ * Devuelve el prompt con la referencia al contrato añadida, o `null` si no hay que tocarlo:
29
+ * solo despachos de orquestación, nunca dos veces y nunca si el coordinador ya lo citó.
30
+ */
31
+ export function withContractHint(
32
+ prompt: string,
33
+ inputKind: string,
34
+ mode: ContractHintMode
35
+ ): string | null {
36
+ if (mode === 'off' || inputKind !== 'orchestration') return null
37
+ if (mode === 'kit' && !isKitDispatch(prompt)) return null
38
+ if (prompt.includes('worker-contract.md')) return null
39
+ return `${prompt.trimEnd()}\n\n${CONTRACT_HINT}`
40
+ }
41
+
42
+ // Mensajes de "comando no encontrado" de bash, zsh, fish, cmd y PowerShell (inglés y español).
43
+ const MISSING_COMMAND =
44
+ /command not found|not recognized|unknown command|no se reconoce|orden no encontrada|no se encontr[oó] la orden/i
45
+
46
+ /** Si la salida del terminal dice que `omk` no existe en el PATH. */
47
+ export function isMissingCommand(lines: readonly string[], command = 'omk'): boolean {
48
+ const name = new RegExp(`(^|[^\\w-])${command}([^\\w-]|$)`)
49
+ return lines.some((line) => name.test(line) && MISSING_COMMAND.test(line))
50
+ }
51
+
52
+ export type PollOptions = {
53
+ attempts: number
54
+ delayMs: number
55
+ sleep: (ms: number) => Promise<void>
56
+ }
57
+
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
67
+ }
68
+ return false
69
+ }
70
+
71
+ export const INSTALL_HINT =
72
+ 'Instálalo con `npm install -g orca-multiagent-kit` (o `./install.sh` desde el zip) y vuelve a lanzar el comando.'
73
+
74
+ export type FocusedWorkspace = { branch: string; displayName: string }
75
+ export type WorkspaceEntry = { id: string; name: string; branch: string | null }
76
+
77
+ /**
78
+ * Id del workspace enfocado. `workspace.readContext` no da el id, así que se cruza con
79
+ * `workspace.list` por nombre y rama; si no hay exactamente una coincidencia, `null`:
80
+ * mejor no actuar que lanzar algo en otro workspace.
81
+ */
82
+ export function resolveFocusedWorkspaceId(
83
+ focused: FocusedWorkspace | null,
84
+ workspaces: readonly WorkspaceEntry[]
85
+ ): string | null {
86
+ if (!focused) return null
87
+ const matches = workspaces.filter(
88
+ (w) => w.name === focused.displayName && (w.branch ?? '') === focused.branch
89
+ )
90
+ return matches.length === 1 ? (matches[0]?.id ?? null) : null
91
+ }
92
+
93
+ const AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/
94
+
95
+ export function isValidAgentId(value: unknown): value is string {
96
+ return typeof value === 'string' && AGENT_ID.test(value)
97
+ }
98
+
99
+ export type AgentState = 'working' | 'blocked' | 'waiting' | 'done'
100
+ export type TrackedAgent = { workspaceId: string | null; title: string | null; state: AgentState }
101
+
102
+ export type AgentSummary = {
103
+ text: string
104
+ tone: 'neutral' | 'accent' | 'warning'
105
+ tooltip: string
106
+ }
107
+
108
+ const STATE_LABEL: Record<Exclude<AgentState, 'done'>, [string, string]> = {
109
+ working: ['trabajando', 'trabajando'],
110
+ blocked: ['bloqueado', 'bloqueados'],
111
+ waiting: ['esperando', 'esperando']
112
+ }
113
+
114
+ export function summarizeAgents(agents: Iterable<TrackedAgent>): AgentSummary {
115
+ const counts = { working: 0, blocked: 0, waiting: 0 }
116
+ for (const agent of agents) {
117
+ if (agent.state !== 'done') counts[agent.state] += 1
118
+ }
119
+ const parts = (Object.keys(counts) as (keyof typeof counts)[])
120
+ .filter((state) => counts[state] > 0)
121
+ .map((state) => `${counts[state]} ${STATE_LABEL[state][counts[state] === 1 ? 0 : 1]}`)
122
+ const tone = counts.blocked > 0 ? 'warning' : counts.working > 0 ? 'accent' : 'neutral'
123
+ return {
124
+ text: parts.length > 0 ? `MAW · ${parts.join(' · ')}` : 'MAW',
125
+ tone,
126
+ tooltip:
127
+ parts.length > 0
128
+ ? `Orca Multiagent Kit: ${parts.join(', ')} en todos los workspaces`
129
+ : 'Orca Multiagent Kit: ningún agente activo'
130
+ }
131
+ }
132
+
133
+ /** Una línea por agente activo, para el comando «estado de los agentes». */
134
+ export function describeAgents(agents: Iterable<TrackedAgent>): string {
135
+ const lines: string[] = []
136
+ for (const agent of agents) {
137
+ if (agent.state === 'done') continue
138
+ lines.push(`- ${agent.title ?? 'agente sin título'}: ${STATE_LABEL[agent.state][0]}`)
139
+ }
140
+ return lines.length > 0 ? lines.join('\n') : 'Ningún agente activo.'
141
+ }
@@ -0,0 +1,155 @@
1
+ // El worker tal como lo carga Orca, contra un host simulado con las capacidades del manifiesto.
2
+ import { afterEach, assert, hostError, mockHost, mountWorker, test, type TestWorker } from 'orca/testing'
3
+ import { CONTRACT_HINT } from './kit.ts'
4
+ import * as main from './worker.ts'
5
+
6
+ const KIT_SPEC = 'UNIT: U1 — Login RUN: 20261107-auth BASE: abc123'
7
+
8
+ const baseResults = (overrides: Record<string, unknown> = {}) => ({
9
+ 'workspace.readContext': { branch: 'main', displayName: 'app', terminals: [] },
10
+ 'workspace.list': {
11
+ workspaces: [{ id: 'w1', kind: 'worktree', name: 'app', path: '/repo/app', branch: 'main', hostId: null }],
12
+ truncated: false
13
+ },
14
+ 'agents.list': { agents: [] },
15
+ 'terminal.create': { terminalId: 't9' },
16
+ 'terminal.read': { lines: [], truncated: false },
17
+ 'agent.launch': { terminalId: 't10' },
18
+ 'notifications.show': { delivered: true },
19
+ 'statusBar.update': { ok: true },
20
+ ...overrides
21
+ })
22
+
23
+ let worker: TestWorker | undefined
24
+ afterEach(async () => {
25
+ await worker?.deactivate()
26
+ worker = undefined
27
+ })
28
+
29
+ const start = async (options: { results?: Record<string, unknown>; settings?: Record<string, string | boolean> } = {}) => {
30
+ worker = await mountWorker(main, {
31
+ host: mockHost({ results: baseResults(options.results), settings: options.settings ?? {} })
32
+ })
33
+ return worker
34
+ }
35
+
36
+ const prompt = (text: string, inputKind: 'orchestration' | 'launch' | 'driving' = 'orchestration') => ({
37
+ agent: 'claude',
38
+ terminalId: 't1',
39
+ prompt: text,
40
+ inputKind
41
+ })
42
+
43
+ test('añade el contrato del worker a un despacho del kit', async () => {
44
+ const w = await start()
45
+ assert.deepEqual(await w.hooks.fire('agent.prompt.before', prompt(KIT_SPEC)), {
46
+ kind: 'continue',
47
+ event: prompt(`${KIT_SPEC}\n\n${CONTRACT_HINT}`)
48
+ })
49
+ })
50
+
51
+ test('deja intactos los prompts que no son despachos del kit', async () => {
52
+ const w = await start()
53
+ for (const event of [prompt('Revisa el PR 42'), prompt(KIT_SPEC, 'launch')]) {
54
+ assert.deepEqual(await w.hooks.fire('agent.prompt.before', event), { kind: 'continue', event })
55
+ }
56
+ })
57
+
58
+ test('el ajuste off desactiva el hook', async () => {
59
+ const w = await start({ settings: { contractHint: 'off' } })
60
+ const event = prompt(KIT_SPEC)
61
+ assert.deepEqual(await w.hooks.fire('agent.prompt.before', event), { kind: 'continue', event })
62
+ })
63
+
64
+ test('verificar abre un terminal con el literal omk verify en el workspace activo', async () => {
65
+ const w = await start()
66
+ const result = await w.command('kit.verify')
67
+ assert.deepEqual(w.host.callsOf('terminal.create'), [
68
+ { workspaceId: 'w1', title: 'omk verify', command: 'omk verify' }
69
+ ])
70
+ assert.equal(result, 'Ejecutando `omk verify` en un terminal nuevo del workspace activo.')
71
+ assert.deepEqual(w.refusals, [])
72
+ })
73
+
74
+ test('actualizar usa omk update', async () => {
75
+ const w = await start()
76
+ await w.command('kit.update')
77
+ assert.equal((w.host.callsOf('terminal.create')[0] as { command: string }).command, 'omk update')
78
+ })
79
+
80
+ test('sin workspace identificable no ejecuta nada y lo avisa', async () => {
81
+ const w = await start({ results: { 'workspace.readContext': null } })
82
+ const result = await w.command('kit.verify')
83
+ assert.equal(w.host.callsOf('terminal.create').length, 0)
84
+ assert.equal(w.host.callsOf('notifications.show').length, 1)
85
+ assert.match(String(result), /No identifico el workspace activo/)
86
+ })
87
+
88
+ test('un fallo de Orca al crear el terminal se notifica, no se calla', async () => {
89
+ const w = await start({
90
+ results: {
91
+ 'terminal.create': () => {
92
+ throw hostError('action_failed', 'sin pty')
93
+ }
94
+ }
95
+ })
96
+ const result = await w.command('kit.verify')
97
+ assert.match(String(result), /^omk verify: action_failed: sin pty/)
98
+ assert.equal(w.host.callsOf('notifications.show').length, 1)
99
+ })
100
+
101
+ test('inicializar lanza el agente configurado con «inicializa el proyecto»', async () => {
102
+ const w = await start({ settings: { initAgent: 'codex' } })
103
+ await w.command('kit.init')
104
+ assert.deepEqual(w.host.callsOf('agent.launch'), [
105
+ { workspaceId: 'w1', agent: 'codex', prompt: 'inicializa el proyecto' }
106
+ ])
107
+ })
108
+
109
+ test('inicializar rechaza un id de agente no válido sin lanzar nada', async () => {
110
+ const w = await start({ settings: { initAgent: 'claude; rm -rf ~' } })
111
+ const result = await w.command('kit.init')
112
+ assert.equal(w.host.callsOf('agent.launch').length, 0)
113
+ assert.match(String(result), /no es un id de agente válido/)
114
+ })
115
+
116
+ test('la barra de estado sigue los cambios de estado de los agentes', async () => {
117
+ const w = await start()
118
+ await w.emit('agent.status.changed', {
119
+ workspaceId: 'w1', paneKey: 'p1', terminalId: 't1', title: 'U1 login', state: 'working', receivedAt: 1
120
+ })
121
+ await w.emit('agent.status.changed', {
122
+ workspaceId: 'w2', paneKey: 'p2', terminalId: 't2', title: 'U2 pagos', state: 'blocked', receivedAt: 2
123
+ })
124
+ const last = () => w.host.callsOf('statusBar.update').at(-1)
125
+ assert.deepEqual(last(), {
126
+ id: 'agents',
127
+ visible: true,
128
+ text: 'MAW · 1 trabajando · 1 bloqueado',
129
+ tone: 'warning',
130
+ tooltip: 'Orca Multiagent Kit: 1 trabajando, 1 bloqueado en todos los workspaces'
131
+ })
132
+ assert.equal(await w.command('agents.status'), '- U1 login: trabajando\n- U2 pagos: bloqueado')
133
+
134
+ await w.emit('workspace.removed', { workspaceId: 'w2', kind: 'worktree', path: '/repo/u2' })
135
+ await w.emit('agent.status.changed', {
136
+ workspaceId: 'w1', paneKey: 'p1', terminalId: 't1', state: 'done', receivedAt: 3
137
+ })
138
+ assert.equal((last() as { text: string }).text, 'MAW')
139
+ assert.deepEqual(w.refusals, [])
140
+ })
141
+
142
+ test('la barra parte de los agentes que ya existen y se oculta si se desactiva', async () => {
143
+ const seeded = await start({
144
+ results: {
145
+ 'agents.list': {
146
+ agents: [{ terminalId: 't1', title: 'U1', agent: 'claude', state: 'working', stateStartedAt: 0 }]
147
+ }
148
+ }
149
+ })
150
+ assert.equal((seeded.host.callsOf('statusBar.update').at(-1) as { text: string }).text, 'MAW · 1 trabajando')
151
+ await seeded.deactivate()
152
+
153
+ const hidden = await start({ settings: { statusBar: false } })
154
+ assert.deepEqual(hidden.host.callsOf('statusBar.update').at(-1), { id: 'agents', visible: false })
155
+ })
@@ -0,0 +1,182 @@
1
+ // Worker del plugin: comandos de paleta del kit, referencia al contrato del worker en los
2
+ // despachos de orquestación y un resumen de agentes en la barra de estado.
3
+ // Orca transpila este fichero al cargarlo: no hay paso de build.
4
+ import type { OrcaWorkerApi } from 'orca/worker'
5
+ import {
6
+ INSTALL_HINT,
7
+ describeAgents,
8
+ isMissingCommand,
9
+ isValidAgentId,
10
+ parseContractHintMode,
11
+ pollUntil,
12
+ resolveFocusedWorkspaceId,
13
+ summarizeAgents,
14
+ withContractHint,
15
+ type ContractHintMode,
16
+ type TrackedAgent
17
+ } from './kit.ts'
18
+
19
+ const STATUS_ITEM = 'agents'
20
+ const INIT_PROMPT = 'inicializa el proyecto'
21
+ const DEFAULT_INIT_AGENT = 'claude'
22
+ // `omk verify` tarda poco; si en ~15 s no hay error de "comando no encontrado", existe.
23
+ const MISSING_CHECK = { attempts: 10, delayMs: 1500 }
24
+ const NO_WORKSPACE =
25
+ 'No identifico el workspace activo. Abre el proyecto en Orca y vuelve a lanzar el comando.'
26
+
27
+ type OmkSubcommand = 'verify' | 'update'
28
+
29
+ // Esperas pendientes de las comprobaciones de `omk`: `deactivate` las cancela al parar el worker.
30
+ const pendingTimers = new Set<ReturnType<typeof setTimeout>>()
31
+ const sleep = (ms: number) =>
32
+ new Promise<void>((resolve) => {
33
+ const timer = setTimeout(() => {
34
+ pendingTimers.delete(timer)
35
+ resolve()
36
+ }, ms)
37
+ pendingTimers.add(timer)
38
+ })
39
+
40
+ export function deactivate(): void {
41
+ for (const timer of pendingTimers) clearTimeout(timer)
42
+ pendingTimers.clear()
43
+ }
44
+ // Los errores del host son `Error` con `code` (host-api §Errors); el tipo no lo declara.
45
+ const describeError = (error: unknown) =>
46
+ error instanceof Error ? `${(error as { code?: string }).code ?? 'error'}: ${error.message}` : String(error)
47
+
48
+ export default async function activate(orca: OrcaWorkerApi): Promise<void> {
49
+ const { host } = orca
50
+ let contractHint: ContractHintMode = 'kit'
51
+ let statusBarEnabled = true
52
+ let initAgent: unknown = DEFAULT_INIT_AGENT
53
+ const agents = new Map<string, TrackedAgent>()
54
+
55
+ const notify = (title: string, body: string) => {
56
+ void host.call('notifications.show', { title, body }).catch((error: unknown) => {
57
+ orca.log(`notificación no entregada (${title}): ${describeError(error)}`)
58
+ })
59
+ }
60
+
61
+ // Un fallo de Orca en un comando se cuenta al usuario; nunca se queda en silencio.
62
+ const guarded = (label: string, run: () => Promise<string>) => async () => {
63
+ try {
64
+ return await run()
65
+ } catch (error) {
66
+ const message = `${label}: ${describeError(error)}`
67
+ orca.log(message)
68
+ notify('Orca Multiagent Kit', message)
69
+ return message
70
+ }
71
+ }
72
+
73
+ const focusedWorkspaceId = async () => {
74
+ const [focused, list] = await Promise.all([
75
+ host.call('workspace.readContext'),
76
+ host.call('workspace.list')
77
+ ])
78
+ return resolveFocusedWorkspaceId(focused, list.workspaces)
79
+ }
80
+
81
+ const renderStatus = () => {
82
+ const summary = summarizeAgents(agents.values())
83
+ const update = statusBarEnabled
84
+ ? { id: STATUS_ITEM, visible: true, text: summary.text, tone: summary.tone, tooltip: summary.tooltip }
85
+ : { id: STATUS_ITEM, visible: false }
86
+ void host.call('statusBar.update', update).catch((error: unknown) => {
87
+ orca.log(`barra de estado sin actualizar: ${describeError(error)}`)
88
+ })
89
+ }
90
+
91
+ const loadSettings = async () => {
92
+ try {
93
+ const settings = await orca.settings.get()
94
+ contractHint = parseContractHintMode(settings.contractHint)
95
+ statusBarEnabled = settings.statusBar !== false
96
+ initAgent = settings.initAgent ?? DEFAULT_INIT_AGENT
97
+ } catch (error) {
98
+ orca.log(`ajustes no leídos, uso los valores por defecto: ${describeError(error)}`)
99
+ }
100
+ }
101
+
102
+ const warnIfOmkMissing = async (terminalId: string) => {
103
+ const missing = await pollUntil(
104
+ async () => (await host.call('terminal.read', { terminalId, maxLines: 40 })).lines,
105
+ (lines) => isMissingCommand(lines),
106
+ { ...MISSING_CHECK, sleep }
107
+ )
108
+ if (missing) notify('omk no está instalado', INSTALL_HINT)
109
+ }
110
+
111
+ const runOmk = (subcommand: OmkSubcommand) =>
112
+ guarded(`omk ${subcommand}`, async () => {
113
+ const workspaceId = await focusedWorkspaceId()
114
+ if (!workspaceId) {
115
+ notify('Orca Multiagent Kit', NO_WORKSPACE)
116
+ return NO_WORKSPACE
117
+ }
118
+ // Literal fijo: nunca se interpola texto del usuario ni de terceros en el terminal.
119
+ const command = `omk ${subcommand}`
120
+ const { terminalId } = await host.call('terminal.create', { workspaceId, title: command, command })
121
+ void warnIfOmkMissing(terminalId).catch((error: unknown) => {
122
+ orca.log(`no pude leer la salida de ${command}: ${describeError(error)}`)
123
+ })
124
+ return `Ejecutando \`${command}\` en un terminal nuevo del workspace activo.`
125
+ })
126
+
127
+ const initProject = guarded('inicializar proyecto', async () => {
128
+ if (!isValidAgentId(initAgent)) {
129
+ const message = `El ajuste «Agente para inicializar» no es un id de agente válido: ${String(initAgent)}`
130
+ notify('Orca Multiagent Kit', message)
131
+ return message
132
+ }
133
+ const workspaceId = await focusedWorkspaceId()
134
+ if (!workspaceId) {
135
+ notify('Orca Multiagent Kit', NO_WORKSPACE)
136
+ return NO_WORKSPACE
137
+ }
138
+ await host.call('agent.launch', { workspaceId, agent: initAgent, prompt: INIT_PROMPT })
139
+ return `Lanzado ${initAgent} con «${INIT_PROMPT}» (skill kit-init) en el workspace activo.`
140
+ })
141
+
142
+ // El hook no deniega nunca: si no aplica, el prompt pasa intacto. Un fallo o un timeout
143
+ // también lo dejan pasar (`onError: "pass"`): es una ayuda al worker, no un control.
144
+ orca.hooks.on('agent.prompt.before', (event, next) => {
145
+ const prompt = withContractHint(event.prompt, event.inputKind, contractHint)
146
+ return prompt === null ? undefined : next({ ...event, prompt })
147
+ })
148
+
149
+ orca.commands.register('kit.verify', runOmk('verify'))
150
+ orca.commands.register('kit.update', runOmk('update'))
151
+ orca.commands.register('kit.init', initProject)
152
+ orca.commands.register('agents.status', async () => describeAgents(agents.values()))
153
+
154
+ orca.events.on('agent.status.changed', (event) => {
155
+ const key = event.terminalId ? `t:${event.terminalId}` : `p:${event.paneKey}`
156
+ if (event.state === 'done') agents.delete(key)
157
+ else agents.set(key, { workspaceId: event.workspaceId, title: event.title ?? null, state: event.state })
158
+ renderStatus()
159
+ })
160
+
161
+ orca.events.on('workspace.removed', (event) => {
162
+ for (const [key, agent] of agents) if (agent.workspaceId === event.workspaceId) agents.delete(key)
163
+ renderStatus()
164
+ })
165
+
166
+ orca.settings.onDidChange(() => {
167
+ void loadSettings().then(renderStatus)
168
+ })
169
+
170
+ await loadSettings()
171
+ try {
172
+ const { agents: current } = await host.call('agents.list')
173
+ for (const agent of current) {
174
+ if (agent.terminalId && agent.state !== 'done') {
175
+ agents.set(`t:${agent.terminalId}`, { workspaceId: null, title: agent.title, state: agent.state })
176
+ }
177
+ }
178
+ } catch (error) {
179
+ orca.log(`agentes iniciales no leídos; la barra se rellena con los eventos: ${describeError(error)}`)
180
+ }
181
+ renderStatus()
182
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "./.orca/types/tsconfig.json",
3
+ "include": [
4
+ "src"
5
+ ]
6
+ }