@johpaz/hive-sdk 0.0.14 → 0.0.15

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 (199) hide show
  1. package/.github/CODEOWNERS +9 -0
  2. package/.github/workflows/publish.yml +89 -0
  3. package/.github/workflows/version-bump.yml +102 -0
  4. package/CHANGELOG.md +38 -0
  5. package/README.md +158 -0
  6. package/bun.lock +543 -0
  7. package/bunfig.toml +7 -0
  8. package/docs/API-AGENTS.md +316 -0
  9. package/docs/API-CONTEXT-COMPILER.md +252 -0
  10. package/docs/API-DAG-SCHEDULER.md +273 -0
  11. package/docs/API-TOOLS-SKILLS-CHANNELS.md +293 -0
  12. package/docs/API-WORKERS-EVENTS.md +152 -0
  13. package/docs/INDEX.md +141 -0
  14. package/docs/README.md +68 -0
  15. package/package.json +54 -105
  16. package/packages/cli/package.json +17 -0
  17. package/packages/cli/src/commands/init.ts +56 -0
  18. package/packages/cli/src/commands/run.ts +45 -0
  19. package/packages/cli/src/commands/test.ts +42 -0
  20. package/packages/cli/src/commands/trace.ts +55 -0
  21. package/packages/cli/src/index.ts +43 -0
  22. package/packages/core/package.json +58 -0
  23. package/packages/core/src/ace/Curator.ts +158 -0
  24. package/packages/core/src/ace/Reflector.ts +200 -0
  25. package/packages/core/src/ace/Tracer.ts +100 -0
  26. package/packages/core/src/ace/index.ts +4 -0
  27. package/packages/core/src/agent/AgentRunner.ts +699 -0
  28. package/packages/core/src/agent/Compaction.ts +221 -0
  29. package/packages/core/src/agent/ContextCompiler.ts +567 -0
  30. package/packages/core/src/agent/ContextGuard.ts +91 -0
  31. package/packages/core/src/agent/ConversationStore.ts +244 -0
  32. package/packages/core/src/agent/Hooks.ts +166 -0
  33. package/packages/core/src/agent/NativeTools.ts +31 -0
  34. package/packages/core/src/agent/PromptBuilder.ts +169 -0
  35. package/packages/core/src/agent/Service.ts +267 -0
  36. package/packages/core/src/agent/StuckLoop.ts +133 -0
  37. package/packages/core/src/agent/index.ts +12 -0
  38. package/packages/core/src/agent/providers/LLMClient.ts +149 -0
  39. package/packages/core/src/agent/providers/anthropic.ts +212 -0
  40. package/packages/core/src/agent/providers/gemini.ts +215 -0
  41. package/packages/core/src/agent/providers/index.ts +199 -0
  42. package/packages/core/src/agent/providers/interface.ts +195 -0
  43. package/packages/core/src/agent/providers/ollama.ts +175 -0
  44. package/packages/core/src/agent/providers/openai-compat.ts +231 -0
  45. package/packages/core/src/agent/providers.ts +1 -0
  46. package/packages/core/src/agent/selectors/PlaybookSelector.ts +147 -0
  47. package/packages/core/src/agent/selectors/SkillSelector.ts +478 -0
  48. package/packages/core/src/agent/selectors/ToolSelector.ts +577 -0
  49. package/packages/core/src/agent/selectors/index.ts +6 -0
  50. package/packages/core/src/api/createAgent.test.ts +48 -0
  51. package/packages/core/src/api/createAgent.ts +122 -0
  52. package/packages/core/src/api/index.ts +2 -0
  53. package/packages/core/src/canvas/CanvasManager.ts +390 -0
  54. package/packages/core/src/canvas/a2ui-tools.ts +255 -0
  55. package/packages/core/src/canvas/canvas-tools.ts +448 -0
  56. package/packages/core/src/canvas/emitter.ts +149 -0
  57. package/packages/core/src/canvas/index.ts +6 -0
  58. package/packages/core/src/config/index.ts +2 -0
  59. package/packages/core/src/config/loader.ts +554 -0
  60. package/packages/core/src/ethics/EthicsGuard.test.ts +54 -0
  61. package/packages/core/src/ethics/EthicsGuard.ts +66 -0
  62. package/packages/core/src/ethics/index.ts +2 -0
  63. package/packages/core/src/gateway/channel-notify.test.ts +14 -0
  64. package/packages/core/src/gateway/channel-notify.ts +12 -0
  65. package/packages/core/src/gateway/index.ts +1 -0
  66. package/packages/core/src/index.ts +37 -0
  67. package/packages/core/src/mcp/MCPClient.ts +439 -0
  68. package/packages/core/src/mcp/MCPToolAdapter.ts +176 -0
  69. package/packages/core/src/mcp/config.ts +13 -0
  70. package/packages/core/src/mcp/hot-reload.ts +147 -0
  71. package/packages/core/src/mcp/index.ts +11 -0
  72. package/packages/core/src/mcp/logger.ts +42 -0
  73. package/packages/core/src/mcp/singleton.ts +21 -0
  74. package/packages/core/src/mcp/transports/index.ts +67 -0
  75. package/packages/core/src/mcp/transports/sse.ts +241 -0
  76. package/packages/core/src/mcp/transports/websocket.ts +159 -0
  77. package/packages/core/src/memory/Scratchpad.test.ts +47 -0
  78. package/packages/core/src/memory/Scratchpad.ts +37 -0
  79. package/packages/core/src/memory/Storage.ts +6 -0
  80. package/packages/core/src/memory/index.ts +2 -0
  81. package/packages/core/src/multimodal/VisionService.ts +293 -0
  82. package/packages/core/src/multimodal/index.ts +2 -0
  83. package/packages/core/src/multimodal/types.ts +28 -0
  84. package/packages/core/src/security/Pairing.ts +250 -0
  85. package/packages/core/src/security/RateLimit.ts +270 -0
  86. package/packages/core/src/security/index.ts +4 -0
  87. package/packages/core/src/skills/SkillLoader.ts +388 -0
  88. package/packages/core/src/skills/bundled-data.generated.ts +3332 -0
  89. package/packages/core/src/skills/defineSkill.ts +18 -0
  90. package/packages/core/src/skills/index.ts +4 -0
  91. package/packages/core/src/state/index.ts +2 -0
  92. package/packages/core/src/state/store.ts +312 -0
  93. package/packages/core/src/storage/SQLiteStorage.ts +407 -0
  94. package/packages/core/src/storage/crypto.ts +101 -0
  95. package/packages/core/src/storage/index.ts +10 -0
  96. package/packages/core/src/storage/onboarding.ts +1603 -0
  97. package/packages/core/src/storage/schema.ts +689 -0
  98. package/packages/core/src/storage/seed.ts +740 -0
  99. package/packages/core/src/storage/usage.ts +374 -0
  100. package/packages/core/src/swarm/AgentBus.ts +460 -0
  101. package/packages/core/src/swarm/AgentExecutor.ts +53 -0
  102. package/packages/core/src/swarm/Coordinator.ts +251 -0
  103. package/packages/core/src/swarm/EventBridge.ts +122 -0
  104. package/packages/core/src/swarm/EventBus.ts +169 -0
  105. package/packages/core/src/swarm/TaskGraph.ts +192 -0
  106. package/packages/core/src/swarm/TaskNode.ts +97 -0
  107. package/packages/core/src/swarm/TaskResult.ts +22 -0
  108. package/packages/core/src/swarm/WorkerPool.ts +236 -0
  109. package/packages/core/src/swarm/errors.ts +37 -0
  110. package/packages/core/src/swarm/index.ts +30 -0
  111. package/packages/core/src/swarm/presets/HiveLearnPreset.ts +99 -0
  112. package/packages/core/src/swarm/presets/ResearchPreset.ts +97 -0
  113. package/packages/core/src/swarm/presets/index.ts +4 -0
  114. package/packages/core/src/swarm/strategies/ParallelStrategy.ts +21 -0
  115. package/packages/core/src/swarm/strategies/PriorityStrategy.ts +46 -0
  116. package/packages/core/src/swarm/strategies/index.ts +3 -0
  117. package/packages/core/src/swarm/types.ts +164 -0
  118. package/packages/core/src/tools/ToolExecutor.ts +58 -0
  119. package/packages/core/src/tools/ToolRegistry.test.ts +98 -0
  120. package/packages/core/src/tools/ToolRegistry.ts +61 -0
  121. package/packages/core/src/tools/agents/get-available-models.ts +118 -0
  122. package/packages/core/src/tools/agents/index.ts +715 -0
  123. package/packages/core/src/tools/bridge-events.ts +26 -0
  124. package/packages/core/src/tools/canvas/index.ts +375 -0
  125. package/packages/core/src/tools/cli/index.ts +142 -0
  126. package/packages/core/src/tools/codebridge/index.ts +342 -0
  127. package/packages/core/src/tools/core/index.ts +476 -0
  128. package/packages/core/src/tools/cron/index.ts +626 -0
  129. package/packages/core/src/tools/filesystem/fs-delete.ts +78 -0
  130. package/packages/core/src/tools/filesystem/fs-edit.ts +106 -0
  131. package/packages/core/src/tools/filesystem/fs-exists.ts +63 -0
  132. package/packages/core/src/tools/filesystem/fs-glob.ts +108 -0
  133. package/packages/core/src/tools/filesystem/fs-list.ts +129 -0
  134. package/packages/core/src/tools/filesystem/fs-read.ts +72 -0
  135. package/packages/core/src/tools/filesystem/fs-write.ts +67 -0
  136. package/packages/core/src/tools/filesystem/index.ts +34 -0
  137. package/packages/core/src/tools/filesystem/workspace-guard.ts +62 -0
  138. package/packages/core/src/tools/index.ts +231 -0
  139. package/packages/core/src/tools/meeting/index.ts +363 -0
  140. package/packages/core/src/tools/office/index.ts +47 -0
  141. package/packages/core/src/tools/office/office-escribir-docx.ts +192 -0
  142. package/packages/core/src/tools/office/office-escribir-pdf.ts +172 -0
  143. package/packages/core/src/tools/office/office-escribir-pptx.ts +174 -0
  144. package/packages/core/src/tools/office/office-escribir-xlsx.ts +116 -0
  145. package/packages/core/src/tools/office/office-leer-docx.ts +93 -0
  146. package/packages/core/src/tools/office/office-leer-pdf.ts +114 -0
  147. package/packages/core/src/tools/office/office-leer-pptx.ts +136 -0
  148. package/packages/core/src/tools/office/office-leer-xlsx.ts +124 -0
  149. package/packages/core/src/tools/projects/index.ts +37 -0
  150. package/packages/core/src/tools/projects/project-create.ts +94 -0
  151. package/packages/core/src/tools/projects/project-done.ts +66 -0
  152. package/packages/core/src/tools/projects/project-fail.ts +66 -0
  153. package/packages/core/src/tools/projects/project-list.ts +96 -0
  154. package/packages/core/src/tools/projects/project-update.ts +72 -0
  155. package/packages/core/src/tools/projects/task-create.ts +68 -0
  156. package/packages/core/src/tools/projects/task-evaluate.ts +93 -0
  157. package/packages/core/src/tools/projects/task-update.ts +93 -0
  158. package/packages/core/src/tools/types.ts +39 -0
  159. package/packages/core/src/tools/voice/index.ts +104 -0
  160. package/packages/core/src/tools/web/browser-click.ts +78 -0
  161. package/packages/core/src/tools/web/browser-extract.ts +139 -0
  162. package/packages/core/src/tools/web/browser-navigate.ts +106 -0
  163. package/packages/core/src/tools/web/browser-screenshot.ts +87 -0
  164. package/packages/core/src/tools/web/browser-script.ts +88 -0
  165. package/packages/core/src/tools/web/browser-service.ts +554 -0
  166. package/packages/core/src/tools/web/browser-type.ts +101 -0
  167. package/packages/core/src/tools/web/browser-wait.ts +136 -0
  168. package/packages/core/src/tools/web/index.ts +41 -0
  169. package/packages/core/src/tools/web/web-fetch.ts +78 -0
  170. package/packages/core/src/tools/web/web-search.ts +123 -0
  171. package/packages/core/src/utils/benchmark.ts +80 -0
  172. package/packages/core/src/utils/crypto.ts +73 -0
  173. package/packages/core/src/utils/date.ts +42 -0
  174. package/packages/core/src/utils/index.ts +10 -0
  175. package/packages/core/src/utils/logger.ts +389 -0
  176. package/packages/core/src/utils/retry.ts +70 -0
  177. package/packages/core/src/utils/toon.ts +253 -0
  178. package/packages/core/src/voice/index.ts +656 -0
  179. package/test/setup-db.ts +216 -0
  180. package/tsconfig.json +39 -0
  181. package/src/agents.ts +0 -1
  182. package/src/canvas.ts +0 -1
  183. package/src/channels.ts +0 -1
  184. package/src/config.ts +0 -1
  185. package/src/events.ts +0 -1
  186. package/src/gateway.ts +0 -1
  187. package/src/index.ts +0 -304
  188. package/src/mcp.ts +0 -1
  189. package/src/multimodal.ts +0 -1
  190. package/src/scheduler.ts +0 -1
  191. package/src/security.ts +0 -1
  192. package/src/skills.ts +0 -1
  193. package/src/state.ts +0 -1
  194. package/src/storage.ts +0 -1
  195. package/src/tools.ts +0 -1
  196. package/src/tts.ts +0 -1
  197. package/src/types.ts +0 -82
  198. package/src/utils.ts +0 -1
  199. package/src/voice.ts +0 -1
@@ -0,0 +1,273 @@
1
+ # API Reference — DAG Scheduler
2
+
3
+ ## Índice
4
+
5
+ 1. [Arquitectura](#arquitectura)
6
+ 2. [TaskNode](#tasknode)
7
+ 3. [TaskGraph](#taskgraph)
8
+ 4. [DAGScheduler](#dagscheduler)
9
+ 5. [Estrategias](#estrategias)
10
+ 6. [Presets](#presets)
11
+ 7. [EventBridge](#eventbridge)
12
+ 8. [Errores Comunes](#errores-comunes)
13
+
14
+ ---
15
+
16
+ ## Arquitectura
17
+
18
+ El DAG Scheduler orquesta la ejecución de grafos acíclicos dirigidos (DAG) de tareas.
19
+
20
+ ```
21
+ TaskNode → TaskGraph → DAGScheduler
22
+
23
+ ┌──────────────┼──────────────┐
24
+ ▼ ▼ ▼
25
+ Worker 1 Worker 2 Worker 3
26
+ (agente) (agente) (agente)
27
+ ```
28
+
29
+ ---
30
+
31
+ ## TaskNode
32
+
33
+ Representa una tarea individual en el grafo.
34
+
35
+ ### TaskNodeConfig
36
+
37
+ ```typescript
38
+ import { TaskNode } from "@hive/core";
39
+
40
+ interface TaskNodeConfig {
41
+ id: string;
42
+ agentId: string;
43
+ name?: string;
44
+ taskDescription: string;
45
+ deps: string[];
46
+ priority?: number;
47
+ timeout?: number;
48
+ maxRetries?: number;
49
+ }
50
+ ```
51
+
52
+ ### Estados
53
+
54
+ ```typescript
55
+ type NodeStatus = "PENDING" | "READY" | "RUNNING" | "COMPLETED" | "FAILED";
56
+ ```
57
+
58
+ ### Ejemplo
59
+
60
+ ```typescript
61
+ const node = new TaskNode({
62
+ id: "fetch-data",
63
+ agentId: "fetcher",
64
+ taskDescription: "Obtener datos de API",
65
+ deps: [],
66
+ });
67
+ node.markRunning();
68
+ // ... ejecutar ...
69
+ node.markCompleted("datos obtenidos");
70
+ ```
71
+
72
+ ---
73
+
74
+ ## TaskGraph
75
+
76
+ Grafo acíclico dirigido de tareas.
77
+
78
+ ```typescript
79
+ import { TaskGraph } from "@hive/core";
80
+
81
+ const graph = new TaskGraph([
82
+ { id: "a", agentId: "worker", taskDescription: "Tarea A", deps: [] },
83
+ { id: "b", agentId: "worker", taskDescription: "Tarea B", deps: ["a"] },
84
+ { id: "c", agentId: "worker", taskDescription: "Tarea C", deps: ["a"] },
85
+ { id: "d", agentId: "worker", taskDescription: "Tarea D", deps: ["b", "c"] },
86
+ ]);
87
+
88
+ // Nodos listos para ejecutar (sin deps pendientes)
89
+ const ready = graph.getReadyNodes();
90
+
91
+ // IDs de nodos completados
92
+ const completed = graph.getCompletedIds();
93
+
94
+ // Nodos recién listos tras completar uno
95
+ const newlyReady = graph.getNewlyReadyIds(new Set(["a"]));
96
+
97
+ // Resultados de dependencias
98
+ const depResults = graph.getDepResults("d");
99
+
100
+ // Progreso
101
+ const progress = graph.getProgress();
102
+ // { total: 4, completed: 1, running: 0, failed: 0, pending: 3, percentComplete: 25 }
103
+ ```
104
+
105
+ ---
106
+
107
+ ## DAGScheduler
108
+
109
+ Orquestador principal de la ejecución.
110
+
111
+ ```typescript
112
+ import { DAGScheduler, TaskGraph } from "@hive/core";
113
+
114
+ const graph = new TaskGraph([
115
+ { id: "fetch", agentId: "fetcher", taskDescription: "Fetch data", deps: [] },
116
+ { id: "process", agentId: "processor", taskDescription: "Process", deps: ["fetch"] },
117
+ { id: "save", agentId: "saver", taskDescription: "Save", deps: ["process"] },
118
+ ]);
119
+
120
+ const scheduler = new DAGScheduler({
121
+ maxConcurrentWorkers: 2,
122
+ });
123
+
124
+ const result = await scheduler.execute(graph);
125
+
126
+ console.log(`Success: ${result.success}`);
127
+ console.log(`Duration: ${result.totalDurationMs}ms`);
128
+ ```
129
+
130
+ ### DAGResult
131
+
132
+ ```typescript
133
+ interface DAGResult {
134
+ swarmId: string;
135
+ totalDurationMs: number;
136
+ completed: NodeSummary[];
137
+ failed: NodeSummary[];
138
+ success: boolean;
139
+ }
140
+
141
+ interface NodeSummary {
142
+ id: string;
143
+ name: string;
144
+ status: "COMPLETED" | "FAILED";
145
+ durationMs: number;
146
+ result?: string;
147
+ error?: string;
148
+ retries: number;
149
+ }
150
+ ```
151
+
152
+ ### Control
153
+
154
+ ```typescript
155
+ scheduler.abort(); // Abortar ejecución en curso
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Estrategias
161
+
162
+ ### ParallelStrategy (FIFO)
163
+
164
+ ```typescript
165
+ import { ParallelStrategy } from "@hive/core";
166
+
167
+ const strategy = new ParallelStrategy(); // Orden de llegada
168
+ ```
169
+
170
+ ### PriorityStrategy
171
+
172
+ ```typescript
173
+ import { PriorityStrategy } from "@hive/core";
174
+
175
+ const strategy = new PriorityStrategy(); // Por prioridad + path crítico
176
+ ```
177
+
178
+ ### Custom Strategy
179
+
180
+ ```typescript
181
+ import type { ExecutionStrategy } from "@hive/core";
182
+
183
+ const myStrategy: ExecutionStrategy = {
184
+ initialize(nodes) { /* precomputar */ },
185
+ pick(nodes) { return nodes[0]; }, // FIFO
186
+ };
187
+ ```
188
+
189
+ ---
190
+
191
+ ## Presets
192
+
193
+ Grafos predefinidos.
194
+
195
+ ### ResearchPreset
196
+
197
+ ```typescript
198
+ import { createResearchGraph } from "@hive/core/swarm/presets";
199
+
200
+ const graph = createResearchGraph({
201
+ agents: { researcher: "researcher-id", writer: "writer-id" },
202
+ query: "Análisis de mercado",
203
+ });
204
+ ```
205
+
206
+ ### HiveLearnPreset
207
+
208
+ ```typescript
209
+ import { createHiveLearnGraph } from "@hive/core/swarm/presets";
210
+
211
+ const graph = createHiveLearnGraph({
212
+ agents: { teacher: "teacher-id", student: "student-id" },
213
+ topic: "Machine Learning",
214
+ });
215
+ ```
216
+
217
+ ---
218
+
219
+ ## EventBridge
220
+
221
+ Puente de eventos entre el scheduler y el resto del sistema.
222
+
223
+ ```typescript
224
+ import { EventBridge } from "@hive/core";
225
+
226
+ const bridge = new EventBridge("swarm-123", "project-1", "coordinator-1");
227
+
228
+ bridge.onTaskCompleted = (node, progress) => {
229
+ console.log(`${node.name}: ${progress.percentComplete}%`);
230
+ };
231
+
232
+ bridge.onSwarmCompleted = (result) => {
233
+ console.log(`Swarm completed. Success: ${result.success}`);
234
+ };
235
+ ```
236
+
237
+ ---
238
+
239
+ ## IAgentExecutor
240
+
241
+ ```typescript
242
+ import type { IAgentExecutor } from "@hive/core";
243
+
244
+ const myExecutor: IAgentExecutor = {
245
+ async execute(node, depResults, threadId) {
246
+ const context = Object.values(depResults).join("\n");
247
+ return await myCustomFunction(node.taskDescription, context);
248
+ },
249
+ };
250
+
251
+ const result = await scheduler.execute(graph, { executor: myExecutor });
252
+ ```
253
+
254
+ ---
255
+
256
+ ## Errores Comunes
257
+
258
+ ### Cyclic dependency detected
259
+
260
+ ```typescript
261
+ // ❌ Ciclo: a→b→a
262
+ [{ id: "a", deps: ["b"] }, { id: "b", deps: ["a"] }];
263
+
264
+ // ✅ Sin ciclo
265
+ [{ id: "a", deps: [] }, { id: "b", deps: ["a"] }];
266
+ ```
267
+
268
+ ### Task timeout
269
+
270
+ ```typescript
271
+ // Configurar timeout razonable
272
+ const config = { id: "task", agentId: "w", taskDescription: "...", deps: [], timeout: 30000 };
273
+ ```
@@ -0,0 +1,293 @@
1
+ # API Reference — Tools, Skills, MCP y Storage
2
+
3
+ ## Índice
4
+
5
+ 1. [Tools](#tools)
6
+ 2. [Skills](#skills)
7
+ 3. [MCP](#mcp)
8
+ 4. [Canvas](#canvas)
9
+ 5. [Storage](#storage)
10
+ 6. [Config](#config)
11
+ 7. [Gateway (stub)](#gateway)
12
+
13
+ ---
14
+
15
+ ## Tools
16
+
17
+ ### defineTool
18
+
19
+ Función para definir herramientas que el agente puede invocar.
20
+
21
+ ```typescript
22
+ import { defineTool } from "@hive/core";
23
+
24
+ const tool = defineTool({
25
+ name: "saludar",
26
+ description: "Saluda a alguien por su nombre",
27
+ execute: async (args: { nombre: string }) => {
28
+ return { mensaje: `¡Hola ${args.nombre}!` };
29
+ },
30
+ });
31
+ ```
32
+
33
+ ### ToolRegistry
34
+
35
+ Registro central de herramientas.
36
+
37
+ ```typescript
38
+ import { ToolRegistry, defineTool } from "@hive/core";
39
+
40
+ const reg = new ToolRegistry();
41
+
42
+ // Registrar
43
+ reg.register(defineTool({ name: "t1", description: "...", execute: async () => ({}) }));
44
+
45
+ // Consultar
46
+ reg.has("t1"); // true
47
+ reg.get("t1"); // ToolDefinition
48
+ reg.list(); // ToolDefinition[]
49
+ reg.getByCategory("web"); // Filtrar por categoría
50
+ reg.getNames(); // ["t1"]
51
+ reg.size(); // 1
52
+
53
+ // Merge con otro registry
54
+ reg.merge(otherRegistry);
55
+
56
+ // Limpiar
57
+ reg.clear();
58
+ ```
59
+
60
+ ### ToolExecutor
61
+
62
+ Ejecutor de herramientas con validación Zod.
63
+
64
+ ```typescript
65
+ import { ToolRegistry, ToolExecutor, defineTool } from "@hive/core";
66
+
67
+ const reg = new ToolRegistry();
68
+ reg.register(defineTool({
69
+ name: "echo",
70
+ description: "Echo",
71
+ execute: async (args) => args,
72
+ }));
73
+
74
+ const exec = new ToolExecutor(reg);
75
+
76
+ // Ejecutar una tool
77
+ const result = await exec.execute("echo", { msg: "hola" });
78
+ // { toolName: "echo", args: { msg: "hola" }, result: { msg: "hola" }, durationMs: 1 }
79
+
80
+ // Ejecución batch
81
+ const results = await exec.executeBatch([
82
+ { name: "echo", args: { msg: "a" } },
83
+ { name: "echo", args: { msg: "b" } },
84
+ ]);
85
+ ```
86
+
87
+ ### Tool Selection (FTS5)
88
+
89
+ ```typescript
90
+ import { selectTools, CORE_TOOL_CATALOG } from "@hive/core";
91
+
92
+ // Selección automática por relevancia
93
+ const tools = selectTools("Buscar archivos en el proyecto");
94
+
95
+ // Filtrar por categoría
96
+ const webTools = tools.filter(t => t.category === "web");
97
+ ```
98
+
99
+ ---
100
+
101
+ ## Skills
102
+
103
+ ### defineSkill
104
+
105
+ ```typescript
106
+ import { defineSkill } from "@hive/core";
107
+
108
+ const skill = defineSkill({
109
+ name: "file-manager",
110
+ description: "Gestiona archivos y directorios",
111
+ steps: [
112
+ { action: "fs_list", instruction: "Listar archivos" },
113
+ { action: "fs_read", instruction: "Leer archivo" },
114
+ ],
115
+ tools: ["fs_list", "fs_read"],
116
+ triggers: ["archivo", "directorio", "listar"],
117
+ });
118
+ ```
119
+
120
+ ### SkillLoader
121
+
122
+ Carga skills desde archivos YAML o datos bundled.
123
+
124
+ ```typescript
125
+ import { SkillLoader } from "@hive/core";
126
+
127
+ const loader = new SkillLoader({
128
+ allowBundled: ["file-manager", "web-researcher"],
129
+ managedDir: "./skills",
130
+ });
131
+
132
+ const skills = loader.list();
133
+ const skill = loader.get("file-manager");
134
+ ```
135
+
136
+ ---
137
+
138
+ ## MCP
139
+
140
+ Model Context Protocol — herramientas externas via STDIO/SSE.
141
+
142
+ ### MCPClientManager
143
+
144
+ ```typescript
145
+ import { MCPClientManager } from "@hive/core";
146
+
147
+ // Configurar con servidores
148
+ const mcp = new MCPClientManager({
149
+ servers: {
150
+ "filesystem": {
151
+ transport: "stdio",
152
+ command: "npx",
153
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"],
154
+ enabled: true,
155
+ },
156
+ "weather-api": {
157
+ transport: "sse",
158
+ url: "https://api.weather.com/mcp",
159
+ enabled: true,
160
+ },
161
+ },
162
+ });
163
+
164
+ // Inicializar y conectar
165
+ await mcp.initialize();
166
+
167
+ // Obtener tools de servidores MCP
168
+ const tools = mcp.getTools("filesystem");
169
+
170
+ // Actualizar configuración
171
+ await mcp.updateConfig({ servers: { ... } });
172
+ ```
173
+
174
+ ### MCPToolAdapter
175
+
176
+ Sincroniza tools MCP con la base de datos FTS5.
177
+
178
+ ```typescript
179
+ import { syncMCPToolsToDB, syncMCPToolsToFTS, clearMCPToolsFromDB } from "@hive/core/mcp";
180
+
181
+ await syncMCPToolsToDB(mcpManager);
182
+ await syncMCPToolsToFTS();
183
+ ```
184
+
185
+ ### Transports
186
+
187
+ ```typescript
188
+ import { createTransport, SSETransport, WebSocketTransport } from "@hive/core/mcp/transports";
189
+
190
+ // STDIO
191
+ const transport = createTransport({
192
+ type: "stdio",
193
+ stdio: { command: "npx", args: ["-y", "server"], env: {} },
194
+ });
195
+
196
+ // SSE
197
+ const sse = new SSETransport({ url: "https://api.example.com/mcp" });
198
+
199
+ // WebSocket
200
+ const ws = new WebSocketTransport({ url: "wss://api.example.com/mcp" });
201
+ ```
202
+
203
+ ---
204
+
205
+ ## Canvas
206
+
207
+ Visualización en tiempo real del estado de agentes.
208
+
209
+ ```typescript
210
+ import { CanvasManager, canvasManager, emitCanvas } from "@hive/core/canvas";
211
+
212
+ // Singleton
213
+ canvasManager.subscribe("agent-1", (update) => {
214
+ console.log("Estado:", update.changes.status);
215
+ });
216
+
217
+ // Emitir eventos
218
+ emitCanvas("canvas:node_update", {
219
+ nodeId: "agent-1",
220
+ changes: { status: "running", currentTool: "web_search" },
221
+ });
222
+ ```
223
+
224
+ ### A2UI Tools
225
+
226
+ ```typescript
227
+ import { createA2UISurfaceTool, createA2UIUpdateComponentsTool } from "@hive/core/canvas";
228
+
229
+ // Crear tools A2UI para UI generada por agentes
230
+ const surfaceTool = createA2UISurfaceTool();
231
+ const updateTool = createA2UIUpdateComponentsTool();
232
+ ```
233
+
234
+ ---
235
+
236
+ ## Storage
237
+
238
+ Base de datos SQLite con FTS5.
239
+
240
+ ```typescript
241
+ import { initializeDatabase, getDb, dbService } from "@hive/core";
242
+
243
+ // Inicializar (crea tablas si no existen)
244
+ await initializeDatabase();
245
+
246
+ // Obtener instancia DB
247
+ const db = getDb();
248
+
249
+ // Queries
250
+ const results = db.query("SELECT * FROM agents WHERE id = ?").all(agentId);
251
+ const single = db.query("SELECT * FROM agents WHERE id = ?").get(agentId);
252
+
253
+ // Insert/Update
254
+ db.query("INSERT INTO agents (id, name) VALUES (?, ?)").run("a1", "Agent 1");
255
+
256
+ // Cerrar
257
+ dbService.close();
258
+ ```
259
+
260
+ ### Schemas FTS5
261
+
262
+ ```sql
263
+ -- 4 tablas virtuales FTS5 para búsqueda full-text
264
+ CREATE VIRTUAL TABLE playbook_fts USING fts5(rule, category, applicable_to);
265
+ CREATE VIRTUAL TABLE tools_fts USING fts5(tool_name, name, description, category);
266
+ CREATE VIRTUAL TABLE skills_fts USING fts5(id, name, description, category, tools, triggers, body);
267
+ CREATE VIRTUAL TABLE mcp_tools_fts USING fts5(id, name, description, category);
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Config
273
+
274
+ ```typescript
275
+ import { loadConfig, loadEnv, getHiveDir } from "@hive/core";
276
+
277
+ const config = await loadConfig();
278
+ // { HIVE_DATA_DIR: "./data", LOG_LEVEL: "info", ... }
279
+
280
+ const hiveDir = getHiveDir(); // ~/.hive o HIVE_DATA_DIR
281
+ ```
282
+
283
+ ---
284
+
285
+ ## Gateway (stub)
286
+
287
+ ```typescript
288
+ import { sendToUserChannel } from "@hive/core/gateway";
289
+
290
+ // Stub — logs al console, retorna { ok: true }
291
+ // Reemplazar cuando se integre con un sistema de notificaciones real
292
+ const result = await sendToUserChannel("cli:user-1", "user-1", "Hello!");
293
+ ```
@@ -0,0 +1,152 @@
1
+ # API Reference — Workers y Eventos
2
+
3
+ ## Índice
4
+
5
+ 1. [Workers](#workers)
6
+ 2. [AgentBus](#agentbus)
7
+ 3. [EventBus](#eventbus)
8
+ 4. [Canvas Events](#canvas-events)
9
+
10
+ ---
11
+
12
+ ## Workers
13
+
14
+ Los workers ejecutan tareas dentro de un swarm.
15
+
16
+ ### AgentExecutor
17
+
18
+ ```typescript
19
+ import { AgentExecutor } from "@hive/core";
20
+
21
+ const executor = new AgentExecutor();
22
+ const result = await executor.execute(node, depResults, threadId);
23
+ ```
24
+
25
+ ### WorkerPool
26
+
27
+ Pool de workers para ejecución concurrente.
28
+
29
+ ```typescript
30
+ import { setSchedulerForCleanup, executeScheduledTask } from "@hive/core/swarm/workers";
31
+
32
+ // Programar task
33
+ await executeScheduledTask(job);
34
+ ```
35
+
36
+ ### Worker Custom
37
+
38
+ ```typescript
39
+ import type { IAgentExecutor } from "@hive/core";
40
+
41
+ const myWorker: IAgentExecutor = {
42
+ async execute(node, depResults, threadId) {
43
+ const context = Object.entries(depResults)
44
+ .map(([id, r]) => `${id}: ${r}`).join("\n");
45
+ return await processTask(node.taskDescription, context);
46
+ },
47
+ };
48
+ ```
49
+
50
+ ---
51
+
52
+ ## AgentBus
53
+
54
+ Sistema de eventos singleton para comunicación entre agentes.
55
+
56
+ ```typescript
57
+ import { agentBus, getUnreadMessagesForWorker } from "@hive/core";
58
+
59
+ // Publicar evento
60
+ agentBus.publish("worker:task_started", { taskId: "task-1" }, "worker-1");
61
+
62
+ // Suscribirse
63
+ const unsub = agentBus.subscribe("worker:task_completed", (data) => {
64
+ console.log("Task completed:", data);
65
+ });
66
+
67
+ // Unsubscribe
68
+ unsub();
69
+ ```
70
+
71
+ ### Métodos Helper
72
+
73
+ ```typescript
74
+ import {
75
+ getUnreadMessagesForWorker,
76
+ getProjectMessageHistory
77
+ } from "@hive/core";
78
+
79
+ // Mensajes no leídos para un worker
80
+ const messages = getUnreadMessagesForWorker("worker-1");
81
+
82
+ // Historial de un proyecto
83
+ const history = getProjectMessageHistory("project-1");
84
+ ```
85
+
86
+ ---
87
+
88
+ ## EventBus
89
+
90
+ EventBus global singleton (eventos del sistema).
91
+
92
+ ```typescript
93
+ import { eventBus } from "@hive/core";
94
+
95
+ // Escuchar eventos
96
+ eventBus.on("agent:start", (data) => {
97
+ console.log("Agent started:", data);
98
+ });
99
+
100
+ // Emitir eventos
101
+ eventBus.emit("agent:complete", { agentId: "a1", result: "ok" });
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Canvas Events
107
+
108
+ Eventos de actualización visual del canvas.
109
+
110
+ ```typescript
111
+ import { emitCanvas } from "@hive/core/canvas";
112
+
113
+ // Actualizar estado de un nodo
114
+ emitCanvas("canvas:node_update", {
115
+ nodeId: "agent-1",
116
+ changes: { status: "thinking" },
117
+ });
118
+
119
+ // Eventos disponibles
120
+ emitCanvas("canvas:node_update", { nodeId, changes });
121
+ emitCanvas("canvas:graph_update", { graphId, changes });
122
+ emitCanvas("canvas:worker_update", { workerId, changes });
123
+ ```
124
+
125
+ ### CanvasManager
126
+
127
+ ```typescript
128
+ import { CanvasManager, canvasManager } from "@hive/core/canvas";
129
+
130
+ // Singleton
131
+ const canvas = canvasManager;
132
+
133
+ // Suscribirse a updates de un nodo
134
+ canvas.subscribe("agent-1", (update) => {
135
+ console.log("Node update:", update);
136
+ });
137
+ ```
138
+
139
+ ### WebSocket Canvas
140
+
141
+ ```typescript
142
+ // Cliente se conecta
143
+ const ws = new WebSocket("ws://localhost:3000/ws/canvas");
144
+
145
+ ws.onmessage = (event) => {
146
+ const update = JSON.parse(event.data);
147
+ // { type: "node_update", nodeId: "...", changes: {...} }
148
+ };
149
+
150
+ // Enviar mensaje al agente
151
+ ws.send(JSON.stringify({ type: "user_message", message: "ejecutar tarea" }));
152
+ ```