orca-multiagent-kit 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -7
  3. package/VERSION +1 -1
  4. package/bin/omk.js +47 -4
  5. package/bin/orca.js +170 -0
  6. package/bin/sea.js +95 -0
  7. package/bin/setup.js +326 -0
  8. package/bin/team.js +353 -0
  9. package/core/AGENTS.md +1 -1
  10. package/docs/EJECUTABLE.md +70 -0
  11. package/docs/PLUGIN-ORCA.md +126 -28
  12. package/orca-plugin/README.md +5 -1
  13. package/orca-plugin/assets/logos/README.md +10 -0
  14. package/orca-plugin/assets/logos/agent.png +0 -0
  15. package/orca-plugin/assets/logos/aider.png +0 -0
  16. package/orca-plugin/assets/logos/amp.png +0 -0
  17. package/orca-plugin/assets/logos/antigravity.png +0 -0
  18. package/orca-plugin/assets/logos/claude.png +0 -0
  19. package/orca-plugin/assets/logos/cline.png +0 -0
  20. package/orca-plugin/assets/logos/codex.png +0 -0
  21. package/orca-plugin/assets/logos/copilot.png +0 -0
  22. package/orca-plugin/assets/logos/cursor.png +0 -0
  23. package/orca-plugin/assets/logos/devin.png +0 -0
  24. package/orca-plugin/assets/logos/droid.png +0 -0
  25. package/orca-plugin/assets/logos/gemini.png +0 -0
  26. package/orca-plugin/assets/logos/goose.png +0 -0
  27. package/orca-plugin/assets/logos/grok.png +0 -0
  28. package/orca-plugin/assets/logos/kimi.png +0 -0
  29. package/orca-plugin/assets/logos/kiro.png +0 -0
  30. package/orca-plugin/assets/logos/opencode.png +0 -0
  31. package/orca-plugin/assets/logos/qwen-code.png +0 -0
  32. package/orca-plugin/orca-plugin.json +28 -7
  33. package/orca-plugin/src/icons.test.ts +14 -0
  34. package/orca-plugin/src/icons.ts +30 -0
  35. package/orca-plugin/src/kit.test.ts +456 -9
  36. package/orca-plugin/src/kit.ts +639 -16
  37. package/orca-plugin/src/models.test.ts +28 -0
  38. package/orca-plugin/src/models.ts +29 -0
  39. package/orca-plugin/src/node.d.ts +40 -0
  40. package/orca-plugin/src/panel-state.ts +28 -0
  41. package/orca-plugin/src/panel.test.tsx +298 -0
  42. package/orca-plugin/src/panel.tsx +609 -0
  43. package/orca-plugin/src/plan-card.test.ts +99 -0
  44. package/orca-plugin/src/plan-card.ts +107 -0
  45. package/orca-plugin/src/protocol.ts +179 -0
  46. package/orca-plugin/src/tabs/autonomy.tsx +70 -0
  47. package/orca-plugin/src/tabs/history.test.tsx +78 -0
  48. package/orca-plugin/src/tabs/history.tsx +118 -0
  49. package/orca-plugin/src/tabs/notices.test.tsx +183 -0
  50. package/orca-plugin/src/tabs/notices.tsx +274 -0
  51. package/orca-plugin/src/tabs/worktrees.test.tsx +130 -0
  52. package/orca-plugin/src/tabs/worktrees.tsx +138 -0
  53. package/orca-plugin/src/ui/agent-icon.tsx +13 -0
  54. package/orca-plugin/src/worker/context.test.ts +32 -0
  55. package/orca-plugin/src/worker/context.ts +92 -0
  56. package/orca-plugin/src/worker/history.test.ts +149 -0
  57. package/orca-plugin/src/worker/history.ts +181 -0
  58. package/orca-plugin/src/worker/notices.test.ts +356 -0
  59. package/orca-plugin/src/worker/notices.ts +291 -0
  60. package/orca-plugin/src/worker/system.test.ts +58 -0
  61. package/orca-plugin/src/worker/system.ts +122 -0
  62. package/orca-plugin/src/worker/worktrees.test.ts +177 -0
  63. package/orca-plugin/src/worker/worktrees.ts +188 -0
  64. package/orca-plugin/src/worker.test.ts +297 -15
  65. package/orca-plugin/src/worker.ts +353 -32
  66. package/package.json +3 -2
  67. package/skills/orca/SKILL.md +1 -0
  68. package/skills/orca/references/engine-orca.md +1 -0
  69. package/skills/orca/references/olimpo.md +1 -0
  70. package/skills/orca/references/plan-card.md +45 -0
@@ -0,0 +1,138 @@
1
+ // Pestaña Worktrees: los worktrees de la orquestación por run, sus agentes y su modelo.
2
+ import { atom, Badge, Box, Button, Card, Collapsible, EmptyState, plugin, read, Row, Select, set, Stack, Text, type PanelContext } from 'orca'
3
+ import { CLAUDE_MODELS } from '../models.ts'
4
+ import { ask, busy, describeError } from '../panel-state.ts'
5
+ import type { WorktreeAgent, WorktreeGroup, WorktreeItem } from '../protocol.ts'
6
+ import { AgentIcon } from '../ui/agent-icon.tsx'
7
+
8
+ // El estado en español que da el worker (los de kit.ts): solo entonces se le puede escribir.
9
+ const WAITING = 'esperando'
10
+
11
+ const groups = atom<WorktreeGroup[] | null>(null)
12
+ // Por qué no se pudo leer la lista, para decirlo en la propia pestaña en vez de en el aviso de arriba.
13
+ const loadError = atom<string | null>(null)
14
+ // El modelo elegido en cada Select, por agente, hasta que se pulsa «Cambiar modelo».
15
+ const chosen = atom<Record<string, string>>({})
16
+
17
+ export function setupWorktrees(ctx: PanelContext): void {
18
+ ctx.subscriptions.push(plugin.on('worktrees.changed', (view) => set(groups, view.groups)))
19
+ void plugin
20
+ .request('worktrees.list')
21
+ .then((view) => set(groups, view.groups))
22
+ .catch((error: unknown) => set(loadError, describeError(error)))
23
+ }
24
+
25
+ const openWorktree = (workspaceId: string) => ask('open-worktree', () => plugin.request('worktrees.open', { workspaceId }))
26
+
27
+ const modelOf = (agent: WorktreeAgent) =>
28
+ read(chosen)[agent.id] ?? (CLAUDE_MODELS.some(({ value }) => value === agent.model) ? agent.model : null) ?? CLAUDE_MODELS[0]?.value ?? ''
29
+
30
+ const setModel = (agent: WorktreeAgent) =>
31
+ ask('model', () => plugin.request('worktrees.model', { id: agent.id, model: modelOf(agent) }))
32
+
33
+ function noModelChange(agent: WorktreeAgent): string | null {
34
+ if (!agent.canSetModel) return 'Es un chat de Orca: cambia el modelo desde su chat.'
35
+ if (agent.state !== WAITING) return 'Espera a que termine su turno para cambiarle el modelo.'
36
+ return null
37
+ }
38
+
39
+ function AgentRow({ agent }: { agent: WorktreeAgent }) {
40
+ const working = read(busy) !== null
41
+ const why = noModelChange(agent)
42
+ return (
43
+ <Stack gap="xs">
44
+ <Row gap="xs" align="center" wrap>
45
+ <AgentIcon agent={agent.agent} />
46
+ <Text weight="semibold" size="sm">
47
+ {agent.title}
48
+ </Text>
49
+ <Badge tone={agent.blocked ? 'warning' : 'neutral'}>{agent.state}</Badge>
50
+ <Badge tone="neutral">{agent.model ?? 'modelo no informado'}</Badge>
51
+ </Row>
52
+ {agent.agent === 'claude' ? (
53
+ <Row gap="xs" align="end" wrap>
54
+ {agent.canSetModel ? (
55
+ <Select
56
+ label={`Modelo de ${agent.title}`}
57
+ value={modelOf(agent)}
58
+ options={CLAUDE_MODELS}
59
+ onChange={(value) => set(chosen, { ...read(chosen), [agent.id]: value })}
60
+ />
61
+ ) : null}
62
+ {agent.canSetModel ? (
63
+ <Button variant="outline" size="sm" disabled={working || why !== null} onPress={() => setModel(agent)}>
64
+ Cambiar modelo
65
+ </Button>
66
+ ) : null}
67
+ {why === null ? null : (
68
+ <Text muted size="xs">
69
+ {why}
70
+ </Text>
71
+ )}
72
+ </Row>
73
+ ) : null}
74
+ </Stack>
75
+ )
76
+ }
77
+
78
+ function Worktree({ item }: { item: WorktreeItem }) {
79
+ const working = read(busy) !== null
80
+ // Como en la lista de worktrees de Orca: el logo del agente delante del nombre.
81
+ return (
82
+ <Row gap="xs" align="start">
83
+ <Box paddingY="sm">
84
+ <AgentIcon agent={item.agents[0]?.agent ?? null} />
85
+ </Box>
86
+ <Box grow>
87
+ <Collapsible
88
+ title={item.name}
89
+ description={[item.branch, item.unit].filter((part): part is string => Boolean(part)).join(' · ')}
90
+ defaultOpen={item.agents.some((agent) => agent.blocked)}
91
+ >
92
+ <Stack gap="sm">
93
+ <Row gap="xs">
94
+ <Button variant="outline" size="sm" icon="open-external" disabled={working} onPress={() => openWorktree(item.workspaceId)}>
95
+ Abrir worktree
96
+ </Button>
97
+ </Row>
98
+ {item.agents.map((agent) => (
99
+ <AgentRow agent={agent} />
100
+ ))}
101
+ </Stack>
102
+ </Collapsible>
103
+ </Box>
104
+ </Row>
105
+ )
106
+ }
107
+
108
+ export function Worktrees() {
109
+ const view = read(groups)
110
+ const failure = read(loadError)
111
+ if (view === null || view.length === 0) {
112
+ return (
113
+ <Card title="Worktrees" description="Los que crea la orquestación, por run.">
114
+ <Stack gap="xs">
115
+ <EmptyState icon="branch" title="Ningún worktree" description="Aparecen en cuanto el coordinador lanza unidades." />
116
+ {failure === null ? null : (
117
+ <Text muted size="xs">
118
+ No pude leer los worktrees: {failure}
119
+ </Text>
120
+ )}
121
+ </Stack>
122
+ </Card>
123
+ )
124
+ }
125
+ return (
126
+ <Stack gap="md">
127
+ {view.map((group) => (
128
+ <Card title={group.title} description={`${group.worktrees.length} worktree${group.worktrees.length === 1 ? '' : 's'}`}>
129
+ <Stack gap="xs">
130
+ {group.worktrees.map((item) => (
131
+ <Worktree item={item} />
132
+ ))}
133
+ </Stack>
134
+ </Card>
135
+ ))}
136
+ </Stack>
137
+ )
138
+ }
@@ -0,0 +1,13 @@
1
+ // El logo del agente (Claude, Codex…) delante de su nombre, del tamaño con que lo pinta Orca.
2
+ // `Image` solo tiene tamaños de 48 px para arriba: con Markdown la imagen sale a su tamaño.
3
+ import { Markdown } from 'orca'
4
+ import { agentIcon } from '../icons.ts'
5
+ import { agentLabel } from '../kit.ts'
6
+
7
+ const SIZE = 16
8
+
9
+ export function AgentIcon({ agent }: { agent: string | null | undefined }) {
10
+ // `agentLabel` sale de una lista cerrada o de un id validado; aun así, nada de `<>"` en el alt.
11
+ const alt = (agent ? agentLabel(agent) : 'Agente').replace(/[<>"&]/g, '')
12
+ return <Markdown content={`<img src="${agentIcon(agent)}" alt="${alt}" width="${SIZE}" height="${SIZE}">`} />
13
+ }
@@ -0,0 +1,32 @@
1
+ // El reparto de sucesos entre el núcleo del worker y las pestañas.
2
+ import { assert, test } from 'orca/testing'
3
+ import { createBus } from './context.ts'
4
+
5
+ const runDone = (run: string) => ({ run, notice: { title: run, body: '' }, at: 1 })
6
+
7
+ test('reparte cada suceso a sus oyentes en orden de registro', () => {
8
+ const bus = createBus(() => assert.fail('nadie falla'))
9
+ const seen: string[] = []
10
+ bus.on('runDone', ({ run }) => seen.push(`a:${run}`))
11
+ bus.on('runDone', ({ run }) => seen.push(`b:${run}`))
12
+ bus.on('workspaceRemoved', () => seen.push('otro'))
13
+ bus.emit('runDone', runDone('r1'))
14
+ assert.deepEqual(seen, ['a:r1', 'b:r1'])
15
+ })
16
+
17
+ test('un oyente que falla queda en el log y no corta a los demás', () => {
18
+ const logs: string[] = []
19
+ const bus = createBus((message) => logs.push(message))
20
+ const seen: string[] = []
21
+ bus.on('runDone', () => {
22
+ throw new Error('roto')
23
+ })
24
+ bus.on('runDone', ({ run }) => seen.push(run))
25
+ bus.emit('runDone', runDone('r2'))
26
+ assert.deepEqual(seen, ['r2'])
27
+ assert.deepEqual(logs, ['oyente de «runDone» falló: roto'])
28
+ })
29
+
30
+ test('sin oyentes no pasa nada', () => {
31
+ createBus(() => assert.fail('nadie falla')).emit('runDone', runDone('r3'))
32
+ })
@@ -0,0 +1,92 @@
1
+ // Lo que el núcleo del worker (src/worker.ts) comparte con cada pestaña: el host, el estado que
2
+ // ya sigue (agentes, terminales y workspaces) y los sucesos que oye una sola vez de Orca. Cada
3
+ // pestaña (src/worker/notices.ts, worktrees.ts, history.ts) se registra con `register(ctx)`.
4
+ import type { JsonValue, OrcaWorkerApi } from 'orca/worker'
5
+ import type { Notice, TrackedAgent, UnitInfo, WorkspaceIndex } from '../kit.ts'
6
+ import type { KitSystem } from './system.ts'
7
+
8
+ /** Lo que los hooks enseñan de un terminal antes, o además, de sus cambios de estado. */
9
+ export type TerminalInfo = { agent?: string; unit?: UnitInfo; workspaceId?: string }
10
+
11
+ /** Los sucesos que el núcleo reparte; `at` es ms desde epoch. */
12
+ export type KitEvents = {
13
+ /** Un agente cambió de estado. `agent` es `null` cuando terminó (`done`) y deja de seguirse. */
14
+ agent: {
15
+ key: string
16
+ previous: TrackedAgent | undefined
17
+ agent: TrackedAgent | null
18
+ /** El último estado que contó Orca, también cuando `agent` es `null`. */
19
+ state: TrackedAgent['state']
20
+ /** Cómo acabó el turno del agente principal, si Orca lo dice. */
21
+ outcome: string | null
22
+ at: number
23
+ }
24
+ /** Un despacho de la skill `orca` llegó al terminal de un agente. */
25
+ dispatch: { key: string; terminalId: string; unit: UnitInfo; agent: string | null; at: number }
26
+ /** Orca va a arrancar un agente en un terminal: `command` es la orden tal cual. */
27
+ launch: { terminalId: string; agent: string; workspaceId: string | null; command: string; at: number }
28
+ /** Un agente terminó una llamada a una herramienta (hook `agent.tool.after`; hoy, Claude Code). */
29
+ tool: { agent: string; workspaceId: string | null; terminalId: string | null; tool: string; input: JsonValue; at: number }
30
+ /** Orca quitó un workspace: lo que se recuerde de él sobra. */
31
+ workspaceRemoved: { workspaceId: string; at: number }
32
+ /** Terminaron todas las unidades lanzadas de un run del kit (el aviso de `trackRun`). */
33
+ runDone: { run: string; notice: Notice; at: number }
34
+ /** La persona hizo algo desde el panel que conviene dejar en el historial. */
35
+ action: {
36
+ kind: 'orchestrate' | 'reply' | 'model' | 'autonomy' | 'plan'
37
+ title: string
38
+ detail: string | null
39
+ /** Clave del agente afectado (`t:<terminal>`), si lo hay. */
40
+ agentKey: string | null
41
+ run: string | null
42
+ at: number
43
+ }
44
+ }
45
+
46
+ export type KitEventName = keyof KitEvents
47
+
48
+ export type KitContext = {
49
+ host: OrcaWorkerApi['host']
50
+ panels: OrcaWorkerApi['panels']
51
+ storage: OrcaWorkerApi['storage']
52
+ /** Disco y CLI de Orca, para los agentes que corren como chat (src/worker/system.ts). */
53
+ system: KitSystem
54
+ log(message: string): void
55
+ /** Notificación de escritorio, si la persona no desactivó «Avisos de agentes». */
56
+ notify(title: string, body: string): void
57
+ /** Los agentes que sigue el núcleo, por clave (`t:<terminal>` o `p:<panel>`). Solo lectura. */
58
+ agents: ReadonlyMap<string, TrackedAgent>
59
+ /** Lo que se sabe de cada terminal por los hooks. Solo lectura. */
60
+ terminals: ReadonlyMap<string, TerminalInfo>
61
+ workspaces(): WorkspaceIndex
62
+ /** El nombre de un workspace; si no se conoce, pide la lista una vez y devuelve `null`. */
63
+ workspaceName(workspaceId: string | null): string | null
64
+ /** Vuelve a pedir `workspace.list` (una sola petición a la vez). */
65
+ refreshWorkspaces(): Promise<void>
66
+ on<E extends KitEventName>(event: E, listener: (payload: KitEvents[E]) => void): void
67
+ emit<E extends KitEventName>(event: E, payload: KitEvents[E]): void
68
+ }
69
+
70
+ type Listener = (payload: never) => void
71
+
72
+ /**
73
+ * Reparto de sucesos en orden de registro. Un oyente que falla no corta a los demás: su error
74
+ * queda en el log del plugin con el suceso que lo causó.
75
+ */
76
+ export function createBus(log: (message: string) => void): Pick<KitContext, 'on' | 'emit'> {
77
+ const listeners = new Map<KitEventName, Listener[]>()
78
+ return {
79
+ on(event, listener) {
80
+ listeners.set(event, [...(listeners.get(event) ?? []), listener as Listener])
81
+ },
82
+ emit(event, payload) {
83
+ for (const listener of listeners.get(event) ?? []) {
84
+ try {
85
+ ;(listener as (value: typeof payload) => void)(payload)
86
+ } catch (error) {
87
+ log(`oyente de «${event}» falló: ${error instanceof Error ? error.message : String(error)}`)
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,149 @@
1
+ // El historial del worker contra un almacén en memoria que se puede frenar y hacer fallar.
2
+ import { assert, test } from 'orca/testing'
3
+ import type { TrackedAgent } from '../kit.ts'
4
+ import type { HistoryEntry } from '../protocol.ts'
5
+ import { createBus, type KitContext } from './context.ts'
6
+ import { HISTORY_KEY, HISTORY_MAX, registerHistory } from './history.ts'
7
+
8
+ type Store = { data: Map<string, unknown>; sets: number; active: number; peak: number; fail: boolean; delay: boolean }
9
+ const newStore = (): Store => ({ data: new Map(), sets: 0, active: 0, peak: 0, fail: false, delay: false })
10
+
11
+ const setup = (store: Store, agents: Map<string, TrackedAgent> = new Map()) => {
12
+ const logs: string[] = []
13
+ const posts: HistoryEntry[][] = []
14
+ const handlers = new Map<string, (input: unknown) => unknown>()
15
+ const bus = createBus((message) => logs.push(message))
16
+ const ctx = {
17
+ ...bus,
18
+ log: (message: string) => logs.push(message),
19
+ agents,
20
+ terminals: new Map([['t1', { workspaceId: 'w1' }]]),
21
+ workspaceName: (id: string | null) => (id === 'w1' ? 'app' : null),
22
+ storage: {
23
+ get: async (key: string) => (store.data.has(key) ? store.data.get(key) : null),
24
+ set: async (key: string, value: unknown) => {
25
+ store.sets += 1
26
+ store.active += 1
27
+ store.peak = Math.max(store.peak, store.active)
28
+ try {
29
+ if (store.delay) await new Promise((resolve) => setTimeout(resolve, 5))
30
+ if (store.fail) throw new Error('disco lleno')
31
+ store.data.set(key, JSON.parse(JSON.stringify(value)))
32
+ } finally {
33
+ store.active -= 1
34
+ }
35
+ }
36
+ },
37
+ panels: {
38
+ handle: (name: string, handler: (input: unknown) => unknown) => handlers.set(name, handler),
39
+ post: (_event: string, payload: { items: HistoryEntry[] }) => posts.push(payload.items)
40
+ }
41
+ } as unknown as KitContext
42
+ registerHistory(ctx)
43
+ const call = (name: string) => handlers.get(name)?.(undefined) as Promise<{ items?: HistoryEntry[]; message?: string }>
44
+ const list = async () => (await call('history.list')).items ?? []
45
+ return { ctx, logs, posts, call, list }
46
+ }
47
+
48
+ const unit = { unit: 'U1', title: 'Avisos', run: 'r1', role: 'Proteo' }
49
+ const tracked = (state: TrackedAgent['state']): TrackedAgent => ({ workspaceId: 'w1', title: 'espera', state, agent: 'claude', unit })
50
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 30))
51
+ const action = (title: string, at: number) =>
52
+ ({ kind: 'plan', title, detail: null, agentKey: null, run: null, at }) as const
53
+
54
+ test('apunta despacho, bloqueo, final, run y acción, el último primero, y sobrevive al reinicio', async () => {
55
+ const store = newStore()
56
+ const first = setup(store)
57
+ first.ctx.emit('dispatch', { key: 't:t1', terminalId: 't1', unit, agent: 'claude', at: 1 })
58
+ first.ctx.emit('agent', { key: 't:t1', previous: tracked('working'), agent: tracked('blocked'), state: 'blocked', outcome: null, at: 2 })
59
+ first.ctx.emit('agent', { key: 't:t1', previous: tracked('blocked'), agent: null, state: 'done', outcome: 'success', at: 3 })
60
+ first.ctx.emit('runDone', { run: 'r1', notice: { title: 'Run r1 terminado', body: 'Todo listo' }, at: 4 })
61
+ first.ctx.emit('action', { kind: 'reply', title: 'Respuesta a U1', detail: 'sí', agentKey: null, run: 'r1', at: 5 })
62
+ await settle()
63
+
64
+ const again = setup(store)
65
+ const items = await again.list()
66
+ assert.deepEqual(items.map((i) => i.kind), ['reply', 'run', 'outcome', 'state', 'dispatch'])
67
+ assert.deepEqual(items.map((i) => i.tone), ['accent', 'success', 'success', 'warning', 'accent'])
68
+ assert.equal(items[4]?.title, 'U1 · Proteo — Avisos despachado')
69
+ assert.equal(items[4]?.workspace, 'app')
70
+ assert.equal(items[2]?.title, 'U1 · Proteo — Avisos terminó')
71
+ assert.equal(new Set(items.map((i) => i.id)).size, 5)
72
+ })
73
+
74
+ test('un fallo termina en danger, otro final en neutral, y lo que no es del kit no se apunta', async () => {
75
+ const s = setup(newStore())
76
+ s.ctx.emit('agent', { key: 'a', previous: tracked('working'), agent: null, state: 'done', outcome: 'failure', at: 1 })
77
+ s.ctx.emit('agent', { key: 'b', previous: tracked('working'), agent: null, state: 'done', outcome: null, at: 2 })
78
+ s.ctx.emit('agent', { key: 'c', previous: { ...tracked('working'), unit: null }, agent: null, state: 'done', outcome: 'success', at: 3 })
79
+ s.ctx.emit('agent', { key: 'd', previous: tracked('blocked'), agent: tracked('blocked'), state: 'blocked', outcome: null, at: 4 })
80
+ assert.deepEqual((await s.list()).map((i) => i.tone), ['neutral', 'danger'])
81
+ })
82
+
83
+ test('guarda las 200 más recientes', async () => {
84
+ const s = setup(newStore())
85
+ for (let at = 1; at <= HISTORY_MAX + 5; at += 1) s.ctx.emit('action', action(`plan ${at}`, at))
86
+ const items = await s.list()
87
+ assert.equal(items.length, HISTORY_MAX)
88
+ assert.equal(items[0]?.title, `plan ${HISTORY_MAX + 5}`)
89
+ assert.equal(items.at(-1)?.title, 'plan 6')
90
+ })
91
+
92
+ test('un history.v1 dañado no rompe el arranque y se descarta entrada a entrada', async () => {
93
+ const bad = newStore()
94
+ bad.data.set(HISTORY_KEY, { no: 'lista' })
95
+ const a = setup(bad)
96
+ assert.deepEqual(await a.list(), [])
97
+ assert.equal(a.logs.length, 1)
98
+
99
+ const mixed = newStore()
100
+ const good = { id: '9-1', at: 9, kind: 'run', tone: 'success', title: 'ok', detail: null, run: null, unit: null, agent: null, workspace: null }
101
+ mixed.data.set(HISTORY_KEY, [good, 7, { ...good, kind: 'otro' }, null])
102
+ const b = setup(mixed)
103
+ assert.deepEqual((await b.list()).map((i) => i.id), ['9-1'])
104
+ assert.equal(b.logs.length, 1)
105
+ })
106
+
107
+ test('una ráfaga de 20 sucesos nunca tiene dos escrituras a la vez y deja guardado lo último', async () => {
108
+ const store = newStore()
109
+ store.delay = true
110
+ const s = setup(store)
111
+ for (let at = 1; at <= 20; at += 1) s.ctx.emit('action', action(`m${at}`, at))
112
+ await new Promise((resolve) => setTimeout(resolve, 100))
113
+ assert.equal(store.peak, 1)
114
+ assert.ok(store.sets <= 2, `escrituras: ${store.sets}`)
115
+ assert.equal((store.data.get(HISTORY_KEY) as HistoryEntry[])[0]?.title, 'm20')
116
+ assert.equal(s.posts.length, 20)
117
+ })
118
+
119
+ test('un fallo de escritura va al log y no pierde lo que hay en memoria', async () => {
120
+ const store = newStore()
121
+ store.fail = true
122
+ const s = setup(store)
123
+ s.ctx.emit('action', action('uno', 1))
124
+ await settle()
125
+ assert.ok(s.logs.some((l) => l.includes('disco lleno')))
126
+ assert.equal((await s.list()).length, 1)
127
+ store.fail = false
128
+ s.ctx.emit('action', action('dos', 2))
129
+ await settle()
130
+ assert.equal((store.data.get(HISTORY_KEY) as HistoryEntry[]).length, 2)
131
+ })
132
+
133
+ test('limpia y acota los textos', async () => {
134
+ const s = setup(newStore())
135
+ s.ctx.emit('action', { ...action(`a\u0007\n${'b'.repeat(300)}`, 1), detail: 'x'.repeat(500) })
136
+ const [entry] = await s.list()
137
+ assert.ok(entry && entry.title.length <= 120 && !/[\u0007\n]/.test(entry.title))
138
+ assert.ok(entry && (entry.detail?.length ?? 0) <= 200)
139
+ })
140
+
141
+ test('history.clear vacía, guarda y avisa', async () => {
142
+ const store = newStore()
143
+ const s = setup(store)
144
+ s.ctx.emit('action', action('uno', 1))
145
+ assert.equal((await s.call('history.clear')).message, 'Historial vaciado.')
146
+ assert.deepEqual(store.data.get(HISTORY_KEY), [])
147
+ assert.deepEqual(await s.list(), [])
148
+ assert.deepEqual(s.posts.at(-1), [])
149
+ })
@@ -0,0 +1,181 @@
1
+ // Pestaña Historial: despachos, bloqueos, finales de unidad, runs terminados y lo que la persona
2
+ // hace desde el panel, guardados en el almacén del plugin (`history.v1`, lo más reciente primero).
3
+ import type { JsonValue } from 'orca/worker'
4
+ import { cleanLabel, type TrackedAgent, type UnitInfo } from '../kit.ts'
5
+ import type { HistoryEntry, HistoryKind, Tone } from '../protocol.ts'
6
+ import type { KitContext, KitEvents } from './context.ts'
7
+
8
+ export const HISTORY_KEY = 'history.v1'
9
+ export const HISTORY_MAX = 200
10
+ const TITLE_MAX = 120
11
+ const DETAIL_MAX = 200
12
+
13
+ const KINDS: readonly HistoryKind[] = ['dispatch', 'state', 'outcome', 'run', 'plan', 'orchestrate', 'reply', 'model', 'autonomy']
14
+ const TONES: readonly Tone[] = ['neutral', 'accent', 'success', 'warning', 'danger']
15
+
16
+ const text = (value: unknown, max: number): string | null => (typeof value === 'string' ? cleanLabel(value, max) : null)
17
+
18
+ /** Una entrada guardada, o `null` si no tiene la forma de una: lo dañado no llega al panel. */
19
+ function parseEntry(value: unknown): HistoryEntry | null {
20
+ if (typeof value !== 'object' || value === null) return null
21
+ const raw = value as Record<string, unknown>
22
+ const { id, at, kind, tone } = raw
23
+ if (typeof id !== 'string' || id === '' || id.length > 60) return null
24
+ if (typeof at !== 'number' || !Number.isFinite(at)) return null
25
+ if (!KINDS.includes(kind as HistoryKind) || !TONES.includes(tone as Tone)) return null
26
+ const title = text(raw.title, TITLE_MAX)
27
+ if (title === null) return null
28
+ return {
29
+ id,
30
+ at,
31
+ kind: kind as HistoryKind,
32
+ tone: tone as Tone,
33
+ title,
34
+ detail: text(raw.detail, DETAIL_MAX),
35
+ run: text(raw.run, 60),
36
+ unit: text(raw.unit, 60),
37
+ agent: text(raw.agent, 40),
38
+ workspace: text(raw.workspace, 60)
39
+ }
40
+ }
41
+
42
+ /** «U1 · Proteo — Avisos» a partir de lo que dice el despacho. */
43
+ function unitLabel(info: UnitInfo): string {
44
+ const head = [info.unit, info.role].filter(Boolean).join(' · ')
45
+ return info.title ? `${head} — ${info.title}` : head
46
+ }
47
+
48
+ export function registerHistory(ctx: KitContext): void {
49
+ let items: HistoryEntry[] = []
50
+ let counter = 0
51
+ let dirty = false
52
+ let draining: Promise<void> | null = null
53
+
54
+ const loaded = (async () => {
55
+ try {
56
+ const stored = await ctx.storage.get(HISTORY_KEY)
57
+ if (stored === null) return
58
+ if (!Array.isArray(stored)) {
59
+ ctx.log('historial: «history.v1» no es una lista; se descarta')
60
+ return
61
+ }
62
+ const valid = stored.flatMap((value) => parseEntry(value) ?? [])
63
+ if (valid.length < stored.length) ctx.log(`historial: ${stored.length - valid.length} entradas dañadas descartadas`)
64
+ // Lo apuntado mientras se leía es más reciente que lo guardado.
65
+ items = [...items, ...valid].slice(0, HISTORY_MAX)
66
+ } catch (error) {
67
+ ctx.log(`historial: no pude leer «${HISTORY_KEY}»: ${error instanceof Error ? error.message : String(error)}`)
68
+ }
69
+ })()
70
+
71
+ // Una escritura en curso y, como mucho, una más detrás que recoge todo lo apuntado entretanto.
72
+ const drain = async (): Promise<void> => {
73
+ while (dirty) {
74
+ dirty = false
75
+ try {
76
+ await ctx.storage.set(HISTORY_KEY, items as unknown as JsonValue)
77
+ } catch (error) {
78
+ ctx.log(`historial: no pude guardar: ${error instanceof Error ? error.message : String(error)}`)
79
+ }
80
+ }
81
+ draining = null
82
+ }
83
+ const save = (): Promise<void> => {
84
+ dirty = true
85
+ draining ??= drain()
86
+ return draining
87
+ }
88
+
89
+ const changed = () => ctx.panels.post('history.changed', { items })
90
+
91
+ const record = (
92
+ at: number,
93
+ entry: Pick<HistoryEntry, 'kind' | 'tone'> & {
94
+ title: string
95
+ detail?: string | null
96
+ run?: string | null
97
+ unit?: string | null
98
+ agent?: string | null
99
+ workspaceId?: string | null
100
+ }
101
+ ): void => {
102
+ const title = cleanLabel(entry.title, TITLE_MAX)
103
+ if (title === null) return
104
+ const next: HistoryEntry = {
105
+ id: `${at}-${(counter += 1)}`,
106
+ at,
107
+ kind: entry.kind,
108
+ tone: entry.tone,
109
+ title,
110
+ detail: entry.detail ? cleanLabel(entry.detail, DETAIL_MAX) : null,
111
+ run: entry.run ? cleanLabel(entry.run, 60) : null,
112
+ unit: entry.unit ? cleanLabel(entry.unit, 60) : null,
113
+ agent: entry.agent ? cleanLabel(entry.agent, 40) : null,
114
+ workspace: ctx.workspaceName(entry.workspaceId ?? null)
115
+ }
116
+ items = [next, ...items].slice(0, HISTORY_MAX)
117
+ changed()
118
+ void loaded.then(save)
119
+ }
120
+
121
+ ctx.on('dispatch', ({ key, terminalId, unit, agent, at }) =>
122
+ record(at, {
123
+ kind: 'dispatch',
124
+ tone: 'accent',
125
+ title: `${unitLabel(unit)} despachado`,
126
+ run: unit.run,
127
+ unit: unit.unit,
128
+ agent,
129
+ workspaceId: ctx.terminals.get(terminalId)?.workspaceId ?? ctx.agents.get(key)?.workspaceId ?? null
130
+ })
131
+ )
132
+
133
+ ctx.on('agent', ({ previous, agent, outcome, at }: KitEvents['agent']) => {
134
+ const tracked: TrackedAgent | undefined = agent ?? previous
135
+ const unit = tracked?.unit
136
+ if (!tracked || !unit) return
137
+ const base = { run: unit.run, unit: unit.unit, agent: tracked.agent ?? null, workspaceId: tracked.workspaceId }
138
+ if (agent === null) {
139
+ const tone: Tone = outcome === 'success' ? 'success' : outcome === 'failure' ? 'danger' : 'neutral'
140
+ record(at, {
141
+ ...base,
142
+ kind: 'outcome',
143
+ tone,
144
+ title: `${unitLabel(unit)} ${outcome === 'failure' ? 'falló' : 'terminó'}`,
145
+ detail: outcome
146
+ })
147
+ } else if (agent.state === 'blocked' && previous?.state !== 'blocked') {
148
+ record(at, { ...base, kind: 'state', tone: 'warning', title: `${unitLabel(unit)} bloqueado`, detail: agent.title })
149
+ }
150
+ })
151
+
152
+ ctx.on('runDone', ({ run, notice, at }) =>
153
+ record(at, { kind: 'run', tone: 'success', title: notice.title, detail: notice.body, run })
154
+ )
155
+
156
+ ctx.on('action', ({ kind, title, detail, agentKey, run, at }) => {
157
+ const tracked = agentKey === null ? undefined : ctx.agents.get(agentKey)
158
+ record(at, {
159
+ kind,
160
+ tone: 'accent',
161
+ title,
162
+ detail,
163
+ run: run ?? tracked?.unit?.run ?? null,
164
+ unit: tracked?.unit?.unit ?? null,
165
+ agent: tracked?.agent ?? null,
166
+ workspaceId: tracked?.workspaceId ?? null
167
+ })
168
+ })
169
+
170
+ ctx.panels.handle('history.list', async () => {
171
+ await loaded
172
+ return { items }
173
+ })
174
+ ctx.panels.handle('history.clear', async () => {
175
+ await loaded
176
+ items = []
177
+ changed()
178
+ await save()
179
+ return { message: 'Historial vaciado.' }
180
+ })
181
+ }