orca-multiagent-kit 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI_INSTALL.md +3 -0
- package/CHANGELOG.md +28 -1
- package/README.md +4 -0
- package/VERSION +1 -1
- package/bin/omk.js +15 -9
- package/core/AGENTS.md +32 -29
- package/docs/CSR.md +95 -0
- package/docs/INSTALADOR-ORCA-WINDOWS.md +101 -0
- package/docs/MANUAL.md +2 -0
- package/docs/ORQUESTADOR.md +123 -0
- package/docs/PLUGIN-ORCA.md +102 -0
- package/install.sh +104 -20
- package/orca-plugin/.gitattributes +1 -0
- package/orca-plugin/README.md +12 -0
- package/orca-plugin/orca-plugin.json +80 -0
- package/orca-plugin/src/kit.test.ts +174 -0
- package/orca-plugin/src/kit.ts +141 -0
- package/orca-plugin/src/worker.test.ts +155 -0
- package/orca-plugin/src/worker.ts +182 -0
- package/orca-plugin/tsconfig.json +6 -0
- package/package.json +2 -2
- package/rules/00-router.md +2 -1
- package/rules/10-communication.md +11 -12
- package/rules/20-clean-code.md +7 -3
- package/rules/30-security.md +1 -1
- package/rules/31-security-audit.md +6 -2
- package/rules/32-ai-security.md +59 -0
- package/rules/40-testing.md +7 -0
- package/rules/50-done-gate.md +20 -17
- package/rules/60-git-workflow.md +1 -1
- package/rules/75-reliability.md +3 -3
- package/rules/80-supply-chain.md +18 -11
- package/rules/95-multi-agent.md +30 -9
- package/rules/lang/cpp.md +1 -1
- package/rules/lang/csharp.md +4 -4
- package/rules/lang/dart-flutter.md +1 -1
- package/rules/lang/infra.md +3 -4
- package/rules/lang/kotlin.md +1 -1
- package/rules/lang/php.md +1 -1
- package/rules/lang/shell.md +17 -1
- package/skills/csr-audit/SKILL.md +6 -5
- package/skills/csr-gate/SKILL.md +12 -8
- package/skills/csr-stack/SKILL.md +6 -3
- package/skills/orca/SKILL.md +17 -12
- package/skills/orca/references/adapters/artifact.md +1 -1
- package/skills/orca/references/adapters/chat.md +1 -1
- package/skills/orca/references/adapters/native-plan.md +1 -1
- package/skills/orca/references/adapters/plan-file.md +1 -1
- package/skills/orca/references/adapters/speckit.md +2 -0
- package/skills/orca/references/engine-manual.md +5 -5
- package/skills/orca/references/engine-orca.md +64 -23
- package/skills/orca/references/engine-subagents.md +13 -4
- package/skills/orca/references/integrate.md +27 -15
- package/skills/orca/references/ledger.md +56 -0
- package/skills/orca/references/race.md +1 -0
- package/skills/orca/references/setup.md +3 -2
- package/skills/orca/references/units.md +7 -0
- package/skills/orca/references/worker-contract.md +24 -11
- package/skills/speckit-orca-implement/SKILL.md +2 -0
- package/speckit-extension/orca/commands/implement.md +2 -0
- package/templates/ORCHESTRATION.md +4 -0
- package/templates/STACK.md +2 -2
|
@@ -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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "orca-multiagent-kit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Una sola fuente de reglas y skills (CSR + MAW) para Claude Code, Antigravity, Codex, Copilot y Cursor, con orquestación multiagente.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Fernando Baquero (https://github.com/FernandoBaqueroo)",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"orca-multiagent-kit": "bin/omk.js"
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
|
-
"bin/", "speckit-extension/", "core/", "rules/", "skills/", "templates/", "output-styles/", "docs/",
|
|
16
|
+
"bin/", "speckit-extension/", "core/", "rules/", "skills/", "templates/", "output-styles/", "docs/", "orca-plugin/",
|
|
17
17
|
"install.sh", "VERSION", "GUIA.html", "AI_INSTALL.md", "CHANGELOG.md", "LICENSE", "README.md"
|
|
18
18
|
],
|
|
19
19
|
"engines": { "node": ">=18" },
|
package/rules/00-router.md
CHANGED
|
@@ -7,7 +7,8 @@ Carga progresiva: el núcleo (`~/.agents/AGENTS.md`) está siempre en contexto;
|
|
|
7
7
|
| `10-communication.md` | El usuario se queja del formato, pide verbosidad, o dudas de estilo | ~600 tok |
|
|
8
8
|
| `20-clean-code.md` | Escribir, revisar o refactorizar cualquier código | ~1.100 tok |
|
|
9
9
|
| `30-security.md` | Siempre que se escriba código de producción | ~1.300 tok |
|
|
10
|
-
| `31-security-audit.md` | Auditoría, pre-release, o código que toca I/O, auth, cripto, red, SQL, ficheros, procesos | ~2.
|
|
10
|
+
| `31-security-audit.md` | Auditoría, pre-release, o código que toca I/O, auth, cripto, red, SQL, ficheros, procesos | ~2.100 tok |
|
|
11
|
+
| `32-ai-security.md` | Código que llama a un LLM, construye prompts, hace RAG o define agentes, herramientas o MCP | ~1.800 tok |
|
|
11
12
|
| `40-testing.md` | Escribir/arreglar tests o definir cobertura | ~1.200 tok |
|
|
12
13
|
| `50-done-gate.md` | Antes de declarar una tarea terminada | ~1.100 tok |
|
|
13
14
|
| `60-git-workflow.md` | Commit, rama, PR, release | ~700 tok |
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# 10 — Protocolo de comunicación: casos y ejemplos
|
|
2
2
|
|
|
3
|
-
> Las reglas duras están en `~/.agents/AGENTS.md` §2 y no se repiten aquí.
|
|
4
|
-
> Este fichero solo cubre lo que no cabe en el núcleo:
|
|
3
|
+
> Las reglas duras (formato largo, excepciones a la brevedad, preguntas) están en `~/.agents/AGENTS.md` §2 y no se repiten aquí.
|
|
4
|
+
> Este fichero solo cubre lo que no cabe en el núcleo: significado de los prefijos, matices y ejemplos.
|
|
5
5
|
|
|
6
6
|
## Principio
|
|
7
7
|
Los tokens de prosa son gasto. Los de razonamiento y código son inversión. Comprime lo primero; no toques lo segundo.
|
|
@@ -13,15 +13,11 @@ Los tokens de prosa son gasto. Los de razonamiento y código son inversión. Com
|
|
|
13
13
|
- `CONFLICT:` una regla superior contradice a otra (ver precedencia en §0 del núcleo).
|
|
14
14
|
- `DEFERRED:` fuera de alcance, o no hecho, y por qué.
|
|
15
15
|
|
|
16
|
-
##
|
|
17
|
-
Disparadores
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
- Avisos de seguridad y acciones irreversibles: frase completa e inequívoca.
|
|
22
|
-
- Secuencias donde el orden importa: migraciones, despliegues, rollback.
|
|
23
|
-
- Cuando comprimir crearía ambigüedad técnica.
|
|
24
|
-
- Cuando el usuario repite una pregunta: significa que la respuesta anterior no se entendió.
|
|
16
|
+
## Matices de las excepciones a la brevedad
|
|
17
|
+
- Disparadores de detalle: además de los del núcleo, `walk me through` y equivalentes en cualquier idioma.
|
|
18
|
+
- Documento para terceros (ADR, README, informe, PR): escribes para esa audiencia, con la extensión que merezca, no para el chat.
|
|
19
|
+
- Comprimir no puede crear ambigüedad técnica: si una frase corta admite dos lecturas, usa la larga.
|
|
20
|
+
- Si el usuario repite una pregunta, la respuesta anterior no se entendió: cambia el enfoque, no la repitas más corta.
|
|
25
21
|
|
|
26
22
|
## Ejemplos
|
|
27
23
|
Mal: «¡Buena pregunta! He revisado el fichero y parece que el problema podría estar en el middleware de autenticación. Voy a arreglarlo ahora.»
|
|
@@ -33,6 +29,9 @@ Bien: `4 ficheros, +120/-31. Gates: PASS.`
|
|
|
33
29
|
Mal: pegar 80 líneas de stack trace.
|
|
34
30
|
Bien: `FAIL test_transfer: expected 0, got -50 (overdraft.rs:44). Falta la comprobación de saldo.`
|
|
35
31
|
|
|
32
|
+
Mal: «Todo listo, debería funcionar.» (sin haber ejecutado nada)
|
|
33
|
+
Bien: `test: SKIPPED (no hay runner en STACK.md §3). Verificado a mano: curl /health → 200.`
|
|
34
|
+
|
|
36
35
|
## Lectura de ficheros
|
|
37
36
|
Lee solo lo necesario, con búsqueda dirigida (grep/glob/símbolo) en vez de volcar ficheros enteros. No vuelques en el chat lo leído: solo el fragmento decisivo.
|
|
38
37
|
|
|
@@ -41,7 +40,7 @@ Lee solo lo necesario, con búsqueda dirigida (grep/glob/símbolo) en vez de vol
|
|
|
41
40
|
- Pregunta solo si la ambigüedad cambia el resultado de forma material (arquitecturas incompatibles) o la acción es irreversible o de alto impacto (borrar datos, producción, migraciones). Una pregunta concreta, no una lista.
|
|
42
41
|
|
|
43
42
|
## Nivel técnico del usuario
|
|
44
|
-
|
|
43
|
+
El perfil (rol, stack habitual, nivel) va en `~/.agents/rules/personal.md`, que el kit no toca. Sin perfil, asume un desarrollador profesional: da por sabidos los conceptos estándar (async/await, contenedores, REST, SQL, transacciones), sin glosarios ni analogías. Contexto histórico o teórico solo si lo pide ("por qué existe X").
|
|
45
44
|
|
|
46
45
|
## Tabla de comportamiento
|
|
47
46
|
| Situación | Comportamiento |
|
package/rules/20-clean-code.md
CHANGED
|
@@ -44,9 +44,13 @@ Escribe código que parezca escrito por quien ya mantenía el repo: mismas conve
|
|
|
44
44
|
- Prefiere composición a herencia; herencia solo para sustitución real (LSP).
|
|
45
45
|
|
|
46
46
|
## Comentarios
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
Explican **por qué**, nunca **qué**: si explica el qué, renombra el código. Cuándo son obligatorios y qué está prohibido: `90-docs-comments.md` §Comentarios.
|
|
48
|
+
|
|
49
|
+
## Código generado con IA
|
|
50
|
+
- Lee lo que vas a entregar como si lo hubiera escrito otro: el código plausible no es código correcto.
|
|
51
|
+
- Cada import, función, flag o endpoint de un tercero se verifica contra la versión instalada (tipos, `--help`, docs de esa versión), no contra la memoria.
|
|
52
|
+
- Sin sobreingeniería por defecto: ni capas, ni opciones, ni manejo de casos que el requisito no pide (YAGNI aplica doble).
|
|
53
|
+
- Diff mínimo: no reformatees, renombres ni "mejores" código que no forma parte del cambio.
|
|
50
54
|
|
|
51
55
|
## Olores que obligan a refactor
|
|
52
56
|
Función >40 líneas · clase >300 líneas · >3 niveles de anidamiento · lista de parámetros larga · envidia de características · obsesión por primitivos · cadenas de `if/else` sobre tipo (usa polimorfismo o match exhaustivo) · retorno de `null` como señal · booleano de control de flujo · dependencia circular · nombre con `Manager`/`Helper`/`Utils` sin significado.
|
package/rules/30-security.md
CHANGED
|
@@ -78,4 +78,4 @@ Todo lo externo es hostil: body, query, headers, cookies, path, ficheros, variab
|
|
|
78
78
|
Antes de añadir una dependencia: ¿es necesaria?, ¿mantenida?, ¿CVE abiertos?, ¿licencia compatible?, ¿cuántas transitivas arrastra? Ver `80-supply-chain.md`.
|
|
79
79
|
|
|
80
80
|
## C12. Específico de IA/LLM
|
|
81
|
-
|
|
81
|
+
Toda salida de modelo, MCP o herramienta externa es entrada no confiable (inyección de prompt indirecta): nunca se ejecuta, renderiza ni usa en SQL/shell/rutas sin validar, y autoriza el permiso del usuario, no lo que pida el texto. Si el código llama a un LLM o define agentes, herramientas o servidores MCP: `32-ai-security.md`.
|
|
@@ -11,6 +11,7 @@ Cuándo: antes de cerrar cualquier cambio que toque entrada de usuario, autentic
|
|
|
11
11
|
6. **Peor caso**: si esta función se ejecuta con entrada del atacante, ¿qué consigue?
|
|
12
12
|
|
|
13
13
|
## Fase B — Revisión manual guiada por OWASP Top 10:2025
|
|
14
|
+
Si el cambio llama a un LLM o define agentes, herramientas o MCP, añade la tabla de `32-ai-security.md` §Auditoría.
|
|
14
15
|
| # | Categoría | Comprobaciones mínimas |
|
|
15
16
|
|---|---|---|
|
|
16
17
|
| A01 | Broken Access Control | Autorización en servidor por petición; propiedad del objeto (IDOR/BOLA); segregación por tenant; rutas admin protegidas; SSRF (destinos, IP resuelta, redirects, metadata endpoint); CORS; path traversal; force browsing |
|
|
@@ -25,7 +26,8 @@ Cuándo: antes de cerrar cualquier cambio que toque entrada de usuario, autentic
|
|
|
25
26
|
| A10 | Mishandling of Exceptional Conditions | Errores ignorados; `catch` vacío; fallback inseguro (fail-open); recursos no liberados; estado inconsistente tras fallo parcial; pánico/crash por entrada; errores que filtran detalles internos |
|
|
26
27
|
|
|
27
28
|
## Fase C — CWE Top 25 (2025): patrones a buscar en el diff
|
|
28
|
-
XSS (79) · SQLi (89) · CSRF (352) · Missing authorization (862) · Out-of-bounds write (787) · Path traversal (22) · Use-after-free (416) · OOB read (125) · OS command injection (78) · Code injection (94) ·
|
|
29
|
+
En el orden de la lista oficial de MITRE: XSS (79) · SQLi (89) · CSRF (352) · Missing authorization (862) · Out-of-bounds write (787) · Path traversal (22) · Use-after-free (416) · OOB read (125) · OS command injection (78) · Code injection (94) · Buffer overflow clásico (120) · Unrestricted upload (434) · NULL deref (476) · Stack overflow (121) · Deserialization (502) · Heap overflow (122) · Incorrect authorization (863) · Improper input validation (20) · Improper access control (284) · Sensitive info exposure (200) · Missing authentication for critical function (306) · SSRF (918) · Command injection (77) · Authorization bypass through user-controlled key (639) · Resource allocation without limits (770).
|
|
30
|
+
Fuera del Top 25 de 2025, pero frecuentes en código de aplicación: hardcoded credentials (798), integer overflow (190), race condition (362), improper authentication (287).
|
|
29
31
|
|
|
30
32
|
## Fase D — Cobertura ASVS 5.0 (17 capítulos) por nivel
|
|
31
33
|
Nivel objetivo por defecto: **L1** para apps internas/personales sin datos de terceros; **L2** para cualquier app con datos personales, dinero o autenticación; **L3** para sistemas críticos.
|
|
@@ -39,7 +41,9 @@ Marca cada capítulo `APLICA / NO APLICA (motivo) / PENDIENTE`.
|
|
|
39
41
|
| SAST multi-lenguaje | `semgrep --config=auto`, `semgrep --config=p/owasp-top-ten` |
|
|
40
42
|
| Vulnerabilidades en deps | `osv-scanner -r .` · `npm audit --omit=dev` · `pnpm audit` · `pip-audit` · `cargo audit` + `cargo deny check` · `govulncheck ./...` · `mvn dependency-check:check` · `dotnet list package --vulnerable` · `composer audit` · `bundler-audit` |
|
|
41
43
|
| SAST por lenguaje | `bandit -r .` (py) · `gosec ./...` (go) · `cargo clippy -- -D warnings` (rust) · `eslint-plugin-security` (js/ts) · `spotbugs`+`find-sec-bugs` (java) · `security-code-scan` (.NET) · `psalm --taint-analysis` (php) · `brakeman` (rails) |
|
|
42
|
-
| Contenedores e IaC | `trivy fs .` · `trivy image <img>` · `hadolint Dockerfile` · `checkov -d .` · `
|
|
44
|
+
| Contenedores e IaC | `trivy fs .` · `trivy image <img>` · `trivy config .` (sustituye a `tfsec`) · `hadolint Dockerfile` · `checkov -d .` · `kube-score` |
|
|
45
|
+
| CI/CD | `zizmor .` (GitHub Actions) · `actionlint` |
|
|
46
|
+
| Integridad de paquetes npm | `npm audit signatures` (firmas y procedencia del registro) |
|
|
43
47
|
| Web dinámico | ZAP baseline · `nikto` · cabeceras con `curl -I` · CSP evaluator |
|
|
44
48
|
| Fuzzing | `cargo fuzz` · `go test -fuzz` · `atheris`/`hypothesis` (py) · `jazzer` (jvm) · AFL++/libFuzzer (C/C++) |
|
|
45
49
|
| Memoria (C/C++/unsafe) | ASan, UBSan, TSan, Valgrind, `-Wall -Wextra -Werror` |
|