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.
- package/AI_INSTALL.md +4 -3
- package/CHANGELOG.md +70 -1
- package/GUIA.html +11 -9
- package/README.md +23 -23
- package/VERSION +1 -1
- package/bin/backup.js +44 -0
- package/bin/fetch.js +243 -0
- package/bin/hooks.js +187 -0
- package/bin/omk.js +134 -51
- package/bin/run/cleanup.js +402 -0
- package/bin/run/git.js +641 -0
- package/bin/run/glob.js +193 -0
- package/bin/run/ledger.js +243 -0
- package/bin/run/plan.js +328 -0
- package/bin/run/units.js +101 -0
- package/bin/run/util.js +116 -0
- package/bin/run.js +224 -0
- package/bin/setup.js +81 -8
- package/bin/sync.js +222 -0
- package/bin/team.js +353 -0
- package/bin/ui.js +8 -4
- package/bin/update.js +169 -0
- package/core/AGENTS.md +7 -7
- package/docs/EJECUTABLE.md +5 -4
- package/docs/MANUAL.md +16 -3
- package/docs/ORQUESTADOR.md +59 -1
- package/docs/PLUGIN-ORCA.md +131 -24
- package/hooks/orca-gate.cjs +402 -0
- package/install.sh +26 -13
- package/orca-plugin/README.md +7 -1
- package/orca-plugin/assets/logos/README.md +10 -0
- package/orca-plugin/assets/logos/agent.png +0 -0
- package/orca-plugin/assets/logos/aider.png +0 -0
- package/orca-plugin/assets/logos/amp.png +0 -0
- package/orca-plugin/assets/logos/antigravity.png +0 -0
- package/orca-plugin/assets/logos/claude.png +0 -0
- package/orca-plugin/assets/logos/cline.png +0 -0
- package/orca-plugin/assets/logos/codex.png +0 -0
- package/orca-plugin/assets/logos/copilot.png +0 -0
- package/orca-plugin/assets/logos/cursor.png +0 -0
- package/orca-plugin/assets/logos/devin.png +0 -0
- package/orca-plugin/assets/logos/droid.png +0 -0
- package/orca-plugin/assets/logos/gemini.png +0 -0
- package/orca-plugin/assets/logos/goose.png +0 -0
- package/orca-plugin/assets/logos/grok.png +0 -0
- package/orca-plugin/assets/logos/kimi.png +0 -0
- package/orca-plugin/assets/logos/kiro.png +0 -0
- package/orca-plugin/assets/logos/opencode.png +0 -0
- package/orca-plugin/assets/logos/qwen-code.png +0 -0
- package/orca-plugin/orca-plugin.json +25 -7
- package/orca-plugin/src/icons.test.ts +14 -0
- package/orca-plugin/src/icons.ts +30 -0
- package/orca-plugin/src/kit.test.ts +491 -22
- package/orca-plugin/src/kit.ts +687 -37
- package/orca-plugin/src/models.test.ts +28 -0
- package/orca-plugin/src/models.ts +29 -0
- package/orca-plugin/src/node.d.ts +40 -0
- package/orca-plugin/src/panel-state.ts +36 -0
- package/orca-plugin/src/panel.check.ts +71 -0
- package/orca-plugin/src/panel.test.tsx +296 -33
- package/orca-plugin/src/panel.tsx +501 -81
- package/orca-plugin/src/plan-card.test.ts +99 -0
- package/orca-plugin/src/plan-card.ts +107 -0
- package/orca-plugin/src/protocol.ts +205 -5
- package/orca-plugin/src/tabs/autonomy.tsx +72 -0
- package/orca-plugin/src/tabs/history.test.tsx +79 -0
- package/orca-plugin/src/tabs/history.tsx +119 -0
- package/orca-plugin/src/tabs/notices.test.tsx +184 -0
- package/orca-plugin/src/tabs/notices.tsx +274 -0
- package/orca-plugin/src/tabs/worktrees.test.tsx +131 -0
- package/orca-plugin/src/tabs/worktrees.tsx +138 -0
- package/orca-plugin/src/ui/action-card.tsx +112 -0
- package/orca-plugin/src/ui/agent-icon.tsx +13 -0
- package/orca-plugin/src/worker/actions.test.ts +288 -0
- package/orca-plugin/src/worker/actions.ts +292 -0
- package/orca-plugin/src/worker/context.test.ts +32 -0
- package/orca-plugin/src/worker/context.ts +95 -0
- package/orca-plugin/src/worker/history.test.ts +149 -0
- package/orca-plugin/src/worker/history.ts +181 -0
- package/orca-plugin/src/worker/notices.test.ts +356 -0
- package/orca-plugin/src/worker/notices.ts +288 -0
- package/orca-plugin/src/worker/system.test.ts +58 -0
- package/orca-plugin/src/worker/system.ts +122 -0
- package/orca-plugin/src/worker/worktrees.test.ts +177 -0
- package/orca-plugin/src/worker/worktrees.ts +188 -0
- package/orca-plugin/src/worker.test.ts +285 -24
- package/orca-plugin/src/worker.ts +344 -64
- package/output-styles/csr-minimal.md +1 -0
- package/package.json +3 -3
- package/rules/50-done-gate.md +1 -1
- package/rules/95-multi-agent.md +13 -3
- package/skills/kit-init/SKILL.md +16 -4
- package/skills/orca/SKILL.md +28 -5
- package/skills/orca/references/adapters/artifact.md +2 -0
- package/skills/orca/references/adapters/chat.md +2 -0
- package/skills/orca/references/adapters/native-plan.md +6 -0
- package/skills/orca/references/adapters/plan-file.md +2 -0
- package/skills/orca/references/engine-manual.md +7 -5
- package/skills/orca/references/engine-orca.md +1 -0
- package/skills/orca/references/engine-subagents.md +4 -4
- package/skills/orca/references/integrate.md +14 -2
- package/skills/orca/references/ledger.md +1 -1
- package/skills/orca/references/olimpo.md +2 -1
- package/skills/orca/references/plan-card.md +45 -0
- package/skills/orca/references/plan.md +2 -1
- package/skills/orca/references/units.md +1 -1
- package/skills/orca/references/worker-contract.md +2 -2
- package/templates/AGENTS.md +2 -2
- package/templates/CLAUDE.md +1 -1
- package/templates/claude-settings.json +25 -0
|
@@ -0,0 +1,95 @@
|
|
|
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 { Tone } from '../protocol.ts'
|
|
7
|
+
import type { KitSystem } from './system.ts'
|
|
8
|
+
|
|
9
|
+
/** Lo que los hooks enseñan de un terminal antes, o además, de sus cambios de estado. */
|
|
10
|
+
export type TerminalInfo = { agent?: string; unit?: UnitInfo; workspaceId?: string }
|
|
11
|
+
|
|
12
|
+
/** Los sucesos que el núcleo reparte; `at` es ms desde epoch. */
|
|
13
|
+
export type KitEvents = {
|
|
14
|
+
/** Un agente cambió de estado. `agent` es `null` cuando terminó (`done`) y deja de seguirse. */
|
|
15
|
+
agent: {
|
|
16
|
+
key: string
|
|
17
|
+
previous: TrackedAgent | undefined
|
|
18
|
+
agent: TrackedAgent | null
|
|
19
|
+
/** El último estado que contó Orca, también cuando `agent` es `null`. */
|
|
20
|
+
state: TrackedAgent['state']
|
|
21
|
+
/** Cómo acabó el turno del agente principal, si Orca lo dice. */
|
|
22
|
+
outcome: string | null
|
|
23
|
+
at: number
|
|
24
|
+
}
|
|
25
|
+
/** Un despacho de la skill `orca` llegó al terminal de un agente. */
|
|
26
|
+
dispatch: { key: string; terminalId: string; unit: UnitInfo; agent: string | null; at: number }
|
|
27
|
+
/** Orca va a arrancar un agente en un terminal: `command` es la orden tal cual. */
|
|
28
|
+
launch: { terminalId: string; agent: string; workspaceId: string | null; command: string; at: number }
|
|
29
|
+
/** Un agente terminó una llamada a una herramienta (hook `agent.tool.after`; hoy, Claude Code). */
|
|
30
|
+
tool: { agent: string; workspaceId: string | null; terminalId: string | null; tool: string; input: JsonValue; at: number }
|
|
31
|
+
/** Orca quitó un workspace: lo que se recuerde de él sobra. */
|
|
32
|
+
workspaceRemoved: { workspaceId: string; at: number }
|
|
33
|
+
/** Terminaron todas las unidades lanzadas de un run del kit (el aviso de `trackRun`). */
|
|
34
|
+
runDone: { run: string; notice: Notice; at: number }
|
|
35
|
+
/** La persona hizo algo desde el panel que conviene dejar en el historial. */
|
|
36
|
+
action: {
|
|
37
|
+
kind: 'kit' | 'orchestrate' | 'reply' | 'model' | 'autonomy' | 'plan'
|
|
38
|
+
/** El color de su entrada en el historial; sin él, el de las acciones (`accent`). */
|
|
39
|
+
tone?: Tone
|
|
40
|
+
title: string
|
|
41
|
+
detail: string | null
|
|
42
|
+
/** Clave del agente afectado (`t:<terminal>`), si lo hay. */
|
|
43
|
+
agentKey: string | null
|
|
44
|
+
run: string | null
|
|
45
|
+
at: number
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type KitEventName = keyof KitEvents
|
|
50
|
+
|
|
51
|
+
export type KitContext = {
|
|
52
|
+
host: OrcaWorkerApi['host']
|
|
53
|
+
panels: OrcaWorkerApi['panels']
|
|
54
|
+
storage: OrcaWorkerApi['storage']
|
|
55
|
+
/** Disco y CLI de Orca, para los agentes que corren como chat (src/worker/system.ts). */
|
|
56
|
+
system: KitSystem
|
|
57
|
+
log(message: string): void
|
|
58
|
+
/** Notificación de escritorio, si la persona no desactivó «Avisos de agentes». */
|
|
59
|
+
notify(title: string, body: string): void
|
|
60
|
+
/** Los agentes que sigue el núcleo, por clave (`t:<terminal>` o `p:<panel>`). Solo lectura. */
|
|
61
|
+
agents: ReadonlyMap<string, TrackedAgent>
|
|
62
|
+
/** Lo que se sabe de cada terminal por los hooks. Solo lectura. */
|
|
63
|
+
terminals: ReadonlyMap<string, TerminalInfo>
|
|
64
|
+
workspaces(): WorkspaceIndex
|
|
65
|
+
/** El nombre de un workspace; si no se conoce, pide la lista una vez y devuelve `null`. */
|
|
66
|
+
workspaceName(workspaceId: string | null): string | null
|
|
67
|
+
/** Vuelve a pedir `workspace.list` (una sola petición a la vez). */
|
|
68
|
+
refreshWorkspaces(): Promise<void>
|
|
69
|
+
on<E extends KitEventName>(event: E, listener: (payload: KitEvents[E]) => void): void
|
|
70
|
+
emit<E extends KitEventName>(event: E, payload: KitEvents[E]): void
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type Listener = (payload: never) => void
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reparto de sucesos en orden de registro. Un oyente que falla no corta a los demás: su error
|
|
77
|
+
* queda en el log del plugin con el suceso que lo causó.
|
|
78
|
+
*/
|
|
79
|
+
export function createBus(log: (message: string) => void): Pick<KitContext, 'on' | 'emit'> {
|
|
80
|
+
const listeners = new Map<KitEventName, Listener[]>()
|
|
81
|
+
return {
|
|
82
|
+
on(event, listener) {
|
|
83
|
+
listeners.set(event, [...(listeners.get(event) ?? []), listener as Listener])
|
|
84
|
+
},
|
|
85
|
+
emit(event, payload) {
|
|
86
|
+
for (const listener of listeners.get(event) ?? []) {
|
|
87
|
+
try {
|
|
88
|
+
;(listener as (value: typeof payload) => void)(payload)
|
|
89
|
+
} catch (error) {
|
|
90
|
+
log(`oyente de «${event}» falló: ${error instanceof Error ? error.message : String(error)}`)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -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[] = ['kit', '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, tone, title, detail, agentKey, run, at }) => {
|
|
157
|
+
const tracked = agentKey === null ? undefined : ctx.agents.get(agentKey)
|
|
158
|
+
record(at, {
|
|
159
|
+
kind,
|
|
160
|
+
tone: 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
|
+
}
|