@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,316 @@
1
+ # API Reference — Agentes
2
+
3
+ ## Índice
4
+
5
+ 1. [createAgent](#createagent)
6
+ 2. [AgentLoop](#agentloop)
7
+ 3. [Tool Selector](#tool-selector)
8
+ 4. [Skill Selector](#skill-selector)
9
+ 5. [LLM Providers](#llm-providers)
10
+
11
+ ---
12
+
13
+ ## createAgent
14
+
15
+ Función de alto nivel para crear y ejecutar agentes.
16
+
17
+ ### Firma
18
+
19
+ ```typescript
20
+ import { createAgent } from "@hive/core";
21
+
22
+ const agent = await createAgent(config: AgentConfig): Promise<Agent>
23
+ ```
24
+
25
+ ### AgentConfig
26
+
27
+ ```typescript
28
+ interface AgentConfig {
29
+ name: string;
30
+ model?: string; // default: gpt-4o-mini
31
+ provider?: "openai" | "anthropic" | "gemini" | "ollama";
32
+ systemPrompt?: string;
33
+ tools?: ToolDefinition[]; // Tools custom
34
+ skills?: SkillDefinition[]; // Skills custom
35
+ mcpServers?: Record<string, { // Servidores MCP
36
+ command?: string; // STDIO transport
37
+ url?: string; // SSE transport
38
+ args?: string[];
39
+ env?: Record<string, string>;
40
+ }>;
41
+ maxIterations?: number;
42
+ workspace?: string;
43
+ }
44
+ ```
45
+
46
+ ### Agent
47
+
48
+ ```typescript
49
+ interface Agent {
50
+ readonly name: string;
51
+ readonly config: AgentConfig;
52
+
53
+ // Streaming chat
54
+ chat(message: string, opts?: {
55
+ threadId?: string;
56
+ channel?: string;
57
+ }): AsyncGenerator<AgentEvent>;
58
+
59
+ // Run to completion (devuelve string final)
60
+ run(task: string, opts?: {
61
+ threadId?: string;
62
+ channel?: string;
63
+ }): Promise<string>;
64
+ }
65
+ ```
66
+
67
+ ### AgentEvent
68
+
69
+ ```typescript
70
+ type AgentEvent =
71
+ | { type: "text"; content: string }
72
+ | { type: "tool_call"; name: string; args: Record<string, unknown> }
73
+ | { type: "tool_result"; name: string; result: unknown }
74
+ | { type: "done"; response: string };
75
+ ```
76
+
77
+ ### Ejemplo
78
+
79
+ ```typescript
80
+ import { createAgent, defineTool } from "@hive/core";
81
+
82
+ const agent = await createAgent({
83
+ name: "asistente",
84
+ provider: "openai",
85
+ model: "gpt-4o-mini",
86
+ systemPrompt: "Eres un asistente útil.",
87
+ });
88
+
89
+ // Streaming
90
+ for await (const event of agent.chat("Hola!")) {
91
+ if (event.type === "text") process.stdout.write(event.content);
92
+ }
93
+
94
+ // Run to completion
95
+ const respuesta = await agent.run("Analiza las ventas del mes");
96
+ ```
97
+
98
+ ---
99
+
100
+ ## defineTool
101
+
102
+ Define una herramienta que el agente puede invocar.
103
+
104
+ ```typescript
105
+ import { defineTool } from "@hive/core";
106
+
107
+ const tool = defineTool({
108
+ name: "saludar",
109
+ description: "Saluda a alguien por su nombre",
110
+ execute: async (args: { nombre: string }) => {
111
+ return { mensaje: `¡Hola ${args.nombre}!` };
112
+ },
113
+ });
114
+ ```
115
+
116
+ ### ToolDefinition
117
+
118
+ ```typescript
119
+ interface ToolDefinition {
120
+ name: string;
121
+ description: string;
122
+ schema?: z.ZodType; // Validación Zod opcional
123
+ execute: (args: any, config?: any) => Promise<any>;
124
+ category?: string;
125
+ }
126
+ ```
127
+
128
+ ---
129
+
130
+ ## defineSkill
131
+
132
+ Define una composición de herramientas con triggers semánticos.
133
+
134
+ ```typescript
135
+ import { defineSkill } from "@hive/core";
136
+
137
+ const skill = defineSkill({
138
+ name: "analisis-datos",
139
+ description: "Analiza datos y genera reportes",
140
+ steps: [
141
+ { action: "web_search", instruction: "Buscar datos relevantes" },
142
+ { action: "create_report", instruction: "Generar reporte" },
143
+ ],
144
+ tools: ["web_search", "create_report"],
145
+ triggers: ["analizar", "reporte", "datos"],
146
+ });
147
+ ```
148
+
149
+ ---
150
+
151
+ ## AgentLoop
152
+
153
+ Clase de bajo nivel para control directo del bucle del agente.
154
+
155
+ ```typescript
156
+ import { AgentLoop, buildAgentLoop } from "@hive/core";
157
+
158
+ const loop = buildAgentLoop({ mcpManager });
159
+
160
+ const stream = loop.stream(
161
+ { messages: [{ role: "user", content: "Hola" }] },
162
+ { configurable: { thread_id: "thread-1" } }
163
+ );
164
+
165
+ for await (const chunk of stream) {
166
+ if (chunk.agent?.messages) {
167
+ console.log(chunk.agent.messages[0].content);
168
+ }
169
+ if (chunk.tools?.messages) {
170
+ console.log("Tool result:", chunk.tools.messages);
171
+ }
172
+ }
173
+ ```
174
+
175
+ ### StreamChunk
176
+
177
+ ```typescript
178
+ interface StreamChunk {
179
+ agent?: { messages: any[] };
180
+ tools?: { messages: any[] };
181
+ usage?: { input_tokens: number; output_tokens: number };
182
+ }
183
+ ```
184
+
185
+ ### runAgent (bajo nivel)
186
+
187
+ ```typescript
188
+ import { runAgent, runAgentIsolated } from "@hive/core";
189
+
190
+ // Streaming
191
+ for await (const chunk of runAgent({
192
+ agentId: "assistant",
193
+ userMessage: "Analiza las ventas",
194
+ threadId: "thread-123",
195
+ })) {
196
+ // procesar chunk
197
+ }
198
+
199
+ // Modo aislado (para workers DAG)
200
+ const result = await runAgentIsolated({
201
+ agentId: "processor",
202
+ taskDescription: "Procesa estos datos",
203
+ threadId: "dag-thread",
204
+ });
205
+ ```
206
+
207
+ ---
208
+
209
+ ## Tool Selector
210
+
211
+ Selección automática de tools basada en FTS5.
212
+
213
+ ```typescript
214
+ import { selectTools, CORE_TOOL_CATALOG } from "@hive/core";
215
+
216
+ // Seleccionar tools relevantes
217
+ const tools = selectTools("Buscar archivos en el proyecto");
218
+ console.log(tools.map(t => t.name));
219
+
220
+ // Con límite personalizado
221
+ const limited = selectTools("search query", CORE_TOOL_CATALOG, 3);
222
+ ```
223
+
224
+ ### Constantes
225
+
226
+ ```typescript
227
+ const MIN_RELEVANCE_THRESHOLD = -30;
228
+ ```
229
+
230
+ ### CORE_TOOL_CATALOG
231
+
232
+ ~50 tools built-in organizadas por categoría:
233
+
234
+ | Categoría | Descripción |
235
+ |-----------|-------------|
236
+ | filesystem | read, write, edit, delete, list, glob |
237
+ | web | web_search, web_fetch, browser automation |
238
+ | projects | project/task CRUD |
239
+ | cron | Croner-based scheduling |
240
+ | cli | Shell command execution |
241
+ | agents | Agent management, task delegation |
242
+ | canvas | UI rendering, A2UI |
243
+ | codebridge | Code execution bridge |
244
+ | voice | TTS/STT |
245
+ | core | save_note, notify, report_progress |
246
+ | office | PDF, DOCX, XLSX, PPTX |
247
+ | meeting | Meeting management |
248
+
249
+ ---
250
+
251
+ ## Skill Selector
252
+
253
+ ```typescript
254
+ import { selectSkills, getMinimalSkills } from "@hive/core";
255
+
256
+ // Skills según mensaje
257
+ const skills = selectSkills("Analyze the sales data");
258
+
259
+ // Skills mínimos siempre disponibles
260
+ const minimal = getMinimalSkills();
261
+ ```
262
+
263
+ ---
264
+
265
+ ## LLM Providers
266
+
267
+ ### Providers Soportados
268
+
269
+ | Provider | Modelos | Streaming |
270
+ |----------|---------|-----------|
271
+ | openai | gpt-4o, gpt-4o-mini | ✅ |
272
+ | anthropic | claude-sonnet, claude-haiku | ✅ |
273
+ | gemini | gemini-2.5-flash | ✅ |
274
+ | ollama | modelos locales | ✅ |
275
+
276
+ ### callLLM
277
+
278
+ ```typescript
279
+ import { callLLM, resolveProviderConfig } from "@hive/core";
280
+
281
+ const config = await resolveProviderConfig("openai", "gpt-4o-mini");
282
+
283
+ const response = await callLLM({
284
+ provider: config.provider,
285
+ model: config.model,
286
+ messages: [{ role: "user", content: "Hola" }],
287
+ });
288
+ ```
289
+
290
+ ---
291
+
292
+ ## Errores Comunes
293
+
294
+ ### createAgent: no se encuentra el agente
295
+
296
+ ```typescript
297
+ // El agente no necesita existir en DB — createAgent lo gestiona internamente
298
+ // Si falla, verificar API keys en variables de entorno
299
+ ```
300
+
301
+ ### Tool no encontrada
302
+
303
+ ```typescript
304
+ // Verificar que la tool está registrada
305
+ const reg = new ToolRegistry();
306
+ reg.register(myTool);
307
+ reg.has("my_tool"); // true
308
+ ```
309
+
310
+ ### Context too large
311
+
312
+ ```typescript
313
+ // Usar maybeCompact para reducir historial
314
+ const { maybeCompact } = await import("../agent/Compaction.ts");
315
+ await maybeCompact(threadId, { channel, userId });
316
+ ```
@@ -0,0 +1,252 @@
1
+ # API Reference — Context Compiler y Componentes Avanzados
2
+
3
+ ## Índice
4
+
5
+ 1. [Context Compiler](#context-compiler)
6
+ 2. [Message History](#message-history)
7
+ 3. [Scratchpad](#scratchpad)
8
+ 4. [EthicsGuard](#ethicsguard)
9
+ 5. [ACE (Tracer, Reflector, Curator)](#ace)
10
+ 6. [MCP Internals](#mcp)
11
+
12
+ ---
13
+
14
+ ## Context Compiler
15
+
16
+ Compila todo el contexto necesario para cada ejecución del agente.
17
+
18
+ ### compileContext
19
+
20
+ ```typescript
21
+ import { compileContext } from "@hive/core";
22
+
23
+ const ctx = await compileContext({
24
+ agentId: "analyst",
25
+ threadId: "thread-123",
26
+ userMessage: "Analiza esto",
27
+ channel: "slack",
28
+ mcpManager: mcpClient,
29
+ isolated: false,
30
+ });
31
+
32
+ // Resultado
33
+ console.log(ctx.systemPrompt);
34
+ console.log(ctx.messages); // Historial compilado
35
+ ```
36
+
37
+ ### Estrategias
38
+
39
+ El Context Compiler implementa 4 estrategias de Context Engineering:
40
+
41
+ | Estrategia | Descripción |
42
+ |------------|-------------|
43
+ | **ESCRIBIR** | Guardar información fuera del contexto (Scratchpad, trazas) |
44
+ | **SELECCIONAR** | Traer solo lo relevante (FTS5 tool/skill/playbook selection) |
45
+ | **COMPRIMIR** | Reducir tokens (compaction, tool result clearing) |
46
+ | **AISLAR** | Separar contextos por agente (workers reciben contexto mínimo) |
47
+
48
+ ---
49
+
50
+ ## Message History
51
+
52
+ ### addMessage
53
+
54
+ ```typescript
55
+ import { addMessage } from "@hive/core";
56
+
57
+ await addMessage(
58
+ threadId: string,
59
+ role: "user" | "assistant" | "system",
60
+ content: string | ContentPart[],
61
+ options?: {
62
+ channel?: string;
63
+ tool_calls?: ToolCall[];
64
+ }
65
+ );
66
+ ```
67
+
68
+ ### getRecentMessages
69
+
70
+ ```typescript
71
+ import { getRecentMessages } from "@hive/core";
72
+
73
+ const messages = await getRecentMessages(threadId, {
74
+ maxTokens: 32000,
75
+ maxMessages: 50,
76
+ });
77
+ ```
78
+
79
+ ### maybeCompact
80
+
81
+ Reduce el historial cuando excede el límite de tokens.
82
+
83
+ ```typescript
84
+ import { maybeCompact } from "@hive/core";
85
+
86
+ await maybeCompact(threadId, { channel: "slack", userId: "U123" });
87
+ ```
88
+
89
+ ### clearOldToolResults
90
+
91
+ ```typescript
92
+ import { clearOldToolResults } from "@hive/core";
93
+
94
+ const clean = clearOldToolResults(messages);
95
+ ```
96
+
97
+ ### ConversationStore
98
+
99
+ ```typescript
100
+ import { getSummary, saveSummary, getScratchpad, saveScratchpadNote } from "@hive/core";
101
+
102
+ // Resumen de conversación
103
+ const summary = getSummary(threadId);
104
+
105
+ // Notas del scratchpad
106
+ const notes = getScratchpad(threadId, "worker-1");
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Scratchpad
112
+
113
+ Memoria temporal por hilo de conversación.
114
+
115
+ ```typescript
116
+ import { Scratchpad } from "@hive/core";
117
+ import { getDb } from "@hive/core";
118
+
119
+ const db = getDb();
120
+ const pad = new Scratchpad(db);
121
+
122
+ // Escribir nota
123
+ pad.write("thread-1", "mi-nota", "contenido");
124
+
125
+ // Leer nota
126
+ const value = pad.read("thread-1", "mi-nota");
127
+
128
+ // Listar notas de un hilo
129
+ const all = pad.list("thread-1");
130
+
131
+ // Eliminar nota
132
+ pad.delete("thread-1", "mi-nota");
133
+
134
+ // Limpiar todas las notas de un hilo
135
+ pad.clear("thread-1");
136
+ ```
137
+
138
+ ---
139
+
140
+ ## EthicsGuard
141
+
142
+ Guardián de reglas de calidad de respuesta desde la base de datos.
143
+
144
+ ```typescript
145
+ import { EthicsGuard } from "@hive/core";
146
+ import { getDb } from "@hive/core";
147
+
148
+ const db = getDb();
149
+ const guard = new EthicsGuard(db);
150
+
151
+ // Obtener reglas
152
+ const rules = guard.getRules(); // Todas
153
+ const rulesForRole = guard.getRules("agent"); // Con FTS5
154
+
155
+ // Inyectar en system prompt
156
+ const prompt = guard.injectIntoPrompt(
157
+ "Eres un asistente.",
158
+ rules
159
+ );
160
+
161
+ // Verificar si hay reglas
162
+ if (guard.hasEthicsLayer()) {
163
+ console.log("Reglas de calidad activas");
164
+ }
165
+ ```
166
+
167
+ ---
168
+
169
+ ## ACE (Tracer, Reflector, Curator)
170
+
171
+ Sistema de Auto-Corrección por Experiencia.
172
+
173
+ ### Tracer
174
+
175
+ ```typescript
176
+ import { saveTrace, recordLLMUsage } from "@hive/core/ace";
177
+
178
+ // Guardar traza de ejecución
179
+ saveTrace({
180
+ agentId: "analyst",
181
+ model: "gpt-4o-mini",
182
+ messages: 5,
183
+ toolCalls: ["web_search", "read_file"],
184
+ durationMs: 1200,
185
+ tokensUsed: 450,
186
+ success: true,
187
+ });
188
+
189
+ // Registrar uso de LLM
190
+ recordLLMUsage({
191
+ model: "gpt-4o-mini",
192
+ inputTokens: 200,
193
+ outputTokens: 250,
194
+ durationMs: 800,
195
+ });
196
+ ```
197
+
198
+ ### Reflector + Curator
199
+
200
+ ```typescript
201
+ import { runReflector, runCurator } from "@hive/core/ace";
202
+
203
+ // Analizar trazas y generar insights
204
+ await runReflector();
205
+
206
+ // Curar insights en reglas del playbook
207
+ await runCurator();
208
+ ```
209
+
210
+ ---
211
+
212
+ ## MCP Internals
213
+
214
+ ### Config
215
+
216
+ ```typescript
217
+ import type { MCPConfig, MCPServerConfig } from "@hive/core";
218
+
219
+ const config: MCPConfig = {
220
+ servers: {
221
+ "my-server": {
222
+ transport: "stdio", // "stdio" | "sse" | "websocket"
223
+ command: "npx",
224
+ args: ["-y", "@server/pkg"],
225
+ env: { KEY: "value" },
226
+ enabled: true,
227
+ },
228
+ },
229
+ };
230
+ ```
231
+
232
+ ### Singleton
233
+
234
+ ```typescript
235
+ import { setMCPManager, getMCPManager, hasMCPManager } from "@hive/core";
236
+
237
+ setMCPManager(mcpManager);
238
+ const mcp = getMCPManager(); // MCPClientManager | undefined
239
+ const exists = hasMCPManager(); // boolean
240
+ ```
241
+
242
+ ### Hot Reload
243
+
244
+ ```typescript
245
+ import { startMCPHotReload, stopMCPHotReload } from "@hive/core";
246
+
247
+ // Watch de configuración MCP
248
+ startMCPHotReload();
249
+
250
+ // Detener watch
251
+ stopMCPHotReload();
252
+ ```