@johpaz/hive-sdk 0.1.4 → 0.1.5

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 (272) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +78 -23
  3. package/bunfig.toml +4 -2
  4. package/docs/API-AGENTS.md +78 -27
  5. package/docs/API-CONTEXT-COMPILER.md +31 -34
  6. package/docs/API-TOOLS-SKILLS-CHANNELS.md +58 -22
  7. package/docs/HIVE-HARNESS.md +1 -1
  8. package/docs/INDEX.md +4 -4
  9. package/docs/TEMPLATE-HIVE-APP.md +10 -10
  10. package/package.json +9 -4
  11. package/packages/cli/package.json +2 -2
  12. package/packages/cli/src/commands/create-app.test.ts +36 -7
  13. package/packages/cli/src/commands/init.ts +3 -3
  14. package/packages/cli/src/commands/run.ts +1 -1
  15. package/packages/cli/src/commands/test.ts +37 -25
  16. package/packages/cli/src/commands/trace.ts +30 -28
  17. package/packages/cli/templates/hive-app/.env.example +10 -2
  18. package/packages/cli/templates/hive-app/README.md +103 -0
  19. package/packages/cli/templates/hive-app/hive.config.ts +9 -3
  20. package/packages/cli/templates/hive-app/src/agents/coordinator.ts +8 -1
  21. package/packages/cli/templates/hive-app/src/main.ts +12 -19
  22. package/packages/core/package.json +5 -4
  23. package/packages/core/src/agent/acceptance-checks.ts +166 -0
  24. package/packages/core/src/agent/agent-catalog.ts +348 -0
  25. package/packages/core/src/agent/agent-loop.ts +1373 -0
  26. package/packages/core/src/agent/capability-search.ts +186 -0
  27. package/packages/core/src/agent/catalog-selector.ts +103 -0
  28. package/packages/core/src/agent/{Compaction.ts → compaction.ts} +86 -63
  29. package/packages/core/src/agent/context-compiler.ts +689 -0
  30. package/packages/core/src/agent/conversation-store.ts +381 -0
  31. package/packages/core/src/agent/curator.ts +276 -0
  32. package/packages/core/src/agent/delegation-runtime.ts +241 -0
  33. package/packages/core/src/agent/goal-runner.ts +323 -0
  34. package/packages/core/src/agent/index.ts +17 -12
  35. package/packages/core/src/agent/llm-client.ts +266 -0
  36. package/packages/core/src/agent/llm-providers/anthropic.ts +264 -0
  37. package/packages/core/src/agent/llm-providers/deepseek.ts +8 -0
  38. package/packages/core/src/agent/{providers → llm-providers}/gemini.ts +98 -60
  39. package/packages/core/src/agent/llm-providers/groq.ts +5 -0
  40. package/packages/core/src/agent/llm-providers/hiveagents.ts +253 -0
  41. package/packages/core/src/agent/{providers → llm-providers}/interface.ts +73 -13
  42. package/packages/core/src/agent/llm-providers/kimi.ts +8 -0
  43. package/packages/core/src/agent/llm-providers/minimax.ts +13 -0
  44. package/packages/core/src/agent/llm-providers/mistral.ts +5 -0
  45. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  46. package/packages/core/src/agent/llm-providers/nvidia.ts +5 -0
  47. package/packages/core/src/agent/{providers → llm-providers}/ollama.ts +31 -5
  48. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +418 -0
  49. package/packages/core/src/agent/llm-providers/openai.ts +5 -0
  50. package/packages/core/src/agent/llm-providers/opencode-go.ts +9 -0
  51. package/packages/core/src/agent/llm-providers/openrouter.ts +5 -0
  52. package/packages/core/src/agent/llm-providers/qwen.ts +5 -0
  53. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  54. package/packages/core/src/agent/minimal-loadout.ts +47 -0
  55. package/packages/core/src/agent/playbook-selector.ts +119 -0
  56. package/packages/core/src/agent/{PromptBuilder.ts → prompt-builder.ts} +21 -22
  57. package/packages/core/src/{harness → agent}/proof-packet.ts +16 -21
  58. package/packages/core/src/agent/providers/index.ts +35 -16
  59. package/packages/core/src/agent/reflector.ts +320 -0
  60. package/packages/core/src/agent/routing-intent.ts +22 -0
  61. package/packages/core/src/{harness → agent}/run-epoch.ts +4 -3
  62. package/packages/core/src/{harness → agent}/run-store.ts +142 -81
  63. package/packages/core/src/agent/{Service.ts → service.ts} +37 -26
  64. package/packages/core/src/agent/skill-selector.ts +374 -0
  65. package/packages/core/src/agent/stuck-loop.ts +209 -0
  66. package/packages/core/src/agent/{selectors/ToolSelector.ts → tool-selector.ts} +188 -178
  67. package/packages/core/src/{ace/Tracer.ts → agent/tracer.ts} +37 -27
  68. package/packages/core/src/api/createAgent.test.ts +139 -27
  69. package/packages/core/src/api/createAgent.ts +232 -44
  70. package/packages/core/src/artifacts/store.ts +162 -0
  71. package/packages/core/src/canvas/canvas-manager.ts +161 -0
  72. package/packages/core/src/canvas/canvas.test.ts +8 -4
  73. package/packages/core/src/canvas/emitter.ts +131 -80
  74. package/packages/core/src/canvas/index.ts +1 -3
  75. package/packages/core/src/channels/base.ts +9 -1
  76. package/packages/core/src/channels/discord.ts +5 -4
  77. package/packages/core/src/channels/manager.ts +122 -30
  78. package/packages/core/src/channels/slack.ts +5 -4
  79. package/packages/core/src/channels/telegram.ts +36 -6
  80. package/packages/core/src/channels/webchat.ts +11 -10
  81. package/packages/core/src/channels/whatsapp.ts +23 -7
  82. package/packages/core/src/config/index.ts +13 -2
  83. package/packages/core/src/config/loader.ts +71 -29
  84. package/packages/core/src/ethics/EthicsGuard.test.ts +90 -36
  85. package/packages/core/src/ethics/EthicsGuard.ts +51 -47
  86. package/packages/core/src/events/agent-bus.ts +44 -68
  87. package/packages/core/src/events/channel-narration.ts +150 -0
  88. package/packages/core/src/events/narration.ts +82 -0
  89. package/packages/core/src/events/tool-narration.ts +62 -0
  90. package/packages/core/src/gateway/delegation-groups.ts +258 -0
  91. package/packages/core/src/{harness → gateway}/durable-queue.ts +102 -42
  92. package/packages/core/src/{harness → gateway}/job-store.ts +85 -48
  93. package/packages/core/src/gateway/lane-queue.ts +173 -0
  94. package/packages/core/src/gateway/notification-inbox.ts +57 -0
  95. package/packages/core/src/gateway/server.ts +1 -1
  96. package/packages/core/src/harness/index.ts +46 -27
  97. package/packages/core/src/index.ts +33 -27
  98. package/packages/core/src/mcp/hot-reload.ts +32 -23
  99. package/packages/core/src/mcp/index.ts +6 -3
  100. package/packages/core/src/mcp/singleton.ts +1 -4
  101. package/packages/core/src/mcp/tool-sync.ts +138 -0
  102. package/packages/core/src/memory/Scratchpad.test.ts +39 -20
  103. package/packages/core/src/memory/Scratchpad.ts +27 -34
  104. package/packages/core/src/multimodal/vision-service.ts +44 -38
  105. package/packages/core/src/resilience/retry.ts +95 -0
  106. package/packages/core/src/scheduler/CronScheduler.ts +334 -287
  107. package/packages/core/src/scheduler/index.ts +9 -7
  108. package/packages/core/src/scheduler/integration.ts +46 -26
  109. package/packages/core/src/scheduler/scheduler.test.ts +9 -13
  110. package/packages/core/src/scheduler/types.ts +7 -2
  111. package/packages/core/src/security/Pairing.ts +1 -1
  112. package/packages/core/src/skills/bundled/a2ui/a2ui_dashboard/SKILL.md +176 -0
  113. package/packages/core/src/skills/bundled/a2ui/a2ui_form/SKILL.md +202 -0
  114. package/packages/core/src/skills/bundled/a2ui/a2ui_interactive/SKILL.md +206 -0
  115. package/packages/core/src/skills/bundled/agents/agent_spawner/SKILL.md +173 -0
  116. package/packages/core/src/skills/bundled/agents/memory_manager/SKILL.md +143 -0
  117. package/packages/core/src/skills/bundled/agents/research_and_remember/SKILL.md +139 -0
  118. package/packages/core/src/skills/bundled/agents/task_orchestrator/SKILL.md +98 -0
  119. package/packages/core/src/skills/bundled/api/api_client/SKILL.md +132 -0
  120. package/packages/core/src/skills/bundled/cli/cli_pipeline/SKILL.md +135 -0
  121. package/packages/core/src/skills/bundled/cli/cli_safe_exec/SKILL.md +125 -0
  122. package/packages/core/src/skills/bundled/cli/software_engineering/SKILL.md +23 -0
  123. package/packages/core/src/skills/bundled/cron_manager/SKILL.md +188 -0
  124. package/packages/core/src/skills/bundled/cron_reminder/SKILL.md +112 -0
  125. package/packages/core/src/skills/bundled/filesystem/file_manager/SKILL.md +118 -0
  126. package/packages/core/src/skills/bundled/filesystem/file_read_and_summarize/SKILL.md +109 -0
  127. package/packages/core/src/skills/bundled/filesystem/file_writer/SKILL.md +129 -0
  128. package/packages/core/src/skills/bundled/filesystem/workspace_file_operator/SKILL.md +22 -0
  129. package/packages/core/src/skills/bundled/office/office_document_manager/SKILL.md +262 -0
  130. package/packages/core/src/skills/bundled/search_knowledge/capability_discovery/SKILL.md +75 -0
  131. package/packages/core/src/skills/bundled/web/browser_automate/SKILL.md +120 -0
  132. package/packages/core/src/skills/bundled/web/browser_scrape/SKILL.md +109 -0
  133. package/packages/core/src/skills/bundled/web/web_monitor/SKILL.md +127 -0
  134. package/packages/core/src/skills/bundled/web/web_research/SKILL.md +119 -0
  135. package/packages/core/src/skills/bundled-data.generated.ts +731 -2678
  136. package/packages/core/src/skills/skills.test.ts +52 -11
  137. package/packages/core/src/{harness → storage}/boot-id.ts +5 -2
  138. package/packages/core/src/storage/bootstrap.ts +151 -0
  139. package/packages/core/src/storage/causal-events.ts +84 -0
  140. package/packages/core/src/storage/collections.ts +680 -0
  141. package/packages/core/src/storage/crypto.ts +205 -74
  142. package/packages/core/src/{harness/db-helpers.ts → storage/hive.ts} +63 -7
  143. package/packages/core/src/storage/hivedb.ts +61 -0
  144. package/packages/core/src/storage/index.ts +111 -18
  145. package/packages/core/src/storage/model-id.ts +53 -0
  146. package/packages/core/src/storage/onboarding.ts +540 -972
  147. package/packages/core/src/storage/reconcile.ts +238 -0
  148. package/packages/core/src/storage/seed.ts +572 -406
  149. package/packages/core/src/storage/usage.ts +285 -225
  150. package/packages/core/src/storage/user-email.ts +11 -0
  151. package/packages/core/src/swarm/AgentExecutor.ts +1 -1
  152. package/packages/core/src/swarm/EventBridge.ts +1 -1
  153. package/packages/core/src/swarm/index.ts +12 -9
  154. package/packages/core/src/tool-runtime/index.ts +146 -23
  155. package/packages/core/src/tool-runtime/tool-worker.ts +2 -2
  156. package/packages/core/src/tool-runtime/worker-tools.ts +27 -0
  157. package/packages/core/src/{canvas/a2ui-tools.ts → tools/a2ui/index.ts} +17 -8
  158. package/packages/core/src/tools/agents/get-available-models.ts +36 -54
  159. package/packages/core/src/tools/agents/index.ts +784 -292
  160. package/packages/core/src/tools/api/api-request.test.ts +164 -0
  161. package/packages/core/src/tools/api/api-request.ts +174 -0
  162. package/packages/core/src/tools/api/index.ts +16 -0
  163. package/packages/core/src/tools/cli/index.ts +4 -0
  164. package/packages/core/src/tools/core/index.ts +281 -112
  165. package/packages/core/src/tools/cron/index.ts +121 -124
  166. package/packages/core/src/tools/index.ts +63 -78
  167. package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -1
  168. package/packages/core/src/tools/types.ts +3 -1
  169. package/packages/core/src/tools/web/artifact-inspect.ts +23 -0
  170. package/packages/core/src/tools/web/browser-screenshot.ts +26 -5
  171. package/packages/core/src/tools/web/browser-service.ts +5 -0
  172. package/packages/core/src/tools/web/browser-type.ts +3 -8
  173. package/packages/core/src/tools/web/index.ts +4 -4
  174. package/packages/core/src/voice/index.ts +89 -63
  175. package/packages/core/src/workers/agent.worker.ts +2 -2
  176. package/packages/core/src/workers/workers.test.ts +3 -10
  177. package/scripts/bump-version.ts +248 -0
  178. package/scripts/generate-skill-bundle.ts +108 -0
  179. package/test/agent-loop-terminal-synthesis.test.ts +32 -0
  180. package/test/catalog-agents-stay-enabled.test.ts +117 -0
  181. package/test/causal-events.test.ts +117 -0
  182. package/test/compaction.test.ts +105 -0
  183. package/test/context-compiler.test.ts +269 -0
  184. package/test/curator.test.ts +130 -0
  185. package/test/durable-queue.test.ts +114 -0
  186. package/test/harness-barrel.test.ts +64 -0
  187. package/test/hive-helpers.test.ts +130 -0
  188. package/test/hivedb-search.test.ts +189 -0
  189. package/test/internal-turns.test.ts +166 -0
  190. package/test/job-idempotency.test.ts +68 -0
  191. package/test/job-retry-backoff.test.ts +184 -0
  192. package/test/job-store.test.ts +381 -0
  193. package/test/llm-retry.test.ts +97 -0
  194. package/test/memory-perf.test.ts +774 -0
  195. package/test/minimal-loadout.test.ts +78 -0
  196. package/test/model-catalog.test.ts +105 -0
  197. package/test/preload.ts +12 -0
  198. package/test/reflector.test.ts +320 -0
  199. package/test/retention-cap.test.ts +91 -0
  200. package/test/retired-capabilities-pruned.test.ts +192 -0
  201. package/test/run-store.test.ts +355 -0
  202. package/test/scratchpad.test.ts +74 -0
  203. package/test/secrets-durability.test.ts +119 -0
  204. package/test/seed-model-reseed.test.ts +155 -0
  205. package/test/setup-agent-seed.test.ts +264 -0
  206. package/test/tool-inventory.test.ts +65 -0
  207. package/test/tool-runtime.test.ts +258 -0
  208. package/test/toon.test.ts +429 -0
  209. package/tsconfig.json +2 -0
  210. package/packages/core/src/ace/Curator.ts +0 -158
  211. package/packages/core/src/ace/Reflector.ts +0 -200
  212. package/packages/core/src/ace/index.ts +0 -4
  213. package/packages/core/src/agent/AgentRunner.ts +0 -711
  214. package/packages/core/src/agent/ContextCompiler.ts +0 -567
  215. package/packages/core/src/agent/ContextGuard.ts +0 -91
  216. package/packages/core/src/agent/ConversationStore.ts +0 -254
  217. package/packages/core/src/agent/Hooks.ts +0 -166
  218. package/packages/core/src/agent/StuckLoop.ts +0 -133
  219. package/packages/core/src/agent/providers/LLMClient.ts +0 -149
  220. package/packages/core/src/agent/providers/anthropic.ts +0 -212
  221. package/packages/core/src/agent/providers/openai-compat.ts +0 -231
  222. package/packages/core/src/agent/selectors/PlaybookSelector.ts +0 -121
  223. package/packages/core/src/agent/selectors/SkillSelector.ts +0 -322
  224. package/packages/core/src/agent/selectors/index.ts +0 -6
  225. package/packages/core/src/auth/auth.ts +0 -121
  226. package/packages/core/src/auth/index.ts +0 -1
  227. package/packages/core/src/canvas/CanvasManager.ts +0 -390
  228. package/packages/core/src/canvas/canvas-tools.ts +0 -448
  229. package/packages/core/src/harness/collections.ts +0 -98
  230. package/packages/core/src/harness/goal-verifier.ts +0 -141
  231. package/packages/core/src/harness/harness.test.ts +0 -236
  232. package/packages/core/src/harness/reconcile.ts +0 -149
  233. package/packages/core/src/mcp/MCPToolAdapter.ts +0 -176
  234. package/packages/core/src/multimodal/VisionService.ts +0 -293
  235. package/packages/core/src/scheduler/dag/AgentExecutor.ts +0 -53
  236. package/packages/core/src/scheduler/dag/DAGScheduler.ts +0 -250
  237. package/packages/core/src/scheduler/dag/EventBridge.ts +0 -122
  238. package/packages/core/src/scheduler/dag/TaskGraph.ts +0 -192
  239. package/packages/core/src/scheduler/dag/TaskNode.ts +0 -97
  240. package/packages/core/src/scheduler/dag/TaskResult.ts +0 -22
  241. package/packages/core/src/scheduler/dag/errors.ts +0 -37
  242. package/packages/core/src/scheduler/dag/index.ts +0 -26
  243. package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +0 -97
  244. package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +0 -21
  245. package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +0 -46
  246. package/packages/core/src/storage/HiveDBStorage.ts +0 -64
  247. package/packages/core/src/storage/SQLiteStorage.ts +0 -414
  248. package/packages/core/src/storage/hiveSeed.ts +0 -308
  249. package/packages/core/src/storage/hiveStorage.test.ts +0 -38
  250. package/packages/core/src/storage/schema.ts +0 -689
  251. package/packages/core/src/storage/storage.test.ts +0 -37
  252. package/packages/core/src/swarm/AgentBus.ts +0 -460
  253. package/packages/core/src/swarm/EventBus.ts +0 -169
  254. package/packages/core/src/swarm/WorkerPool.ts +0 -236
  255. package/packages/core/src/tools/bridge-events.ts +0 -26
  256. package/packages/core/src/tools/canvas/index.ts +0 -375
  257. package/packages/core/src/tools/codebridge/index.ts +0 -342
  258. package/packages/core/src/tools/meeting/index.ts +0 -353
  259. package/packages/core/src/tools/projects/index.ts +0 -37
  260. package/packages/core/src/tools/projects/project-create.ts +0 -94
  261. package/packages/core/src/tools/projects/project-done.ts +0 -66
  262. package/packages/core/src/tools/projects/project-fail.ts +0 -66
  263. package/packages/core/src/tools/projects/project-list.ts +0 -96
  264. package/packages/core/src/tools/projects/project-update.ts +0 -72
  265. package/packages/core/src/tools/projects/task-create.ts +0 -68
  266. package/packages/core/src/tools/projects/task-evaluate.ts +0 -93
  267. package/packages/core/src/tools/projects/task-update.ts +0 -93
  268. package/packages/core/src/tools/voice/index.ts +0 -104
  269. package/packages/core/src/tools/web/api-request.test.ts +0 -170
  270. package/packages/core/src/tools/web/api-request.ts +0 -239
  271. package/test/setup-db.ts +0 -216
  272. /package/packages/core/src/agent/{NativeTools.ts → native-tools.ts} +0 -0
@@ -0,0 +1,119 @@
1
+ /**
2
+ * HiveDB-based Playbook Rules Selector (ACE Curator)
3
+ *
4
+ * This module allows the Context Compiler to inject relevant evolved rules
5
+ * into the agent prompt based on semantic relevance to the current message.
6
+ * Search runs on the HiveDB capability index (Spanish stemming + accent
7
+ * folding, lenient parsing — raw user text never throws).
8
+ */
9
+
10
+ import { col } from "../storage/hive"
11
+ import type { PlaybookDoc } from "../storage/collections"
12
+ import { logger } from "../utils/logger"
13
+ import {
14
+ searchCapabilities,
15
+ applyRelativeCutoff,
16
+ replaceCapabilityDocs,
17
+ type CapabilityDoc,
18
+ } from "./capability-search"
19
+
20
+ const log = logger.child("playbook-selector")
21
+
22
+ // ─── Types ───────────────────────────────────────────────────────────────────────
23
+
24
+ export interface PlaybookRule {
25
+ id: string
26
+ rule: string
27
+ category: string
28
+ applicable_to?: string
29
+ }
30
+
31
+ // ─── Configuration ─────────────────────────────────────────────────────────────
32
+
33
+ /** Maximum rules to inject per context window */
34
+ const MAX_RULES_PER_TURN = 5
35
+
36
+ /**
37
+ * Relative relevance cutoff: keep a hit only if it scores at least this
38
+ * fraction of the top hit (HiveDB BM25 scores are positive, higher = better).
39
+ */
40
+ const RELEVANCE_RATIO = 0.3
41
+
42
+ // ─── Selection Logic ───────────────────────────────────────────────────────────
43
+
44
+ /**
45
+ * Select relevant rules from the Playbook based on semantic matching
46
+ */
47
+ export async function selectPlaybookRules(message: string): Promise<PlaybookRule[]> {
48
+ const startTime = performance.now()
49
+
50
+ if (!message.trim()) return []
51
+
52
+ try {
53
+ const hits = await searchCapabilities(message, {
54
+ types: ["playbook"],
55
+ k: MAX_RULES_PER_TURN,
56
+ })
57
+
58
+ const relevantIds = applyRelativeCutoff(hits, RELEVANCE_RATIO).map(h => h.rawId)
59
+
60
+ if (relevantIds.length === 0) return []
61
+
62
+ // Fetch full rules
63
+ const playbookCol = await col<PlaybookDoc>("playbook")
64
+ const entries = await Promise.all(relevantIds.map(id => playbookCol.get(id)))
65
+ const rules: PlaybookRule[] = entries
66
+ .filter((e): e is NonNullable<typeof e> => !!e && e.doc.active)
67
+ .map(e => ({
68
+ id: e.id,
69
+ rule: e.doc.rule,
70
+ category: e.doc.category,
71
+ applicable_to: e.doc.applicable_to ?? undefined,
72
+ }))
73
+
74
+ const timing = performance.now() - startTime
75
+ log.info(`[playbook-selector] Selected ${rules.length} rules in ${timing.toFixed(2)}ms`)
76
+ if (rules.length > 0) {
77
+ log.debug(`[playbook-selector] Rules: ${rules.map(r => `[${r.id}] ${r.rule.substring(0, 60)}`).join(', ')}`)
78
+ }
79
+
80
+ return rules
81
+ } catch (err) {
82
+ log.error(`[playbook-selector] Failed to select rules:`, err)
83
+ return []
84
+ }
85
+ }
86
+
87
+ // ─── Sync Logic ───────────────────────────────────────────────────────────────
88
+
89
+ /**
90
+ * Sync active playbook rules to the HiveDB capability index.
91
+ * Replaces all `type=playbook` documents atomically.
92
+ */
93
+ export async function syncPlaybookToIndex(): Promise<void> {
94
+ try {
95
+ // Step 1: Get active rules
96
+ const playbookCol = await col<PlaybookDoc>("playbook")
97
+ const rules = (await playbookCol.scan({})).map(e => e.doc).filter(r => r.active)
98
+
99
+ if (rules.length === 0) {
100
+ log.debug(`[playbook-selector] No rules in playbook to sync`)
101
+ }
102
+
103
+ // Step 2: Replace all playbook documents in the capability index
104
+ const docs: CapabilityDoc[] = rules.map(item => ({
105
+ type: "playbook" as const,
106
+ rawId: item.id,
107
+ body: item.rule,
108
+ tags: [item.category, item.applicable_to].filter(Boolean).join(" "),
109
+ }))
110
+
111
+ await replaceCapabilityDocs("playbook", docs)
112
+
113
+ log.info(`[playbook-selector] Sync complete: ${rules.length} rules indexed in HiveDB`)
114
+
115
+ } catch (err) {
116
+ log.error(`[playbook-selector] Playbook index sync failed:`, err)
117
+ throw err
118
+ }
119
+ }
@@ -13,10 +13,11 @@
13
13
  * - Skills activos
14
14
  */
15
15
 
16
- import { getDb } from "../storage/SQLiteStorage.ts"
17
- import { logger } from "../utils/logger.ts"
18
- import { formatContext } from "../utils/toon.ts"
19
- import { resolveUserId } from "../storage/onboarding.ts"
16
+ import { col } from "../storage/hive"
17
+ import type { EthicsDoc, AgentDoc, UserDoc } from "../storage/collections"
18
+ import { logger } from "../utils/logger"
19
+ import { formatContext } from "../utils/toon"
20
+ import { resolveUserId } from "../storage/onboarding"
20
21
 
21
22
  const log = logger.child("prompt-builder")
22
23
 
@@ -35,18 +36,16 @@ export interface BuildSystemPromptOpts {
35
36
  * 4. Identidad del usuario (nombre, preferencias, contexto)
36
37
  */
37
38
  export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<string> {
38
- const db = getDb()
39
39
  const { agentId, userId } = opts
40
40
 
41
41
  // ──────────────────────────────────────────────────────────────────────────
42
42
  // 1. ÉTICA — Capa constitucional (siempre completa)
43
43
  // ──────────────────────────────────────────────────────────────────────────
44
- const ethicsRules = db.query<any, []>(`
45
- SELECT name, content, description
46
- FROM ethics
47
- WHERE enabled = 1 AND active = 1
48
- ORDER BY is_default DESC, id ASC
49
- `).all()
44
+ const ethicsCol = await col<EthicsDoc>("ethics")
45
+ const ethicsRules = (await ethicsCol.scan({}))
46
+ .map(e => e.doc)
47
+ .filter(r => r.enabled && r.active)
48
+ .sort((a, b) => (b.is_default ? 1 : 0) - (a.is_default ? 1 : 0) || a.id.localeCompare(b.id))
50
49
 
51
50
  let ethicsSection = ""
52
51
  if (ethicsRules.length > 0) {
@@ -68,11 +67,9 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
68
67
  // ──────────────────────────────────────────────────────────────────────────
69
68
  // 2. IDENTIDAD DEL AGENTE
70
69
  // ──────────────────────────────────────────────────────────────────────────
71
- const agent = db.query<any, [string]>(`
72
- SELECT id, name, role, description, system_prompt, tone, max_iterations, workspace
73
- FROM agents
74
- WHERE id = ?
75
- `).get(agentId)
70
+ const agentsCol = await col<AgentDoc>("agents")
71
+ const agentEntry = await agentsCol.get(agentId)
72
+ const agent = agentEntry?.doc
76
73
 
77
74
  if (!agent) {
78
75
  throw new Error(`Agent not found: ${agentId}`)
@@ -119,11 +116,9 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
119
116
  // ──────────────────────────────────────────────────────────────────────────
120
117
  // 3. IDENTIDAD DEL USUARIO
121
118
  // ──────────────────────────────────────────────────────────────────────────
122
- const user = db.query<any, [string]>(`
123
- SELECT id, name, language, timezone, occupation, notes
124
- FROM users
125
- WHERE id = ?
126
- `).get(userId)
119
+ const usersCol = await col<UserDoc>("users")
120
+ const userEntry = await usersCol.get(userId)
121
+ const user = userEntry?.doc
127
122
 
128
123
  let userSection = `# IDENTIDAD DEL USUARIO\n\n`
129
124
 
@@ -131,6 +126,7 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
131
126
  const userData: Record<string, string | null> = {}
132
127
 
133
128
  if (user.name) userData.Nombre = user.name
129
+ if (agent.role === "coordinator" && user.email) userData.CorreoPropio = user.email
134
130
  if (user.language) userData.Idioma = user.language
135
131
  if (user.timezone) userData.ZonaHoraria = user.timezone
136
132
  if (user.occupation) userData.Ocupación = user.occupation
@@ -139,6 +135,9 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
139
135
  // Usar TOON para comprimir datos del usuario
140
136
  if (Object.keys(userData).length > 0) {
141
137
  userSection += formatContext(userData) + "\n\n"
138
+ if (agent.role === "coordinator" && user.email) {
139
+ userSection += `Cuando el usuario diga "envíame", "mándame" o "a mi correo" sin indicar otro destinatario, usá CorreoPropio. Para terceras personas, resolvé su dirección por separado.\n\n`
140
+ }
142
141
  } else {
143
142
  userSection += `Usuario ID: ${userId}\n\n`
144
143
  }
@@ -164,6 +163,6 @@ export async function buildSystemPromptWithProjects(opts: {
164
163
  agentId: string
165
164
  userId?: string
166
165
  }): Promise<string> {
167
- const userId = opts.userId || resolveUserId({}) || "default"
166
+ const userId = opts.userId || (await resolveUserId({})) || "default"
168
167
  return buildSystemPrompt({ agentId: opts.agentId, userId })
169
168
  }
@@ -1,20 +1,18 @@
1
1
  /**
2
- * Proof packets — compressed evidence artifact for a completed run
3
- * (harness-engineering "proof" practice): what was intended, what was
2
+ * Proof packets — compressed evidence artifact for a completed goal/project
3
+ * run (harness-engineering "proof" practice): what was intended, what was
4
4
  * checked, what evidence backs the verdict, and known limits. Written once
5
- * per run so a reviewer doesn't have to replay the whole run to trust its
6
- * outcome.
5
+ * per run by the goal_run / project_task executors after verification, so a
6
+ * reviewer doesn't have to replay the whole run to trust its outcome.
7
7
  */
8
8
 
9
- import { col, nextId } from "./db-helpers";
10
- import type { ProofPacketDoc } from "./collections";
11
- import type { AcceptanceResult } from "./goal-verifier";
9
+ import { col, nextId, toIndexable } from "../storage/hive";
10
+ import type { ProofPacketDoc } from "../storage/collections";
11
+ import type { AcceptanceResult } from "./goal-runner";
12
12
  import type { RunEpoch } from "./run-epoch";
13
13
  import { logger } from "../utils/logger";
14
14
 
15
- const log = logger.child("harness:proof-packet");
16
-
17
- const COLLECTION = "harness_proofPackets";
15
+ const log = logger.child("proof-packet");
18
16
 
19
17
  export interface BuildProofPacketInput {
20
18
  runId: string;
@@ -27,10 +25,14 @@ export interface BuildProofPacketInput {
27
25
  evidence: string[];
28
26
  knownLimits?: string | null;
29
27
  epoch?: RunEpoch | null;
28
+ catalogAgentId?: string | null;
30
29
  }
31
30
 
32
31
  export async function buildProofPacket(input: BuildProofPacketInput): Promise<ProofPacketDoc> {
33
- const id = await nextId(COLLECTION);
32
+ if (input.met && (input.checksRun.length === 0 || input.evidence.length === 0)) {
33
+ throw new Error("A successful proof packet requires at least one check run and non-empty evidence");
34
+ }
35
+ const id = await nextId("proofPackets");
34
36
  const acceptanceResults: AcceptanceResult[] =
35
37
  input.acceptanceResults ?? [{ id: "goal", description: input.intendedOutcome, met: input.met, evidence: input.evidence.join("; ") || "n/a" }];
36
38
 
@@ -44,26 +46,19 @@ export async function buildProofPacket(input: BuildProofPacketInput): Promise<Pr
44
46
  evidence_json: JSON.stringify(input.evidence),
45
47
  known_limits: input.knownLimits ?? null,
46
48
  epoch_json: input.epoch ? JSON.stringify(input.epoch) : null,
49
+ catalog_agent_id: toIndexable(input.catalogAgentId),
47
50
  met: input.met,
48
51
  created_at: Date.now(),
49
52
  };
50
53
 
51
- const c = await col<ProofPacketDoc>(COLLECTION);
54
+ const c = await col<ProofPacketDoc>("proofPackets");
52
55
  await c.put(id, doc, { expectedVersion: 0 });
53
56
  log.info(`[buildProofPacket] Packet ${id} written for run ${input.runId} (met=${input.met})`);
54
57
  return doc;
55
58
  }
56
59
 
57
60
  export async function findProofPacketsByRun(runId: string): Promise<ProofPacketDoc[]> {
58
- const c = await col<ProofPacketDoc>(COLLECTION);
61
+ const c = await col<ProofPacketDoc>("proofPackets");
59
62
  const entries = await c.findBy("run_id", runId);
60
63
  return entries.map((e) => e.doc);
61
64
  }
62
-
63
- export async function ensureProofPacketIndexes(): Promise<void> {
64
- const c = await col<ProofPacketDoc>(COLLECTION);
65
- await c.createIndex("run_id");
66
- await c.createIndex("agent_id");
67
- }
68
-
69
- export { COLLECTION as PROOF_PACKETS_COLLECTION };
@@ -7,14 +7,19 @@
7
7
 
8
8
  import type { Config } from "../../config/loader.ts"
9
9
  import { logger } from "../../utils/logger.ts"
10
- import { getDb } from "../../storage/SQLiteStorage.ts"
11
- import { getAgentLoop } from "../AgentRunner.ts"
12
- import { resolveUserId, resolveAgentId } from "../../storage/onboarding.ts"
13
- import type { ContentPart } from "../../multimodal/types.ts"
14
-
15
- export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia"
16
-
17
- import type { StepEvent } from "../AgentRunner.ts"
10
+ import { getAgentLoop } from "../agent-loop"
11
+ import { resolveUserId, resolveAgentId } from "../../storage/onboarding"
12
+ import type { ContentPart } from "../../multimodal/types"
13
+ import type { TurnSource } from "../../storage/collections"
14
+
15
+ export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia" | "hiveagents" | "z-ai" | "modelscope" | "minimax" | "qwen" | "groq" | "opencode-go"
16
+
17
+ export interface StepEvent {
18
+ type: "text" | "plan" | "tool_call" | "tool_result"
19
+ message: string
20
+ toolName?: string
21
+ isError?: boolean
22
+ }
18
23
 
19
24
  export interface ModelOptions {
20
25
  provider?: Provider
@@ -26,12 +31,22 @@ export interface ModelOptions {
26
31
  tools?: Record<string, any>
27
32
  maxSteps?: number
28
33
  onToken?: (token: string) => void
34
+ onReasoningToken?: (token: string) => void
29
35
  onStep?: (step: StepEvent) => Promise<void>
30
36
  threadId?: string
31
37
  userId?: string
38
+ agentId?: string
32
39
  channel?: string
33
40
  rawUserMessage?: string
34
41
  signal?: AbortSignal
42
+ /** Durable run options — checkpoint/resume via agentRuns (see run-store). */
43
+ runId?: string
44
+ resume?: boolean
45
+ durable?: boolean
46
+ turnId?: string
47
+ sessionId?: string
48
+ /** See AgentLoopOptions.historySource in agent-loop.ts. */
49
+ historySource?: TurnSource
35
50
  }
36
51
 
37
52
  export interface ModelResponse {
@@ -57,12 +72,11 @@ export class AgentRunner {
57
72
  }
58
73
 
59
74
  async generate(options: ModelOptions): Promise<ModelResponse> {
60
- const db = getDb()
61
- // Resolve agentId from database (coordinator or first enabled)
62
- const agentId = resolveAgentId(null) || "main"
75
+ // Resolve agentId from explicit option or database (coordinator/first enabled)
76
+ const agentId = options.agentId || (await resolveAgentId(null)) || "main"
63
77
 
64
78
  // Resolve userId from database
65
- const userId = options.userId || resolveUserId({})
79
+ const userId = options.userId || (await resolveUserId({}))
66
80
  if (!userId) {
67
81
  throw new Error("No userId provided. Please complete onboarding first.")
68
82
  }
@@ -90,8 +104,16 @@ export class AgentRunner {
90
104
  // system_prompt intentionally omitted — context-compiler builds it
91
105
  channel: options.channel,
92
106
  raw_user_message: options.rawUserMessage,
107
+ run_id: options.runId,
108
+ resume: options.resume,
109
+ durable: options.durable,
110
+ turn_id: options.turnId,
111
+ session_id: options.sessionId,
112
+ history_source: options.historySource,
93
113
  },
94
114
  signal: options.signal,
115
+ onToken: options.onToken,
116
+ onReasoningToken: options.onReasoningToken,
95
117
  }
96
118
  )
97
119
 
@@ -122,7 +144,7 @@ export class AgentRunner {
122
144
  } else {
123
145
  logger.debug(`[STREAM] Content empty or whitespace only, skipping accumulation`)
124
146
  }
125
- if (options.onToken) options.onToken(content)
147
+ if (options.onToken && !chunk.agent.streamed) options.onToken(content)
126
148
  } else {
127
149
  logger.debug(`[STREAM] No content in chunk, lastMsg.content is falsy`)
128
150
  }
@@ -194,6 +216,3 @@ export class AgentRunner {
194
216
  }
195
217
  }
196
218
 
197
- export function createAgentRunner(config: Config): AgentRunner {
198
- return new AgentRunner(config)
199
- }