@johpaz/hive-agents 1.0.0 → 1.0.1

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 (159) hide show
  1. package/README.md +25 -11
  2. package/dist/hive.js +22245 -6788
  3. package/dist/tool-worker.js +6 -2
  4. package/dist/ui/assets/{A2UIPage-D4nUFe5q.js → A2UIPage-D4nzp5NV.js} +1 -1
  5. package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-M2RhjeA1.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-DkFRtj8g.js} +1 -1
  7. package/dist/ui/assets/AgentNewPage-CfBU7puz.js +1 -0
  8. package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-Ctzq2LWx.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-DKbGO1QW.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-H6rgr8DQ.js} +2 -2
  11. package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-BIjYGf4m.js} +2 -2
  12. package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-DazoxtBJ.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-DMZ6KtQ3.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-CSLFvHL7.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-BCfvugHB.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BE6Epe0d.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-D0cApfM1.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BVUPHG9z.js} +1 -1
  19. package/dist/ui/assets/{SettingsPage-B6FTSkOn.js → SettingsPage-DCZ4nql4.js} +1 -1
  20. package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-In19p30M.js} +1 -1
  21. package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-ByVBSzxL.js} +1 -1
  22. package/dist/ui/assets/{activity-CQuPevhB.js → activity-BIIli7ET.js} +1 -1
  23. package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-D1PD9yFH.js} +1 -1
  24. package/dist/ui/assets/arrow-left-BfcnX8Er.js +1 -0
  25. package/dist/ui/assets/arrow-right-Q-dzAn8k.js +1 -0
  26. package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +1 -0
  27. package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-S9-_Q6QR.js} +1 -1
  28. package/dist/ui/assets/check-CryV78SQ.js +1 -0
  29. package/dist/ui/assets/chevron-down-QCtMs-Af.js +1 -0
  30. package/dist/ui/assets/chevron-left-dTGbyl5G.js +1 -0
  31. package/dist/ui/assets/chevron-right-D0GjXbnO.js +1 -0
  32. package/dist/ui/assets/chevron-up-Cg0jO8uT.js +1 -0
  33. package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-DTVW4R94.js} +1 -1
  34. package/dist/ui/assets/circle-check-BAolxswA.js +1 -0
  35. package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-CJXbXzRh.js} +1 -1
  36. package/dist/ui/assets/{copy-33tZrzc9.js → copy-X_TPpA-A.js} +1 -1
  37. package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-uUBz_NIB.js} +1 -1
  38. package/dist/ui/assets/{download-CiQqqXyz.js → download-C-fXu08w.js} +1 -1
  39. package/dist/ui/assets/{earth-DCvN7ynm.js → earth-CTsVjCmp.js} +1 -1
  40. package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-5zBh5yzc.js} +1 -1
  41. package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-CvpRhwC_.js} +1 -1
  42. package/dist/ui/assets/{eye-C8sKSSkg.js → eye-CM-HQEWU.js} +1 -1
  43. package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-lwkvYGtA.js} +1 -1
  44. package/dist/ui/assets/gauge-CB-cas-h.js +1 -0
  45. package/dist/ui/assets/{history-BtTD1kDo.js → history-eSHspWRr.js} +1 -1
  46. package/dist/ui/assets/index-D489S18g.css +2 -0
  47. package/dist/ui/assets/{index-Bejlp-R1.js → index-ZjAc-KQS.js} +4 -4
  48. package/dist/ui/assets/{info-mpk1tsNC.js → info-DTgFQ_jA.js} +1 -1
  49. package/dist/ui/assets/{key-CoQ0qtXt.js → key-CeM9JJkq.js} +1 -1
  50. package/dist/ui/assets/loader-circle-Dtfz4FWw.js +1 -0
  51. package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-B089GUAJ.js} +1 -1
  52. package/dist/ui/assets/{mail-BG0RYSkL.js → mail--gNFIe4M.js} +1 -1
  53. package/dist/ui/assets/{pause-Cme88_9s.js → pause-DjT1nwQM.js} +1 -1
  54. package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-6PRgdjiU.js} +1 -1
  55. package/dist/ui/assets/play-tOrP0xUJ.js +1 -0
  56. package/dist/ui/assets/plus-Cnom3j47.js +1 -0
  57. package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-D-joO9J0.js} +1 -1
  58. package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BRrzoHQW.js} +1 -1
  59. package/dist/ui/assets/search-D277MUP0.js +1 -0
  60. package/dist/ui/assets/{select-BhbW0stK.js → select-BOR8MsSL.js} +1 -1
  61. package/dist/ui/assets/{send-D6whYpw-.js → send-DIlj81PT.js} +1 -1
  62. package/dist/ui/assets/{settings-BX6q3MGB.js → settings-CkBjgAEm.js} +1 -1
  63. package/dist/ui/assets/{shield-BnGyu1xf.js → shield-U0hIjGzm.js} +1 -1
  64. package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-VXHGDbNh.js} +1 -1
  65. package/dist/ui/assets/{square-ju5H8nrT.js → square-OHeetvN3.js} +1 -1
  66. package/dist/ui/assets/terminal-C6YPcJl_.js +1 -0
  67. package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-DQxm7DUM.js} +1 -1
  68. package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-Dj8ZhmWj.js} +1 -1
  69. package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-COLvs-Ho.js} +1 -1
  70. package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-q6iROeWE.js} +1 -1
  71. package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-Bm735CXN.js} +1 -1
  72. package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-DklBfOZ6.js} +1 -1
  73. package/dist/ui/assets/{zap-DT7cM7YS.js → zap-BEZNJ0i0.js} +1 -1
  74. package/dist/ui/index.html +8 -6
  75. package/dist/ui/logoblack.png +0 -0
  76. package/dist/ui/logocolor-dark.png +0 -0
  77. package/dist/ui/logocolorbg.png +0 -0
  78. package/dist/ui/logodoradobg.png +0 -0
  79. package/package.json +12 -8
  80. package/packages/cli/src/commands/doctor.ts +111 -0
  81. package/packages/cli/src/commands/onboard.ts +126 -59
  82. package/packages/cli/src/ui-bundle.generated.ts +9 -92
  83. package/packages/core/src/agent/acceptance-checks.ts +172 -0
  84. package/packages/core/src/agent/agent-catalog.ts +1 -37
  85. package/packages/core/src/agent/agent-loop.ts +21 -2
  86. package/packages/core/src/agent/catalog-selector.ts +0 -1
  87. package/packages/core/src/agent/compaction.ts +16 -1
  88. package/packages/core/src/agent/context-compiler.ts +3 -1
  89. package/packages/core/src/agent/conversation-store.ts +1 -1
  90. package/packages/core/src/agent/delegation-runtime.ts +1 -8
  91. package/packages/core/src/agent/goal-runner.ts +111 -32
  92. package/packages/core/src/agent/index.ts +1 -1
  93. package/packages/core/src/agent/llm-client.ts +34 -2
  94. package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
  95. package/packages/core/src/agent/llm-providers/interface.ts +13 -2
  96. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  97. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  98. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  99. package/packages/core/src/agent/proof-packet.ts +2 -11
  100. package/packages/core/src/agent/providers/index.ts +1 -1
  101. package/packages/core/src/agent/tool-selector.ts +25 -1
  102. package/packages/core/src/canvas/emitter.ts +0 -44
  103. package/packages/core/src/channels/manager.ts +117 -25
  104. package/packages/core/src/channels/whatsapp.ts +6 -1
  105. package/packages/core/src/config/loader.ts +13 -1
  106. package/packages/core/src/events/channel-narration.ts +150 -0
  107. package/packages/core/src/events/tool-narration.ts +62 -0
  108. package/packages/core/src/gateway/channel-notify.ts +11 -7
  109. package/packages/core/src/gateway/delegation-groups.ts +24 -11
  110. package/packages/core/src/gateway/helpers/narration.ts +4 -62
  111. package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
  112. package/packages/core/src/gateway/job-executors.ts +29 -67
  113. package/packages/core/src/gateway/resolver.ts +10 -2
  114. package/packages/core/src/gateway/routes/agents.ts +6 -6
  115. package/packages/core/src/gateway/routes/channels.ts +15 -1
  116. package/packages/core/src/gateway/routes/models.ts +69 -12
  117. package/packages/core/src/gateway/routes/providers.ts +110 -28
  118. package/packages/core/src/gateway/routes/setup.ts +63 -11
  119. package/packages/core/src/gateway/routes/system.ts +8 -5
  120. package/packages/core/src/gateway/routes/voice.ts +3 -0
  121. package/packages/core/src/gateway/server.ts +58 -28
  122. package/packages/core/src/gateway/webchat-turn.ts +29 -5
  123. package/packages/core/src/index.ts +1 -1
  124. package/packages/core/src/storage/bootstrap.ts +13 -9
  125. package/packages/core/src/storage/collections.ts +12 -46
  126. package/packages/core/src/storage/crypto.ts +147 -58
  127. package/packages/core/src/storage/hivedb.ts +9 -0
  128. package/packages/core/src/storage/model-id.ts +53 -0
  129. package/packages/core/src/storage/onboarding.ts +15 -4
  130. package/packages/core/src/storage/seed.ts +254 -138
  131. package/packages/core/src/storage/usage.ts +61 -123
  132. package/packages/core/src/tools/agents/index.ts +199 -27
  133. package/packages/core/src/tools/index.ts +2 -1
  134. package/packages/core/src/tools/web/browser-backend.ts +129 -0
  135. package/packages/core/src/tools/web/browser-service.ts +75 -35
  136. package/packages/core/src/tools/web/webview-backend.ts +412 -0
  137. package/packages/core/src/voice/index.ts +108 -17
  138. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +2 -1
  139. package/packages/skills/src/bundled-data.generated.ts +2 -23
  140. package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
  141. package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
  142. package/dist/ui/assets/arrow-left-0EBE7nsF.js +0 -1
  143. package/dist/ui/assets/arrow-right-5QIaph-z.js +0 -1
  144. package/dist/ui/assets/arrow-up-right-DQQCY007.js +0 -1
  145. package/dist/ui/assets/check-Dp6tzwax.js +0 -1
  146. package/dist/ui/assets/chevron-down-33N886NY.js +0 -1
  147. package/dist/ui/assets/chevron-left-C6itJXh3.js +0 -1
  148. package/dist/ui/assets/chevron-right-CFodBS-b.js +0 -1
  149. package/dist/ui/assets/chevron-up-BvSmyBEs.js +0 -1
  150. package/dist/ui/assets/circle-check-BJWNbLuF.js +0 -1
  151. package/dist/ui/assets/gauge-BRGwuN8G.js +0 -1
  152. package/dist/ui/assets/index-XoTT41Hr.css +0 -2
  153. package/dist/ui/assets/loader-circle-BhqRN2nO.js +0 -1
  154. package/dist/ui/assets/play-CfYDHD6h.js +0 -1
  155. package/dist/ui/assets/plus-C5BxJeOX.js +0 -1
  156. package/dist/ui/assets/search-rfBcmohK.js +0 -1
  157. package/dist/ui/assets/terminal-Bjfu-TkS.js +0 -1
  158. package/packages/core/src/agent/acceptance-verifier.ts +0 -300
  159. package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +0 -26
@@ -1,100 +1,68 @@
1
1
  import { col, nextId, bumpRollup } from "./hive";
2
- import type { UsageRecordDoc, UsageRollupDoc } from "./collections";
2
+ import type { ModelDoc, UsageRecordDoc, UsageRollupDoc } from "./collections";
3
3
  import { logger } from "../utils/logger";
4
4
 
5
5
  const log = logger.child("usage");
6
6
 
7
- // Precios en USD por millón de tokens (input / output)
8
- // Fuentes: docs.anthropic.com, openrouter.ai/api/v1/models, api-docs.deepseek.com, console.groq.com
9
- const MODEL_PRICING: Record<string, { inputPer1M: number; outputPer1M: number }> = {
10
- // ── Anthropic (fuente: docs.anthropic.com) ──
11
- "claude-opus-4-6": { inputPer1M: 5, outputPer1M: 25 },
12
- "claude-sonnet-4-6": { inputPer1M: 3, outputPer1M: 15 },
13
- "claude-haiku-4-5-20251001": { inputPer1M: 1, outputPer1M: 5 },
14
- "anthropic/claude-opus-4-6": { inputPer1M: 5, outputPer1M: 25 },
15
- "anthropic/claude-sonnet-4-6": { inputPer1M: 3, outputPer1M: 15 },
16
-
17
- // ── OpenAI (fuente: openrouter.ai/api/v1/models) ──
18
- "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10 },
19
- "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6 },
20
- "gpt-5.4": { inputPer1M: 2.5, outputPer1M: 15 },
21
- "gpt-5.4-pro": { inputPer1M: 30, outputPer1M: 180 },
22
- "gpt-5.3": { inputPer1M: 1.75, outputPer1M: 14 },
23
- "gpt-5.2": { inputPer1M: 1.75, outputPer1M: 14 },
24
- "o4-mini": { inputPer1M: 1.1, outputPer1M: 4.4 },
25
- "openai/gpt-5.4": { inputPer1M: 2.5, outputPer1M: 15 },
26
- "openai/gpt-5.4-pro": { inputPer1M: 30, outputPer1M: 180 },
27
- "openai/gpt-5.2": { inputPer1M: 1.75, outputPer1M: 14 },
28
- // Groq OSS (fuente: console.groq.com)
29
- "openai/gpt-oss-120b": { inputPer1M: 0.15, outputPer1M: 0.6 },
30
- "openai/gpt-oss-20b": { inputPer1M: 0.075, outputPer1M: 0.3 },
31
-
32
- // ── Google Gemini (fuente: openrouter.ai/api/v1/models) ──
33
- "gemini-3.1-pro-preview": { inputPer1M: 2, outputPer1M: 12 },
34
- "gemini-3.1-flash-lite-preview": { inputPer1M: 0.25, outputPer1M: 1.5 },
35
- "gemini-3-flash-preview": { inputPer1M: 0.5, outputPer1M: 3 },
36
- "gemini-2.5-pro": { inputPer1M: 1.25, outputPer1M: 10 },
37
- "gemini-2.5-flash": { inputPer1M: 0.15, outputPer1M: 0.6 },
38
- "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4 },
39
- "gemini-2.0-flash-lite": { inputPer1M: 0.075, outputPer1M: 0.3 },
40
- "google/gemini-3.1-pro-preview": { inputPer1M: 2, outputPer1M: 12 },
41
- "google/gemini-3.1-flash-lite-preview": { inputPer1M: 0.25, outputPer1M: 1.5 },
42
- "google/gemini-3-flash-preview": { inputPer1M: 0.5, outputPer1M: 3 },
43
- "google/gemini-2.5-flash": { inputPer1M: 0.15, outputPer1M: 0.6 },
44
-
45
- // ── Mistral (fuente: openrouter.ai/api/v1/models) ──
46
- "mistral-large-2512": { inputPer1M: 0.5, outputPer1M: 1.5 },
47
- "devstral-2512": { inputPer1M: 0.4, outputPer1M: 2 },
48
- "ministral-14b-2512": { inputPer1M: 0.2, outputPer1M: 0.2 },
49
- "ministral-8b-2512": { inputPer1M: 0.15, outputPer1M: 0.15 },
50
- "codestral-2508": { inputPer1M: 0.2, outputPer1M: 0.6 },
51
- "mistral-small-3.2-24b-instruct": { inputPer1M: 0.1, outputPer1M: 0.3 },
52
- "mistral-large-latest": { inputPer1M: 0.5, outputPer1M: 1.5 },
53
- "codestral-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
54
-
55
- // ── DeepSeek (fuente: api-docs.deepseek.com/quick_start/pricing) ──
56
- "deepseek-chat": { inputPer1M: 0.28, outputPer1M: 0.42 },
57
- "deepseek-reasoner": { inputPer1M: 0.28, outputPer1M: 0.42 },
58
- "deepseek/deepseek-v3.2": { inputPer1M: 0.25, outputPer1M: 0.4 },
59
- "deepseek/deepseek-r1:free": { inputPer1M: 0, outputPer1M: 0 },
60
-
61
- // ── Kimi / Moonshot (fuente: openrouter.ai/moonshotai) ──
62
- "kimi-k2.5": { inputPer1M: 0.45, outputPer1M: 2.2 },
63
- "kimi-k2": { inputPer1M: 0.45, outputPer1M: 2.2 },
64
- "moonshot-v1-8k": { inputPer1M: 1.67, outputPer1M: 1.67 },
65
- "moonshot-v1-32k": { inputPer1M: 3.33, outputPer1M: 3.33 },
66
- "moonshot-v1-128k": { inputPer1M: 8.33, outputPer1M: 8.33 },
67
- "moonshotai/kimi-k2.5": { inputPer1M: 0.45, outputPer1M: 2.2 },
68
- "moonshotai/kimi-k2-instruct-0905": { inputPer1M: 0.45, outputPer1M: 2.2 },
69
-
70
- // ── Meta Llama (vía OpenRouter) ──
71
- "meta-llama/llama-3.3-70b-instruct": { inputPer1M: 0.88, outputPer1M: 0.88 },
72
- "meta-llama/llama-4-maverick": { inputPer1M: 0.2, outputPer1M: 0.8 },
73
-
74
- // ── Qwen (vía OpenRouter) ──
75
- "qwen/qwen3.5-plus-02-15": { inputPer1M: 0.26, outputPer1M: 1.56 },
76
- "qwen/qwen3.5-flash-02-23": { inputPer1M: 0.1, outputPer1M: 0.4 },
77
- "qwen/qwen3-32b": { inputPer1M: 0, outputPer1M: 0 },
78
-
79
- // ── Groq (fuente: console.groq.com/docs/models) ──
80
- "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
81
- "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
82
- "groq/compound": { inputPer1M: 0, outputPer1M: 0 },
83
- "groq/compound-mini": { inputPer1M: 0, outputPer1M: 0 },
84
-
85
- // ── Ollama local = siempre free ──
86
- "qwen3:4b": { inputPer1M: 0, outputPer1M: 0 },
87
- "qwen3:8b": { inputPer1M: 0, outputPer1M: 0 },
88
- "qwen3:14b": { inputPer1M: 0, outputPer1M: 0 },
89
- "llama3.2:3b": { inputPer1M: 0, outputPer1M: 0 },
90
- "gemma3:9b": { inputPer1M: 0, outputPer1M: 0 },
91
- };
92
-
93
- function calculateCost(model: string, inputTokens: number, outputTokens: number): number {
94
- const pricing = MODEL_PRICING[model] || { inputPer1M: 0, outputPer1M: 0 };
95
- const inputCost = (inputTokens / 1_000_000) * pricing.inputPer1M;
96
- const outputCost = (outputTokens / 1_000_000) * pricing.outputPer1M;
97
- return inputCost + outputCost;
7
+ /**
8
+ * Costo de una llamada, en USD.
9
+ *
10
+ * El precio vive en la propia fila del modelo (`ModelDoc.input_per_1m` /
11
+ * `output_per_1m`), sembrada desde SEED_DATA.models. Antes había acá un mapa
12
+ * `MODEL_PRICING` hardcodeado en paralelo al catálogo: mantener dos listas en
13
+ * sincronía fallaba en silencio — un modelo sembrado sin entrada en el mapa
14
+ * costaba $0 sin avisar.
15
+ */
16
+
17
+ /** Precio por id de modelo. Se llena bajo demanda y lo invalida el re-seed. */
18
+ let pricingCache: Map<string, { input: number; output: number } | null> | null = null;
19
+
20
+ /** Llamar cuando el catálogo cambie, para que el próximo costo relea de la BD. */
21
+ export function invalidateModelPricingCache(): void {
22
+ pricingCache = null;
23
+ }
24
+
25
+ async function loadPricing(): Promise<Map<string, { input: number; output: number } | null>> {
26
+ if (pricingCache) return pricingCache;
27
+ const cache = new Map<string, { input: number; output: number } | null>();
28
+ try {
29
+ const modelsCol = await col<ModelDoc>("models");
30
+ for (const row of await modelsCol.scan({})) {
31
+ const { input_per_1m: i, output_per_1m: o } = row.doc;
32
+ cache.set(row.id, i == null && o == null ? null : { input: i ?? 0, output: o ?? 0 });
33
+ }
34
+ pricingCache = cache;
35
+ } catch {
36
+ // La BD puede no estar lista todavía (arranque temprano): no cachear el
37
+ // resultado vacío o el costo quedaría en 0 para toda la vida del proceso.
38
+ return cache;
39
+ }
40
+ return cache;
41
+ }
42
+
43
+ /** Modelos ya avisados, para no repetir el warning en cada llamada. */
44
+ const unpricedModels = new Set<string>();
45
+
46
+ export async function calculateCost(
47
+ provider: string,
48
+ model: string,
49
+ inputTokens: number,
50
+ outputTokens: number
51
+ ): Promise<number> {
52
+ const pricing = (await loadPricing()).get(model);
53
+
54
+ if (!pricing) {
55
+ // Sin esto un modelo sin tarifa aparece como $0.00 en el dashboard, que es
56
+ // indistinguible de un modelo realmente gratuito.
57
+ const key = `${provider}/${model}`;
58
+ if (!unpricedModels.has(key)) {
59
+ unpricedModels.add(key);
60
+ log.warn(`[usage] Sin tarifa para ${key} — su costo se contará como $0. Agregá inputPer1M/outputPer1M en SEED_DATA.models (storage/seed.ts).`);
61
+ }
62
+ return 0;
63
+ }
64
+
65
+ return (inputTokens / 1_000_000) * pricing.input + (outputTokens / 1_000_000) * pricing.output;
98
66
  }
99
67
 
100
68
  /** Hourly bucket key ("2026-07-09T14") — lexicographic order matches chronological order. */
@@ -213,7 +181,7 @@ export function recordUsage(options: {
213
181
  // Fire-and-forget to avoid blocking the LLM call path.
214
182
  Promise.resolve().then(async () => {
215
183
  try {
216
- const costUsd = calculateCost(options.model, options.inputTokens, options.outputTokens);
184
+ const costUsd = await calculateCost(options.provider, options.model, options.inputTokens, options.outputTokens);
217
185
  const now = Date.now();
218
186
 
219
187
  const id = await nextId("usageRecords");
@@ -337,36 +305,6 @@ export async function getUsageStats(hours: number = 24): Promise<UsageSummary> {
337
305
  };
338
306
  }
339
307
 
340
- /**
341
- * Get average cost per token for a model (input + output average)
342
- */
343
- export function getAverageTokenCost(model: string): number {
344
- // 1. Exact match
345
- let pricing = MODEL_PRICING[model];
346
-
347
- // 2. Try stripping a single provider prefix (e.g. "openrouter/moonshotai/kimi" → "moonshotai/kimi")
348
- if (!pricing) {
349
- const slashIdx = model.indexOf('/');
350
- if (slashIdx !== -1) {
351
- pricing = MODEL_PRICING[model.slice(slashIdx + 1)];
352
- }
353
- }
354
-
355
- // 3. Partial match — find any key whose name is contained in the model string
356
- if (!pricing) {
357
- for (const [key, p] of Object.entries(MODEL_PRICING)) {
358
- if (model.includes(key) || key.includes(model)) {
359
- pricing = p;
360
- break;
361
- }
362
- }
363
- }
364
-
365
- if (!pricing) return 0;
366
- // Average of input and output cost per token
367
- return (pricing.inputPer1M + pricing.outputPer1M) / 2 / 1_000_000;
368
- }
369
-
370
308
  /**
371
309
  * Record TOON savings for metrics tracking
372
310
  * This updates the usage_records table with complete TOON compression metrics
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Agents Tools - 14 tools
3
- *
2
+ * Agents Tools - 15 tools
3
+ *
4
4
  * @category agents
5
5
  */
6
6
 
@@ -14,11 +14,8 @@ import { agentBus } from "../../events/agent-bus.ts";
14
14
  import {
15
15
  emitDelegationStarted,
16
16
  emitDelegationFinished,
17
- emitVerificationStarted,
18
- emitVerificationFinished,
19
17
  emitWorkEvent,
20
18
  } from "../../canvas/emitter.ts";
21
- import { VERIFIER_AGENT_ID } from "../../agent/acceptance-verifier.ts";
22
19
 
23
20
  const log = logger.child("agents");
24
21
 
@@ -493,7 +490,7 @@ export const agentArchiveTool: Tool = {
493
490
 
494
491
  export const taskDelegateTool: Tool = {
495
492
  name: "task_delegate",
496
- description: "Delegate a bounded task to an existing worker_id (any `agents` row: catalog-seeded or agent_create-made). The delivery is independently verified before success is returned. mode=sync blocks the conversation until done; mode=async enqueues and frees the conversation immediately — the user is notified automatically in this same chat when the worker finishes. Prefer async unless you expect the result in a few seconds.",
493
+ description: "Delegate a bounded task to an existing worker_id (any `agents` row: catalog-seeded or agent_create-made). The delivery goes through deterministic acceptance checks (no LLM); you judge anything they don't cover in your closing turn, and use task_revise to send it back with feedback if it doesn't meet its criteria. mode=sync blocks the conversation until done; mode=async enqueues and frees the conversation immediately — the user is notified automatically in this same chat when the worker finishes. Prefer async unless you expect the result in a few seconds.",
497
494
  parameters: {
498
495
  type: "object",
499
496
  properties: {
@@ -721,43 +718,39 @@ export const taskDelegateTool: Tool = {
721
718
 
722
719
  agentBus.notifyTaskCompleted(agentId, worker.name, 0, taskName, "", result);
723
720
 
724
- // Verification now always runs, closing the old gap where a plain
725
- // worker_id delegation (agent_create) skipped it entirely in sync mode.
726
- const { verifyAgentDelivery } = await import("../../agent/acceptance-verifier.ts");
727
- emitVerificationStarted({ verifierId: VERIFIER_AGENT_ID, workerId: agentId, taskRef: syncDelegationRef, taskName });
728
- const verification = await verifyAgentDelivery({
729
- runId: `sync-${crypto.randomUUID()}`,
730
- executorAgentId: agentId,
721
+ // Deterministic acceptance checks now always run, closing the old gap
722
+ // where a plain worker_id delegation (agent_create) skipped them
723
+ // entirely in sync mode. No LLM call: the calling agent (usually the
724
+ // coordinator) judges the delivery itself in this same tool response.
725
+ const { runAcceptanceChecks, recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
726
+ const checks = await runAcceptanceChecks({
731
727
  objective: taskDescription,
732
728
  acceptance,
733
729
  delivery: result,
734
- mcpServerIds: prepared.mcpServerIds,
735
- mcpManager,
730
+ evidence: [result],
736
731
  });
737
- const verdict = JSON.parse(verification.verdict_json);
738
- emitVerificationFinished({ verifierId: VERIFIER_AGENT_ID, taskRef: syncDelegationRef });
739
- if (verification.status !== "verified") {
732
+ if (checks.status === "failed") {
733
+ await recordAgentOutcome(agentId, "harmful");
740
734
  emitWorkEvent({
741
735
  phase: "review_failed",
742
736
  taskRef: syncDelegationRef,
743
737
  taskName,
744
- actorId: VERIFIER_AGENT_ID,
738
+ actorId: parentAgentId || agentId,
745
739
  targetId: agentId,
746
- detail: verdict.summary || "La entrega no superó la verificación",
740
+ detail: checks.summary,
747
741
  });
748
742
  return {
749
743
  ok: false,
750
- status: verification.status,
751
- verification_id: verification.id,
752
- error: verdict.summary || "Independent verification did not authorize success.",
753
- retry_guidance: verdict.retry_guidance,
744
+ status: checks.status,
745
+ error: checks.summary,
754
746
  };
755
747
  }
748
+ await recordAgentOutcome(agentId, "helpful");
756
749
  emitWorkEvent({
757
750
  phase: "review_passed",
758
751
  taskRef: syncDelegationRef,
759
752
  taskName,
760
- actorId: VERIFIER_AGENT_ID,
753
+ actorId: parentAgentId || agentId,
761
754
  targetId: agentId,
762
755
  });
763
756
  emitWorkEvent({
@@ -771,7 +764,8 @@ export const taskDelegateTool: Tool = {
771
764
  ok: true,
772
765
  worker_id: agentId,
773
766
  worker_name: worker.name,
774
- verification_id: verification.id,
767
+ acceptance,
768
+ checks,
775
769
  result,
776
770
  };
777
771
  } catch (err) {
@@ -793,13 +787,190 @@ export const taskDelegateTool: Tool = {
793
787
  error: errorMessage,
794
788
  };
795
789
  } finally {
796
- emitVerificationFinished({ verifierId: VERIFIER_AGENT_ID, taskRef: syncDelegationRef });
797
790
  emitDelegationFinished({ workerId: agentId, taskRef: syncDelegationRef });
798
791
  await prepared.release();
799
792
  }
800
793
  },
801
794
  };
802
795
 
796
+ // ─── task_revise ─────────────────────────────────────────────────────────────
797
+
798
+ const MAX_TASK_REVISIONS = 2;
799
+
800
+ export const taskReviseTool: Tool = {
801
+ name: "task_revise",
802
+ description: "Send a completed or blocked delegated task back to its worker with concrete feedback, instead of reporting it as done. The worker resumes on the SAME thread — it keeps its prior context, so the feedback only needs to describe what's missing. Use this when a delivery doesn't meet its acceptance criteria and you can't fix it yourself.",
803
+ parameters: {
804
+ type: "object",
805
+ properties: {
806
+ task_id: { type: "string", description: "The task_id from task_delegate's result." },
807
+ feedback: { type: "string", description: "Concrete, actionable feedback: what's wrong and what the worker still needs to do." },
808
+ acceptance: {
809
+ type: "array",
810
+ description: "Updated acceptance criteria, if they need to change. Defaults to the original task's criteria.",
811
+ items: {
812
+ type: "object",
813
+ properties: {
814
+ id: { type: "string" },
815
+ description: { type: "string" },
816
+ checkTool: { type: "string" },
817
+ },
818
+ required: ["id", "description"],
819
+ },
820
+ },
821
+ },
822
+ required: ["task_id", "feedback"],
823
+ },
824
+ execute: async (params: Record<string, unknown>, config?: any) => {
825
+ const taskId = params.task_id as string | undefined;
826
+ const feedback = params.feedback as string | undefined;
827
+ if (!taskId) return { ok: false, error: "Provide task_id." };
828
+ if (!feedback || !feedback.trim()) return { ok: false, error: "Provide feedback describing what's missing." };
829
+
830
+ const parentAgentId = config?.configurable?.agent_id ?? "";
831
+ if (!parentAgentId) {
832
+ return { ok: false, error: "Caller identity is missing (config.configurable.agent_id)." };
833
+ }
834
+ const agentsCol = await col<AgentDoc>("agents");
835
+ const parentEntry = await agentsCol.get(parentAgentId);
836
+ if (!parentEntry) return { ok: false, error: `Caller agent not found: ${parentAgentId}` };
837
+ const parentProviderId = fromIndexable(parentEntry.doc.provider_id);
838
+ const parentModelId = fromIndexable(parentEntry.doc.model_id);
839
+
840
+ const tasksCol = await col<TaskDoc>("tasks");
841
+ const taskEntry = await tasksCol.get(taskId);
842
+ if (!taskEntry) return { ok: false, error: `Task not found: ${taskId}` };
843
+ const task = taskEntry.doc;
844
+ if (task.status !== "completed" && task.status !== "blocked") {
845
+ return { ok: false, error: `Task ${taskId} is "${task.status}" — only completed or blocked tasks can be revised.` };
846
+ }
847
+ if ((task.attempts ?? 0) >= MAX_TASK_REVISIONS) {
848
+ return { ok: false, error: `Task ${taskId} already used its ${MAX_TASK_REVISIONS} revision attempt(s). Fix it yourself or report the limit to the user.` };
849
+ }
850
+ if (!task.thread_id) {
851
+ return { ok: false, error: `Task ${taskId} has no thread_id — cannot resume its worker.` };
852
+ }
853
+
854
+ const agentId = fromIndexable(task.agent_id);
855
+ const workerEntry = agentId ? await agentsCol.get(agentId) : null;
856
+ if (!workerEntry) return { ok: false, error: `Worker not found for task ${taskId}: ${agentId}` };
857
+ const worker = workerEntry.doc;
858
+ if (!worker.enabled) return { ok: false, error: `Worker is disabled: ${worker.name}` };
859
+
860
+ const { createRun, getRun, deserializeAcceptance } = await import("../../agent/run-store.ts");
861
+ const { getDurableQueue } = await import("../../gateway/durable-queue.ts");
862
+ const { updateDoc } = await import("../../storage/hive.ts");
863
+
864
+ const previousRun = task.run_id ? await getRun(task.run_id) : null;
865
+ const previousAcceptance = previousRun ? deserializeAcceptance(previousRun) : null;
866
+ const acceptance = (params.acceptance as AcceptanceCriterion[] | undefined) ?? previousAcceptance ?? [{ id: "objective", description: task.description ?? feedback }];
867
+
868
+ try {
869
+ const run = await createRun({
870
+ thread_id: task.thread_id,
871
+ agent_id: agentId!,
872
+ user_id: config?.configurable?.user_id ?? "",
873
+ channel: config?.configurable?.channel ?? null,
874
+ kind: "worker",
875
+ max_iterations: worker.max_iterations || 10,
876
+ resume_policy: "resume",
877
+ acceptance,
878
+ catalog_agent_id: worker.source === "catalog" ? agentId! : undefined,
879
+ });
880
+
881
+ const turnId = config?.configurable?.turn_id as string | undefined;
882
+ if (turnId) {
883
+ const { registerDelegatedTask } = await import("../../gateway/delegation-groups.ts");
884
+ await registerDelegatedTask({
885
+ turnId,
886
+ taskId,
887
+ threadId: config?.configurable?.thread_id ?? "",
888
+ channel: config?.configurable?.channel,
889
+ userId: config?.configurable?.user_id,
890
+ sessionId: config?.configurable?.session_id,
891
+ coordinatorAgentId: parentAgentId,
892
+ });
893
+ }
894
+
895
+ const queue = getDurableQueue();
896
+ const job = await queue.enqueue({
897
+ lane: `task:${taskId}`,
898
+ type: "worker_task",
899
+ run_id: run.id,
900
+ payload: {
901
+ workerId: agentId,
902
+ taskDescription: `${task.description ?? ""}\n\nCORRECCIÓN SOLICITADA: ${feedback}`,
903
+ taskName: task.name,
904
+ taskId,
905
+ acceptance,
906
+ parentAgentId,
907
+ parentProviderId,
908
+ parentModelId,
909
+ userId: config?.configurable?.user_id ?? "",
910
+ workspace: config?.configurable?.workspace ?? null,
911
+ originThreadId: config?.configurable?.thread_id ?? null,
912
+ originChannel: config?.configurable?.channel ?? null,
913
+ originSessionId: config?.configurable?.session_id ?? null,
914
+ turnId: turnId ?? null,
915
+ revision: true,
916
+ },
917
+ });
918
+
919
+ await updateDoc<TaskDoc>("tasks", taskId, {
920
+ status: "pending",
921
+ error: null,
922
+ job_id: job.id,
923
+ run_id: run.id,
924
+ attempts: (task.attempts ?? 0) + 1,
925
+ delegation_group_id: turnId ?? task.delegation_group_id ?? null,
926
+ updated_at: Date.now(),
927
+ } as Partial<TaskDoc>);
928
+
929
+ const { recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
930
+ await recordAgentOutcome(agentId, "harmful");
931
+
932
+ emitWorkEvent({
933
+ phase: "review_failed",
934
+ taskRef: taskId,
935
+ taskName: task.name,
936
+ actorId: parentAgentId,
937
+ targetId: agentId!,
938
+ detail: feedback,
939
+ });
940
+
941
+ if (turnId) {
942
+ const { publishNarration } = await import("../../events/narration.ts");
943
+ await publishNarration({
944
+ turnId,
945
+ threadId: config?.configurable?.thread_id ?? "",
946
+ channel: config?.configurable?.channel,
947
+ userId: config?.configurable?.user_id,
948
+ sessionId: config?.configurable?.session_id,
949
+ agentId: agentId!,
950
+ agentName: worker.name,
951
+ kind: "delegated",
952
+ status: "queued",
953
+ label: `Devolví “${task.name}” a ${worker.name} con correcciones`,
954
+ dedupeKey: `revised:${taskId}:${(task.attempts ?? 0) + 1}`,
955
+ });
956
+ }
957
+
958
+ return {
959
+ ok: true,
960
+ task_id: taskId,
961
+ job_id: job.id,
962
+ run_id: run.id,
963
+ worker_id: agentId,
964
+ attempts: (task.attempts ?? 0) + 1,
965
+ status: "queued",
966
+ message: `Revision enqueued (async). Use task_status with task_id="${taskId}" to check it.`,
967
+ };
968
+ } catch (err) {
969
+ return { ok: false, error: `Task revision failed: ${(err as Error).message}` };
970
+ }
971
+ },
972
+ };
973
+
803
974
  // ─── task_list ──────────────────────────────────────────────────────────────
804
975
 
805
976
  export const taskListTool: Tool = {
@@ -1044,6 +1215,7 @@ export function createTools(): Tool[] {
1044
1215
  agentFindTool,
1045
1216
  agentArchiveTool,
1046
1217
  taskDelegateTool,
1218
+ taskReviseTool,
1047
1219
  taskListTool,
1048
1220
  taskStatusTool,
1049
1221
  busPublishTool,
@@ -20,7 +20,7 @@ import * as cron from "./cron/index.ts";
20
20
  // CLI (1)
21
21
  import * as cli from "./cli/index.ts";
22
22
 
23
- // Agents (14)
23
+ // Agents (15)
24
24
  import * as agents from "./agents/index.ts";
25
25
 
26
26
  // A2UI (4)
@@ -151,6 +151,7 @@ export {
151
151
  agentFindTool,
152
152
  agentArchiveTool,
153
153
  taskDelegateTool,
154
+ taskReviseTool,
154
155
  taskListTool,
155
156
  taskStatusTool,
156
157
  busPublishTool,
@@ -0,0 +1,129 @@
1
+ /**
2
+ * BrowserBackend — el contrato que consumen las browser tools.
3
+ *
4
+ * Hay dos implementaciones con perfiles opuestos:
5
+ *
6
+ * - `AgentBrowserBackend` (browser-service.ts): habla con el CLI de
7
+ * agent-browser por subproceso. Maneja Chrome de verdad, corre headless y
8
+ * por lo tanto sirve en Docker y en un servidor sin display. El costo es
9
+ * un `Bun.spawn` por operación —medido en ~68 ms de piso— más una
10
+ * instalación diferida de ~75 MB y la descarga de Chrome.
11
+ *
12
+ * - `WebViewBackend` (webview-backend.ts): usa `Bun.WebView`, in-process.
13
+ * Sin instalación, sin subprocesos, ~0.25 ms por `evaluate`. Necesita un
14
+ * entorno gráfico (WebKitGTK en Linux, WebKit del sistema en macOS), así
15
+ * que no sirve headless.
16
+ *
17
+ * El default sigue siendo agent-browser: es el único de los dos que funciona
18
+ * donde suele correr el gateway. WebView se elige explícitamente.
19
+ */
20
+
21
+ export interface ScreenshotOptions {
22
+ encoding?: "blob" | "buffer" | "base64" | "shmem";
23
+ format?: "png" | "jpeg" | "webp";
24
+ quality?: number;
25
+ clip?: { x: number; y: number; width: number; height: number; scale: number };
26
+ }
27
+
28
+ export interface SnapshotOptions {
29
+ /** Colapsa nodos sin nombre accesible y recorta el texto largo. Default: true. */
30
+ compact?: boolean;
31
+ /** Profundidad máxima del árbol. */
32
+ depth?: number;
33
+ /** Sólo elementos accionables (links, botones, inputs...). */
34
+ interactiveOnly?: boolean;
35
+ }
36
+
37
+ /**
38
+ * La superficie que las tools de `tools/web/` realmente usan. Se mantuvo
39
+ * deliberadamente chica: cualquier método que se agregue acá hay que
40
+ * implementarlo en los dos backends.
41
+ */
42
+ export interface BrowserBackend {
43
+ readonly url: string;
44
+ readonly title: string;
45
+ readonly loading: boolean;
46
+
47
+ navigate(url: string): Promise<void>;
48
+ evaluate<T = unknown>(script: string): Promise<T>;
49
+ screenshot(options?: ScreenshotOptions): Promise<string>;
50
+ /** Árbol de accesibilidad en texto — lo que ve el modelo en vez del HTML crudo. */
51
+ snapshot(options?: SnapshotOptions): Promise<string>;
52
+ click(selector: string, options?: Record<string, unknown>): Promise<void>;
53
+ type(text: string): Promise<void>;
54
+ typeIn(selector: string, text: string): Promise<void>;
55
+ fill(selector: string, text: string): Promise<void>;
56
+ press(key: string, options?: { modifiers?: string[] }): Promise<void>;
57
+ scroll(dx: number, dy: number): Promise<void>;
58
+ scrollTo(selector: string, options?: { behavior?: "smooth" | "instant" }): Promise<void>;
59
+ back(): Promise<void>;
60
+ forward(): Promise<void>;
61
+ reload(): Promise<void>;
62
+ resize(width: number, height: number): Promise<void>;
63
+ /** Captura de un elemento puntual; el backend puede recortar sobre el viewport. */
64
+ screenshotElement(selector: string): Promise<string>;
65
+ close(): void;
66
+ }
67
+
68
+ export type BrowserBackendKind = "agent-browser" | "webview";
69
+
70
+ /** `auto` resuelve a webview si el runtime lo soporta; si no, agent-browser. */
71
+ export type BrowserBackendPreference = BrowserBackendKind | "auto";
72
+
73
+ /** Motor que usa `Bun.WebView` por debajo. */
74
+ export type WebViewEngine = "webkit" | "chrome";
75
+
76
+ const CHROME_PATHS = [
77
+ "/usr/bin/google-chrome",
78
+ "/usr/bin/google-chrome-stable",
79
+ "/usr/bin/chromium",
80
+ "/usr/bin/chromium-browser",
81
+ "/snap/bin/chromium",
82
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
83
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
84
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
85
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
86
+ ];
87
+
88
+ /** Chrome instalado en el sistema — `Bun.WebView` con motor chrome lo necesita. */
89
+ export function findChrome(): string | null {
90
+ if (process.env.BUN_CHROME_PATH) return process.env.BUN_CHROME_PATH;
91
+ const { existsSync } = require("node:fs") as typeof import("node:fs");
92
+ for (const candidate of CHROME_PATHS) {
93
+ if (existsSync(candidate)) return candidate;
94
+ }
95
+ // Último recurso: lo que esté en el PATH del usuario.
96
+ const home = process.env.HOME;
97
+ if (home) {
98
+ for (const name of ["google-chrome", "chromium"]) {
99
+ const local = `${home}/.local/bin/${name}`;
100
+ if (existsSync(local)) return local;
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+
106
+ /**
107
+ * Motor a usar. WebKit no tiene dependencias externas pero sólo existe en macOS;
108
+ * Chrome corre headless en cualquier lado —incluido Docker— siempre que el
109
+ * binario esté instalado.
110
+ */
111
+ export function resolveWebViewEngine(): WebViewEngine | null {
112
+ if (process.platform === "darwin") return "webkit";
113
+ return findChrome() ? "chrome" : null;
114
+ }
115
+
116
+ /** `Bun.WebView` existe desde Bun 1.3; además hace falta un motor utilizable. */
117
+ export function isWebViewSupported(): boolean {
118
+ if (typeof (globalThis as { Bun?: { WebView?: unknown } }).Bun?.WebView !== "function") return false;
119
+ return resolveWebViewEngine() !== null;
120
+ }
121
+
122
+ export function resolveBackendKind(
123
+ preference: BrowserBackendPreference | undefined,
124
+ ): BrowserBackendKind {
125
+ const wanted = process.env.HIVE_BROWSER_BACKEND ?? preference ?? "agent-browser";
126
+ if (wanted === "webview") return "webview";
127
+ if (wanted === "auto") return isWebViewSupported() ? "webview" : "agent-browser";
128
+ return "agent-browser";
129
+ }