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
@@ -0,0 +1,356 @@
1
+ // La pestaña Avisos del worker, cargada con el núcleo contra un host simulado.
2
+ import { afterEach, assert, hostError, mockHost, mountWorker, test, type TestWorker } from 'orca/testing'
3
+ import type { NoticeItem } from '../protocol.ts'
4
+ import * as main from '../worker.ts'
5
+
6
+ const PLAN = {
7
+ version: 1,
8
+ run: '20261107-recargas',
9
+ source: 'spec-kit 003-recargas',
10
+ autonomy: 'semi',
11
+ base: null,
12
+ integration: 'feat/003-recargas',
13
+ merge: 'feat/003-recargas → main',
14
+ units: [
15
+ { round: 0, id: 'U0', title: 'setup', role: 'Hefesto', level: 'alto', agent: 'coordinador', model: null, resource: 'inline', files: '7', depends: null },
16
+ { round: 1, id: 'U2', title: 'recarga', role: 'Ariadna', level: 'alto', agent: 'claude', model: '<alto>', resource: 'worker', files: '11', depends: 'U0' }
17
+ ],
18
+ notes: ['modelos: nuevo']
19
+ }
20
+ const PLAN_PATH = 'C:\\repo\\.work\\runs\\r1\\plan.json'
21
+
22
+ let worker: TestWorker | undefined
23
+ afterEach(async () => {
24
+ await worker?.deactivate()
25
+ worker = undefined
26
+ })
27
+
28
+ const start = async (results: Record<string, unknown> = {}) => {
29
+ worker = await mountWorker(main, {
30
+ host: mockHost({
31
+ results: {
32
+ 'workspace.readContext': { branch: 'main', displayName: 'app', terminals: [] },
33
+ 'workspace.list': {
34
+ workspaces: [{ id: 'w1', kind: 'worktree', name: 'app', path: '/repo/app', branch: 'refs/heads/main', hostId: null }],
35
+ truncated: false
36
+ },
37
+ 'agents.list': { agents: [] },
38
+ 'terminal.read': { lines: [], truncated: false },
39
+ 'terminal.sendText': { accepted: true },
40
+ 'notifications.show': { delivered: true },
41
+ 'statusBar.update': { ok: true },
42
+ ...results
43
+ }
44
+ })
45
+ })
46
+ return worker
47
+ }
48
+
49
+ const settle = () => new Promise<void>((resolve) => setTimeout(resolve, 5))
50
+ const list = async (w: TestWorker) => ((await w.request('notices.list')) as { items: NoticeItem[] }).items
51
+ const status = (terminalId: string, state: 'working' | 'blocked' | 'waiting' | 'done', receivedAt: number) => ({
52
+ workspaceId: 'w1',
53
+ paneKey: `p-${terminalId}`,
54
+ terminalId,
55
+ state,
56
+ receivedAt,
57
+ title: `agente ${terminalId}`
58
+ })
59
+ // `terminalId: null` es un coordinador sin terminal: Orca no manda el campo.
60
+ const write = (path: string, content: string, terminalId: string | null = 't1', tool = 'Write') =>
61
+ ({ agent: 'claude', workspaceId: 'w1', ...(terminalId === null ? {} : { terminalId }), tool, input: { file_path: path, content } }) as never
62
+
63
+ test('un Write de plan.json enseña la tarjeta, avisa y la deja en el historial', async () => {
64
+ const w = await start()
65
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
66
+ const [notice, ...rest] = await list(w)
67
+ assert.equal(rest.length, 0)
68
+ assert.equal(notice?.id, 'plan:20261107-recargas')
69
+ assert.equal(notice?.kind, 'plan')
70
+ assert.equal(notice?.canReply, true)
71
+ assert.equal(notice?.plan?.units.length, 2)
72
+ assert.deepEqual(w.host.callsOf('notifications.show'), [
73
+ { title: 'Plan listo: 20261107-recargas', body: '2 unidades en 2 rondas. Confírmalo en Avisos.' }
74
+ ])
75
+ assert.equal(w.posts.filter((post) => post.event === 'notices.changed').length, 1)
76
+ assert.deepEqual(w.refusals, [])
77
+ })
78
+
79
+ test('otro tool, otra ruta o un JSON roto no hacen nada; lo roto queda en el log', async () => {
80
+ const w = await start()
81
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN), 't1', 'Edit'))
82
+ await w.hooks.fire('agent.tool.after', write('C:\\repo\\notas.json', JSON.stringify(PLAN)))
83
+ await w.hooks.fire('agent.tool.after', { agent: 'claude', workspaceId: 'w1', terminalId: 't1', tool: 'Write', input: 'x' } as never)
84
+ assert.deepEqual(await list(w), [])
85
+ assert.equal(w.logs.length, 0)
86
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, '{ roto'))
87
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify({ ...PLAN, version: 9 })))
88
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, 'x'.repeat(70 * 1024)))
89
+ assert.deepEqual(await list(w), [])
90
+ assert.equal(w.logs.filter((line) => line.startsWith('plan.json ignorado')).length, 3)
91
+ assert.equal(w.host.callsOf('notifications.show').length, 0)
92
+ })
93
+
94
+ test('un plan nuevo del mismo run sustituye al anterior; sin terminal no se puede responder', async () => {
95
+ const w = await start()
96
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
97
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify({ ...PLAN, units: [PLAN.units[0]] }), null))
98
+ const items = await list(w)
99
+ assert.equal(items.length, 1)
100
+ assert.equal(items[0]?.plan?.units.length, 1)
101
+ assert.equal(items[0]?.canReply, false)
102
+ await assert.rejects(w.request('notices.reply', { id: 'plan:20261107-recargas', text: 'sí' }), /no se le puede escribir/)
103
+ })
104
+
105
+ test('«sí» y «cambia: …» se escriben en el terminal del coordinador y quitan el aviso', async () => {
106
+ const w = await start()
107
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN), 't7'))
108
+ const result = await w.request('notices.reply', { id: 'plan:20261107-recargas', text: 'sí' })
109
+ assert.deepEqual(w.host.callsOf('terminal.sendText'), [{ terminalId: 't7', text: 'sí', enter: true }])
110
+ assert.match(result.message, /Enviado a su terminal: Plan de rondas/)
111
+ assert.deepEqual(await list(w), [])
112
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN), 't7'))
113
+ await w.request('notices.reply', { id: 'plan:20261107-recargas', text: 'cambia: sin la ronda 2' })
114
+ assert.equal((w.host.callsOf('terminal.sendText')[1] as { text: string }).text, 'cambia: sin la ronda 2')
115
+ })
116
+
117
+ test('un agente bloqueado sale con su contexto limpio y desaparece al volver a trabajar', async () => {
118
+ const lines = ['\u001b[31mrojo\u001b[0m', '', 'x\u0007y', ...Array.from({ length: 20 }, (_, i) => `línea ${i}`), 'z'.repeat(300)]
119
+ const w = await start({ 'terminal.read': { lines, truncated: false } })
120
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
121
+ await settle()
122
+ const [notice] = await list(w)
123
+ assert.equal(notice?.id, 't:t1')
124
+ assert.equal(notice?.kind, 'blocked')
125
+ assert.equal(notice?.workspace, 'app')
126
+ assert.equal(notice?.canReply, true)
127
+ assert.equal(notice?.context.length, 12)
128
+ assert.equal(notice?.context.at(-1)?.length, 200)
129
+ assert.equal(notice?.context.at(-2), 'línea 19')
130
+ assert.deepEqual(w.host.callsOf('terminal.read'), [{ terminalId: 't1', maxLines: 40 }])
131
+ await w.emit('agent.status.changed', status('t1', 'working', 2000))
132
+ assert.deepEqual(await list(w), [])
133
+ await w.emit('agent.status.changed', status('t1', 'waiting', 3000))
134
+ assert.equal((await list(w))[0]?.kind, 'waiting')
135
+ await w.emit('agent.status.changed', status('t1', 'done', 4000))
136
+ assert.deepEqual(await list(w), [])
137
+ })
138
+
139
+ test('un fallo al leer el terminal se registra y el aviso sale sin contexto', async () => {
140
+ const w = await start({
141
+ 'terminal.read': () => {
142
+ throw hostError('unavailable', 'sin terminal')
143
+ }
144
+ })
145
+ await w.emit('agent.status.changed', status('t1', 'waiting', 1000))
146
+ await settle()
147
+ const [notice] = await list(w)
148
+ assert.deepEqual(notice?.context, [])
149
+ assert.match(w.logs.join('\n'), /contexto de t:t1 no leído/)
150
+ })
151
+
152
+ test('un chat de Orca sin terminal sale pero no admite respuesta', async () => {
153
+ const w = await start()
154
+ await w.emit('agent.status.changed', {
155
+ workspaceId: 'w1',
156
+ paneKey: 'structured-agent-session-claude_abc:1',
157
+ state: 'blocked',
158
+ receivedAt: 1000
159
+ })
160
+ const [notice] = await list(w)
161
+ assert.equal(notice?.id, 'p:structured-agent-session-claude_abc:1')
162
+ assert.equal(notice?.agent, 'claude')
163
+ assert.equal(notice?.canReply, false)
164
+ assert.deepEqual(notice?.context, [])
165
+ assert.equal(w.host.callsOf('terminal.read').length, 0)
166
+ await assert.rejects(w.request('notices.reply', { id: notice?.id ?? '', text: 'hola' }), /no se le puede escribir/)
167
+ })
168
+
169
+ test('el orden es planes, bloqueados y esperando, y dentro el más antiguo primero', async () => {
170
+ const w = await start()
171
+ await w.emit('agent.status.changed', status('t1', 'waiting', 1000))
172
+ await w.emit('agent.status.changed', status('t2', 'blocked', 3000))
173
+ await w.emit('agent.status.changed', status('t3', 'blocked', 2000))
174
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
175
+ assert.deepEqual((await list(w)).map((item) => item.id), ['plan:20261107-recargas', 't:t3', 't:t2', 't:t1'])
176
+ })
177
+
178
+ test('una unidad del kit lleva su nombre de unidad', async () => {
179
+ const w = await start()
180
+ await w.hooks.fire('agent.prompt.before', {
181
+ agent: 'claude',
182
+ terminalId: 't1',
183
+ prompt: 'UNIT: U2 — Pagos RUN: r1 BASE: abc\nROL: Ariadna · código — nivel alto',
184
+ inputKind: 'orchestration'
185
+ })
186
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
187
+ const [notice] = await list(w)
188
+ assert.equal(notice?.unit, 'U2 · Ariadna — Pagos')
189
+ assert.equal(notice?.title, 'U2 · Ariadna — Pagos')
190
+ })
191
+
192
+ test('responder limpia el texto, quita el aviso y no lo deja volver con el mismo estado', async () => {
193
+ const w = await start()
194
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
195
+ const result = await w.request('notices.reply', { id: 't:t1', text: ' dale\u001b[31m\nahora\ty ya\r\n ' })
196
+ assert.deepEqual(w.host.callsOf('terminal.sendText'), [{ terminalId: 't1', text: 'dale[31m ahora y ya', enter: true }])
197
+ assert.equal(result.message, 'Enviado a su terminal: agente t1.')
198
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1500))
199
+ assert.deepEqual(await list(w), [])
200
+ await w.emit('agent.status.changed', status('t1', 'waiting', 2000))
201
+ assert.equal((await list(w)).length, 1)
202
+ })
203
+
204
+ test('responder rechaza ids desconocidos, textos vacíos o largos y no textos', async () => {
205
+ const w = await start()
206
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
207
+ await assert.rejects(w.request('notices.reply', { id: 't:otro', text: 'hola' }), /ya no existe/)
208
+ await assert.rejects(w.request('notices.reply', { id: 't1', text: 'hola' }), /ya no existe/)
209
+ for (const text of ['', ' \n\t ', '\u001b\u0007', 'x'.repeat(2001), 5 as never]) {
210
+ await assert.rejects(w.request('notices.reply', { id: 't:t1', text }), (error: unknown) => (error as { code?: string }).code === 'invalid_params')
211
+ }
212
+ assert.equal(w.host.callsOf('terminal.sendText').length, 0)
213
+ assert.equal((await list(w)).length, 1)
214
+ await w.request('notices.reply', { id: 't:t1', text: 'x'.repeat(2000) })
215
+ assert.equal(w.host.callsOf('terminal.sendText').length, 1)
216
+ })
217
+
218
+ test('si el terminal no acepta el texto, el aviso se queda y el error es claro', async () => {
219
+ const w = await start({ 'terminal.sendText': { accepted: false } })
220
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
221
+ await assert.rejects(w.request('notices.reply', { id: 't:t1', text: 'hola' }), /no aceptó el texto/)
222
+ assert.equal((await list(w)).length, 1)
223
+ })
224
+
225
+ test('descartar quita el aviso; el de un agente no vuelve hasta que cambie su estado', async () => {
226
+ const w = await start()
227
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
228
+ await w.request('notices.dismiss', { id: 't:t1' })
229
+ assert.deepEqual(await list(w), [])
230
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1200))
231
+ assert.deepEqual(await list(w), [])
232
+ await w.emit('agent.status.changed', status('t1', 'working', 1500))
233
+ await w.emit('agent.status.changed', status('t1', 'blocked', 2000))
234
+ assert.equal((await list(w)).length, 1)
235
+ await assert.rejects(w.request('notices.dismiss', { id: 'nada' }), /ya no existe/)
236
+ })
237
+
238
+ test('un plan descartado no vuelve hasta que llegue otro plan.json', async () => {
239
+ const w = await start()
240
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
241
+ await w.request('notices.dismiss', { id: 'plan:20261107-recargas' })
242
+ assert.deepEqual(await list(w), [])
243
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
244
+ assert.equal((await list(w)).length, 1)
245
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
246
+ assert.equal((await list(w)).length, 2)
247
+ })
248
+
249
+ test('al quitar un workspace salen sus avisos de agente, no los planes', async () => {
250
+ const w = await start()
251
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
252
+ await w.hooks.fire('agent.tool.after', write(PLAN_PATH, JSON.stringify(PLAN)))
253
+ await w.emit('workspace.removed', { workspaceId: 'w1', kind: 'worktree', path: '/repo/app' })
254
+ assert.deepEqual((await list(w)).map((item) => item.id), ['plan:20261107-recargas'])
255
+ })
256
+
257
+ test('notices.changed solo se publica cuando cambia lo que se ve', async () => {
258
+ const w = await start()
259
+ const changes = () => w.posts.filter((post) => post.event === 'notices.changed').length
260
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
261
+ await settle()
262
+ const before = changes()
263
+ await w.emit('agent.status.changed', status('t1', 'blocked', 1000))
264
+ assert.equal(changes(), before)
265
+ })
266
+
267
+ // Un coordinador que corre como chat de Orca: sin terminal ni hook de herramientas. El plan sale
268
+ // del disco cuando se para, y la respuesta va al buzón de su run de Orca.
269
+ const CHAT_PANE = 'structured-agent-session-claude_abc:1'
270
+ const chatStatus = (state: 'working' | 'waiting', receivedAt: number) => ({ workspaceId: 'w1', paneKey: CHAT_PANE, state, receivedAt })
271
+
272
+ const withSystem = (plans: { mtimeMs: number; content: string }[]) => {
273
+ const sent: { orcaRun: string; subject: string; body: string }[] = []
274
+ const reads: { path: string; since: number }[] = []
275
+ const previous = main.hostSystem.current
276
+ main.hostSystem.current = {
277
+ readPlans: async (path, since) => {
278
+ reads.push({ path, since })
279
+ return plans.filter((plan) => plan.mtimeMs > since).map((plan) => ({ path: `${path}/.work/runs/r1/plan.json`, ...plan }))
280
+ },
281
+ sendToRun: async (orcaRun, subject, body) => {
282
+ sent.push({ orcaRun, subject, body })
283
+ }
284
+ }
285
+ return { sent, reads, restore: () => (main.hostSystem.current = previous) }
286
+ }
287
+
288
+ test('con el coordinador en un chat, el plan sale del disco al pararse y «sí» va al buzón de su run', async () => {
289
+ const later = Date.now() + 60_000
290
+ const system = withSystem([{ mtimeMs: later, content: JSON.stringify({ ...PLAN, orcaRun: 'run_4fbb2d2e147c' }) }])
291
+ try {
292
+ const w = await start()
293
+ await w.emit('agent.status.changed', chatStatus('waiting', 1))
294
+ await settle()
295
+ const [plan, chat] = await list(w)
296
+ assert.equal(plan?.kind, 'plan')
297
+ assert.equal(plan?.via, 'run')
298
+ assert.equal(plan?.canReply, true)
299
+ assert.deepEqual(system.reads.map(({ path }) => path), ['/repo/app'])
300
+ // El chat del coordinador también se puede contestar: va al mismo buzón.
301
+ await w.emit('agent.status.changed', chatStatus('working', 2))
302
+ await w.emit('agent.status.changed', chatStatus('waiting', 3))
303
+ await settle()
304
+ assert.equal((await list(w)).find(({ kind }) => kind === 'waiting')?.via, 'run')
305
+ assert.ok(chat === undefined || chat.kind === 'waiting')
306
+ const result = await w.request('notices.reply', { id: plan?.id ?? '', text: 'sí' })
307
+ assert.match(result.message, /al chat del coordinador/)
308
+ assert.deepEqual(system.sent, [{ orcaRun: 'run_4fbb2d2e147c', subject: 'Respuesta desde el panel: Plan de rondas · 20261107-recargas', body: 'sí' }])
309
+ assert.equal(w.host.callsOf('terminal.sendText').length, 0)
310
+ // Pararse otra vez no lo saca de nuevo: ese plan.json ya se vio.
311
+ await w.emit('agent.status.changed', chatStatus('working', 4))
312
+ await w.emit('agent.status.changed', chatStatus('waiting', 5))
313
+ await settle()
314
+ assert.equal((await list(w)).filter(({ kind }) => kind === 'plan').length, 0)
315
+ } finally {
316
+ system.restore()
317
+ }
318
+ })
319
+
320
+ test('un plan.json de antes de arrancar el plugin no sale, y sin run de Orca el chat no se puede contestar', async () => {
321
+ const system = withSystem([{ mtimeMs: 1, content: JSON.stringify(PLAN) }])
322
+ try {
323
+ const w = await start()
324
+ await w.emit('agent.status.changed', chatStatus('waiting', 1))
325
+ await settle()
326
+ const items = await list(w)
327
+ assert.deepEqual(items.map(({ kind }) => kind), ['waiting'])
328
+ assert.equal(items[0]?.canReply, false)
329
+ assert.equal(items[0]?.via, null)
330
+ await assert.rejects(w.request('notices.reply', { id: items[0]?.id ?? '', text: 'hola' }), /no se le puede escribir/)
331
+ assert.deepEqual(system.sent, [])
332
+ } finally {
333
+ system.restore()
334
+ }
335
+ })
336
+
337
+ test('si Orca no entrega la respuesta, se dice y el aviso se queda', async () => {
338
+ const later = Date.now() + 60_000
339
+ const system = withSystem([{ mtimeMs: later, content: JSON.stringify({ ...PLAN, orcaRun: 'run_4fbb2d2e147c' }) }])
340
+ main.hostSystem.current = {
341
+ ...main.hostSystem.current,
342
+ sendToRun: async () => {
343
+ throw Object.assign(new Error('Orca no entregó el mensaje (runtime_unavailable: x)'), { code: 'unavailable' })
344
+ }
345
+ }
346
+ try {
347
+ const w = await start()
348
+ await w.emit('agent.status.changed', chatStatus('waiting', 1))
349
+ await settle()
350
+ const [plan] = await list(w)
351
+ await assert.rejects(w.request('notices.reply', { id: plan?.id ?? '', text: 'sí' }), /no entregó/)
352
+ assert.equal((await list(w))[0]?.kind, 'plan')
353
+ } finally {
354
+ system.restore()
355
+ }
356
+ })
@@ -0,0 +1,288 @@
1
+ // Pestaña Avisos: lo que espera a la persona (planes de rondas por confirmar, agentes bloqueados o
2
+ // esperando) y sus respuestas. Con terminal, la respuesta se escribe en él; con el coordinador en un
3
+ // chat de Orca, va al buzón de su run de Orca, que se la entrega en el chat (src/worker/system.ts).
4
+ // Estado en memoria: un aviso por agente que espera (clave del núcleo) y uno por plan (`plan:<run>`).
5
+ import { ANSI, agentName, canonicalWorkspaceId, cleanLabel, type TrackedAgent } from '../kit.ts'
6
+ import { parsePlan, planPathRun } from '../plan-card.ts'
7
+ import type { NoticeItem, PlanCard } from '../protocol.ts'
8
+ import type { KitContext, KitEvents } from './context.ts'
9
+
10
+ const CONTEXT_READ_LINES = 40
11
+ const CONTEXT_LINES = 12
12
+ const CONTEXT_LINE_MAX = 200
13
+ const PLAN_BYTES_MAX = 64 * 1024
14
+ const REPLY_MAX = 2000
15
+ const DETAIL_MAX = 120
16
+ const KIND_ORDER: Record<NoticeItem['kind'], number> = { plan: 0, blocked: 1, waiting: 2 }
17
+
18
+ // Un aviso y lo que el panel no ve: el terminal o el run de Orca al que se responde, su workspace
19
+ // y su run del kit.
20
+ type Entry = {
21
+ item: NoticeItem
22
+ terminalId: string | null
23
+ workspaceId: string | null
24
+ run: string | null
25
+ orcaRun: string | null
26
+ }
27
+
28
+ // Quién ha escrito o tiene el plan: el agente que se para o el que llama a su herramienta.
29
+ type PlanSource = { agent: string | null; terminalId: string | null; workspaceId: string | null; at: number }
30
+
31
+ const invalidParams = (message: string) => Object.assign(new Error(message), { code: 'invalid_params' })
32
+ const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error))
33
+
34
+ // Una línea sin saltos, tabuladores ni caracteres de control o de formato, recortada.
35
+ function replyText(value: unknown): string {
36
+ if (typeof value !== 'string') throw invalidParams('el texto de la respuesta no es un texto')
37
+ const text = value
38
+ .replace(/\r\n|\n|\t/g, ' ')
39
+ .replace(/[\p{Cc}\p{Cf}]/gu, '')
40
+ .trim()
41
+ if (text === '') throw invalidParams('la respuesta está vacía')
42
+ if (text.length > REPLY_MAX) throw invalidParams(`la respuesta pasa de ${REPLY_MAX} caracteres`)
43
+ return text
44
+ }
45
+
46
+ function contextLines(lines: readonly string[]): string[] {
47
+ const clean: string[] = []
48
+ for (const line of lines) {
49
+ const text = cleanLabel(line.replace(ANSI, ''), CONTEXT_LINE_MAX)
50
+ if (text !== null) clean.push(text)
51
+ }
52
+ return clean.slice(-CONTEXT_LINES)
53
+ }
54
+
55
+ /** Por dónde va la respuesta: el terminal manda; sin él, el buzón del run de Orca del coordinador. */
56
+ function route(terminalId: string | null, orcaRun: string | null): Pick<NoticeItem, 'canReply' | 'via'> {
57
+ if (terminalId !== null) return { canReply: true, via: 'terminal' }
58
+ if (orcaRun !== null) return { canReply: true, via: 'run' }
59
+ return { canReply: false, via: null }
60
+ }
61
+
62
+ export function registerNotices(ctx: KitContext): void {
63
+ const entries = new Map<string, Entry>()
64
+ // Avisos de agente descartados, con el estado en que se descartaron: no vuelven hasta que cambie.
65
+ const dismissed = new Map<string, TrackedAgent['state']>()
66
+ // Por workspace del coordinador, el run de Orca de su último plan: su buzón llega a su chat.
67
+ const coordinatorRuns = new Map<string, string>()
68
+ // Por carpeta de workspace, hasta cuándo se han mirado sus plan.json. Los de antes de arrancar
69
+ // el plugin no salen: son de runs ya confirmados o abandonados.
70
+ const plansSeen = new Map<string, number>()
71
+ const startedAt = Date.now()
72
+ let posted = ''
73
+
74
+ const items = () =>
75
+ [...entries.values()]
76
+ .map(({ item }) => item)
77
+ .sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || a.since - b.since)
78
+
79
+ // Los paneles abiertos reciben la lista solo cuando cambia lo serializado.
80
+ const publish = () => {
81
+ const view = { items: items() }
82
+ const serialized = JSON.stringify(view)
83
+ if (serialized === posted) return
84
+ posted = serialized
85
+ ctx.panels.post('notices.changed', view)
86
+ }
87
+
88
+ const remove = (id: string) => {
89
+ if (entries.delete(id)) publish()
90
+ }
91
+
92
+ // Lo último que pinta el terminal. Un fallo se registra y el aviso se queda sin contexto.
93
+ const loadContext = async (id: string, terminalId: string, since: number) => {
94
+ let lines: string[]
95
+ try {
96
+ lines = contextLines((await ctx.host.call('terminal.read', { terminalId, maxLines: CONTEXT_READ_LINES })).lines)
97
+ } catch (error) {
98
+ ctx.log(`contexto de ${id} no leído: ${describeError(error)}`)
99
+ return
100
+ }
101
+ const entry = entries.get(id)
102
+ // El agente pudo cambiar de estado o desaparecer mientras se leía.
103
+ if (!entry || entry.item.since !== since) return
104
+ entries.set(id, { ...entry, item: { ...entry.item, context: lines } })
105
+ publish()
106
+ }
107
+
108
+ const showPlan = (plan: PlanCard, source: PlanSource) => {
109
+ const id = `plan:${plan.run}`
110
+ const rounds = new Set(plan.units.map(({ round }) => round)).size
111
+ const summary = `${plan.units.length} unidades en ${rounds} rondas`
112
+ if (plan.orcaRun !== null && source.workspaceId !== null) coordinatorRuns.set(source.workspaceId, plan.orcaRun)
113
+ entries.set(id, {
114
+ item: {
115
+ id,
116
+ kind: 'plan',
117
+ title: `Plan de rondas · ${plan.run}`,
118
+ agent: source.agent === null ? null : cleanLabel(source.agent, 40),
119
+ workspace: ctx.workspaceName(source.workspaceId),
120
+ unit: null,
121
+ since: source.at,
122
+ context: [],
123
+ ...route(source.terminalId, plan.orcaRun),
124
+ plan
125
+ },
126
+ terminalId: source.terminalId,
127
+ workspaceId: source.workspaceId,
128
+ run: plan.run,
129
+ orcaRun: plan.orcaRun
130
+ })
131
+ publish()
132
+ ctx.notify(`Plan listo: ${plan.run}`, `${summary}. Confírmalo en Avisos.`)
133
+ ctx.emit('action', { kind: 'plan', title: `Plan listo: ${plan.run}`, detail: summary, agentKey: null, run: plan.run, at: source.at })
134
+ }
135
+
136
+ // Un plan.json escrito: se valida entero; lo que no encaja queda en el log y no sale.
137
+ const learnPlan = (label: string, content: unknown, source: PlanSource) => {
138
+ if (typeof content !== 'string' || content.length > PLAN_BYTES_MAX) {
139
+ ctx.log(`plan.json ignorado (${label}): el contenido no es un texto de hasta 64 KB`)
140
+ return
141
+ }
142
+ let plan
143
+ try {
144
+ plan = parsePlan(JSON.parse(content))
145
+ } catch (error) {
146
+ ctx.log(`plan.json ignorado (${label}): JSON roto, ${describeError(error)}`)
147
+ return
148
+ }
149
+ if (plan === null) {
150
+ ctx.log(`plan.json ignorado (${label}): no encaja con la versión 1 de plan-card.md`)
151
+ return
152
+ }
153
+ showPlan(plan, source)
154
+ }
155
+
156
+ const workspacePath = (workspaceId: string | null) => {
157
+ if (workspaceId === null) return null
158
+ const index = ctx.workspaces()
159
+ return index.byId.get(canonicalWorkspaceId(workspaceId, index))?.path ?? null
160
+ }
161
+
162
+ // Cuando un agente se para (también un chat de Orca, que no avisa de sus herramientas), los
163
+ // plan.json nuevos de su workspace.
164
+ const scanPlans = async (source: PlanSource) => {
165
+ const path = workspacePath(source.workspaceId)
166
+ if (path === null) return
167
+ const since = plansSeen.get(path) ?? startedAt
168
+ let files
169
+ try {
170
+ files = await ctx.system.readPlans(path, since)
171
+ } catch (error) {
172
+ ctx.log(`plan.json de ${cleanLabel(path, 120)} no leídos: ${describeError(error)}`)
173
+ return
174
+ }
175
+ if (files.length === 0) return
176
+ plansSeen.set(path, Math.max(since, ...files.map(({ mtimeMs }) => mtimeMs)))
177
+ for (const file of files) learnPlan(cleanLabel(file.path, 120) ?? 'plan.json', file.content, source)
178
+ }
179
+
180
+ const onAgent = ({ key, agent, state, at }: KitEvents['agent']) => {
181
+ if (agent === null || (state !== 'blocked' && state !== 'waiting')) {
182
+ dismissed.delete(key)
183
+ remove(key)
184
+ return
185
+ }
186
+ const terminalId = agent.terminalId ?? null
187
+ if (state === 'waiting') {
188
+ void scanPlans({ agent: agent.agent ?? null, terminalId, workspaceId: agent.workspaceId, at })
189
+ }
190
+ if (dismissed.get(key) === state) return
191
+ dismissed.delete(key)
192
+ const previous = entries.get(key)
193
+ const since = agent.since ?? at
194
+ const changed = previous?.item.kind !== state || previous.item.since !== since
195
+ const { unit } = agent
196
+ // Un chat que coordina un run con plan: se le responde por el buzón de ese run.
197
+ const orcaRun = terminalId === null && agent.workspaceId !== null ? (coordinatorRuns.get(agent.workspaceId) ?? null) : null
198
+ const item: NoticeItem = {
199
+ id: key,
200
+ kind: state,
201
+ title: agentName(agent),
202
+ agent: agent.agent ?? null,
203
+ workspace: ctx.workspaceName(agent.workspaceId),
204
+ unit: unit ? agentName({ ...agent, title: null }) : null,
205
+ since,
206
+ context: changed ? [] : (previous?.item.context ?? []),
207
+ ...route(terminalId, orcaRun),
208
+ plan: null
209
+ }
210
+ entries.set(key, { item, terminalId, workspaceId: agent.workspaceId, run: unit?.run ?? null, orcaRun })
211
+ publish()
212
+ if (changed && terminalId !== null) void loadContext(key, terminalId, since)
213
+ }
214
+
215
+ const onTool = (event: KitEvents['tool']) => {
216
+ if (event.tool !== 'Write') return
217
+ const input = event.input
218
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) return
219
+ const { file_path: file, content } = input
220
+ if (typeof file !== 'string' || planPathRun(file) === null) return
221
+ // Visto por el hook: cuando el agente se pare no se vuelve a sacar del disco.
222
+ const path = workspacePath(event.workspaceId)
223
+ if (path !== null) plansSeen.set(path, Date.now())
224
+ learnPlan(cleanLabel(file, 120) ?? 'plan.json', content, {
225
+ agent: event.agent,
226
+ terminalId: event.terminalId,
227
+ workspaceId: event.workspaceId,
228
+ at: event.at
229
+ })
230
+ }
231
+
232
+ ctx.on('agent', onAgent)
233
+ ctx.on('tool', onTool)
234
+ ctx.on('workspaceRemoved', ({ workspaceId }) => {
235
+ for (const [id, entry] of entries) {
236
+ if (entry.item.kind !== 'plan' && entry.workspaceId === workspaceId) entries.delete(id)
237
+ }
238
+ coordinatorRuns.delete(workspaceId)
239
+ for (const key of dismissed.keys()) if (!ctx.agents.has(key)) dismissed.delete(key)
240
+ publish()
241
+ })
242
+
243
+ ctx.panels.handle('notices.list', () => ({ items: items() }))
244
+
245
+ ctx.panels.handle('notices.reply', async (input) => {
246
+ const id: unknown = input?.id
247
+ const entry = typeof id === 'string' ? entries.get(id) : undefined
248
+ if (!entry) throw invalidParams('ese aviso ya no existe')
249
+ const { terminalId, orcaRun } = entry
250
+ if (!entry.item.canReply || (terminalId === null && orcaRun === null)) {
251
+ throw invalidParams('a ese aviso no se le puede escribir desde aquí')
252
+ }
253
+ const text = replyText(input?.text)
254
+ const { title } = entry.item
255
+ if (terminalId !== null) {
256
+ const { accepted } = await ctx.host.call('terminal.sendText', { terminalId, text, enter: true })
257
+ if (!accepted) {
258
+ throw Object.assign(new Error('el terminal no aceptó el texto: puede que ya se haya cerrado'), { code: 'unavailable' })
259
+ }
260
+ } else if (orcaRun !== null) {
261
+ await ctx.system.sendToRun(orcaRun, `Respuesta desde el panel: ${title}`, text)
262
+ }
263
+ // Respondido: no vuelve hasta que el agente cambie de estado (un evento repetido no lo resucita).
264
+ if (entry.item.kind !== 'plan') dismissed.set(entry.item.id, entry.item.kind)
265
+ entries.delete(entry.item.id)
266
+ publish()
267
+ const agentKey = entry.item.kind !== 'plan' ? entry.item.id : terminalId === null ? null : `t:${terminalId}`
268
+ ctx.emit('action', {
269
+ kind: 'reply',
270
+ title: `Respuesta a ${title}`,
271
+ detail: cleanLabel(text, DETAIL_MAX),
272
+ agentKey,
273
+ run: entry.run,
274
+ at: Date.now()
275
+ })
276
+ const where = terminalId !== null ? 'a su terminal' : 'al chat del coordinador'
277
+ return { message: `Enviado ${where}: ${title}.` }
278
+ })
279
+
280
+ ctx.panels.handle('notices.dismiss', (input) => {
281
+ const id: unknown = input?.id
282
+ const entry = typeof id === 'string' ? entries.get(id) : undefined
283
+ if (!entry) throw invalidParams('ese aviso ya no existe')
284
+ if (entry.item.kind !== 'plan') dismissed.set(entry.item.id, entry.item.kind)
285
+ remove(entry.item.id)
286
+ return { message: `Descartado: ${entry.item.title}.` }
287
+ })
288
+ }