@johpaz/hive-agents 1.0.0 → 1.0.2

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 (165) hide show
  1. package/README.md +25 -11
  2. package/dist/hive.js +22498 -6889
  3. package/dist/tool-worker.js +6 -2
  4. package/dist/ui/assets/A2UIPage-BRpjnMss.js +8 -0
  5. package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-ASjKD7Js.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-bqJ-MS40.js} +1 -1
  7. package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +1 -0
  8. package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-BIpLG0V6.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-dRckcgrN.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-BX_hPtiN.js} +2 -2
  11. package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-KMaMaFf4.js} +2 -2
  12. package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-Zchu-f16.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-6Po7_T2u.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-qrpYGVD-.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-C8ny_pxu.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BYwLMTCl.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BXwjLfap.js} +1 -1
  19. package/dist/ui/assets/SettingsPage-DD7GKtS6.js +9 -0
  20. package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-D7YX2io-.js} +1 -1
  21. package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-C3cgimxd.js} +1 -1
  22. package/dist/ui/assets/{activity-CQuPevhB.js → activity-DZKL7dg4.js} +1 -1
  23. package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-DuGs07XP.js} +1 -1
  24. package/dist/ui/assets/arrow-left-12JaXVoH.js +1 -0
  25. package/dist/ui/assets/arrow-right-Dbui5p0d.js +1 -0
  26. package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +1 -0
  27. package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-CkDsc4OJ.js} +1 -1
  28. package/dist/ui/assets/check-DxOMIDcl.js +1 -0
  29. package/dist/ui/assets/chevron-down-CObv-xyx.js +1 -0
  30. package/dist/ui/assets/chevron-left-C0mqwhLU.js +1 -0
  31. package/dist/ui/assets/chevron-right-jCt1h8Kw.js +1 -0
  32. package/dist/ui/assets/chevron-up-DX_5iw7O.js +1 -0
  33. package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-BkP6x0zQ.js} +1 -1
  34. package/dist/ui/assets/circle-check-CXC2AiMS.js +1 -0
  35. package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-h4OJiHV3.js} +1 -1
  36. package/dist/ui/assets/{copy-33tZrzc9.js → copy-BtpYEEvV.js} +1 -1
  37. package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-CO1WrPJc.js} +1 -1
  38. package/dist/ui/assets/{download-CiQqqXyz.js → download-aPuVaZik.js} +1 -1
  39. package/dist/ui/assets/{earth-DCvN7ynm.js → earth-sc8YJMc0.js} +1 -1
  40. package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-DEBZJGzY.js} +1 -1
  41. package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-D_C_678M.js} +1 -1
  42. package/dist/ui/assets/{eye-C8sKSSkg.js → eye-BfN613fx.js} +1 -1
  43. package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-Bth5pPZX.js} +1 -1
  44. package/dist/ui/assets/gauge-DypSzSOE.js +1 -0
  45. package/dist/ui/assets/{history-BtTD1kDo.js → history-njH_sPSo.js} +1 -1
  46. package/dist/ui/assets/{index-Bejlp-R1.js → index-D-9yCvjP.js} +4 -4
  47. package/dist/ui/assets/index-wML8DaUo.css +2 -0
  48. package/dist/ui/assets/{info-mpk1tsNC.js → info-Def2ZFeP.js} +1 -1
  49. package/dist/ui/assets/{key-CoQ0qtXt.js → key-D8bkDl83.js} +1 -1
  50. package/dist/ui/assets/loader-circle-wLVzSdML.js +1 -0
  51. package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-Cdopbw1b.js} +1 -1
  52. package/dist/ui/assets/{mail-BG0RYSkL.js → mail-BQ_YA9_b.js} +1 -1
  53. package/dist/ui/assets/{pause-Cme88_9s.js → pause-CvS_LzKx.js} +1 -1
  54. package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-C3tPvnCk.js} +1 -1
  55. package/dist/ui/assets/play-C-oR-PMH.js +1 -0
  56. package/dist/ui/assets/plus-CF9No2td.js +1 -0
  57. package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-dsaiFxuT.js} +1 -1
  58. package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BmYQwOhh.js} +1 -1
  59. package/dist/ui/assets/search-CTONpTyl.js +1 -0
  60. package/dist/ui/assets/{select-BhbW0stK.js → select-BfRyBbi9.js} +1 -1
  61. package/dist/ui/assets/{send-D6whYpw-.js → send-C3o2wpLi.js} +1 -1
  62. package/dist/ui/assets/{settings-BX6q3MGB.js → settings-DEpdBuf2.js} +1 -1
  63. package/dist/ui/assets/{shield-BnGyu1xf.js → shield-gbUkSqfi.js} +1 -1
  64. package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-Ccd1JZ3s.js} +1 -1
  65. package/dist/ui/assets/{square-ju5H8nrT.js → square-BrwQ6Mun.js} +1 -1
  66. package/dist/ui/assets/terminal-DP9j3HjM.js +1 -0
  67. package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-CfCs7RhJ.js} +1 -1
  68. package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-C3lWSnRr.js} +1 -1
  69. package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-D3s2U82M.js} +1 -1
  70. package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-B3rT_xU9.js} +1 -1
  71. package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-D2h9cyml.js} +1 -1
  72. package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-CGQECzu2.js} +1 -1
  73. package/dist/ui/assets/{zap-DT7cM7YS.js → zap-B1azpiE7.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/index.ts +23 -17
  83. package/packages/cli/src/ui-bundle.generated.ts +9 -92
  84. package/packages/core/src/agent/acceptance-checks.ts +172 -0
  85. package/packages/core/src/agent/agent-catalog.ts +1 -37
  86. package/packages/core/src/agent/agent-loop.ts +21 -2
  87. package/packages/core/src/agent/catalog-selector.ts +0 -1
  88. package/packages/core/src/agent/compaction.ts +16 -1
  89. package/packages/core/src/agent/context-compiler.ts +3 -1
  90. package/packages/core/src/agent/conversation-store.ts +1 -1
  91. package/packages/core/src/agent/delegation-runtime.ts +1 -8
  92. package/packages/core/src/agent/goal-runner.ts +111 -32
  93. package/packages/core/src/agent/index.ts +1 -1
  94. package/packages/core/src/agent/llm-client.ts +34 -2
  95. package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
  96. package/packages/core/src/agent/llm-providers/interface.ts +13 -2
  97. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  98. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  99. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  100. package/packages/core/src/agent/proof-packet.ts +2 -11
  101. package/packages/core/src/agent/providers/index.ts +1 -1
  102. package/packages/core/src/agent/tool-selector.ts +25 -1
  103. package/packages/core/src/canvas/canvas-manager.ts +36 -7
  104. package/packages/core/src/canvas/emitter.ts +0 -44
  105. package/packages/core/src/channels/manager.ts +117 -25
  106. package/packages/core/src/channels/whatsapp.ts +6 -1
  107. package/packages/core/src/config/loader.ts +13 -1
  108. package/packages/core/src/events/channel-narration.ts +150 -0
  109. package/packages/core/src/events/tool-narration.ts +62 -0
  110. package/packages/core/src/gateway/channel-notify.ts +11 -7
  111. package/packages/core/src/gateway/delegation-groups.ts +24 -11
  112. package/packages/core/src/gateway/helpers/narration.ts +4 -62
  113. package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
  114. package/packages/core/src/gateway/job-executors.ts +29 -67
  115. package/packages/core/src/gateway/resolver.ts +10 -2
  116. package/packages/core/src/gateway/routes/a2ui.ts +43 -0
  117. package/packages/core/src/gateway/routes/agents.ts +6 -6
  118. package/packages/core/src/gateway/routes/channels.ts +15 -1
  119. package/packages/core/src/gateway/routes/models.ts +69 -12
  120. package/packages/core/src/gateway/routes/providers.ts +110 -28
  121. package/packages/core/src/gateway/routes/runtime.ts +58 -0
  122. package/packages/core/src/gateway/routes/setup.ts +161 -90
  123. package/packages/core/src/gateway/routes/system.ts +8 -5
  124. package/packages/core/src/gateway/routes/voice.ts +3 -0
  125. package/packages/core/src/gateway/server.ts +74 -28
  126. package/packages/core/src/gateway/webchat-turn.ts +29 -5
  127. package/packages/core/src/index.ts +1 -1
  128. package/packages/core/src/storage/bootstrap.ts +13 -9
  129. package/packages/core/src/storage/collections.ts +12 -46
  130. package/packages/core/src/storage/crypto.ts +147 -58
  131. package/packages/core/src/storage/hivedb.ts +9 -0
  132. package/packages/core/src/storage/model-id.ts +53 -0
  133. package/packages/core/src/storage/onboarding.ts +36 -9
  134. package/packages/core/src/storage/seed.ts +283 -138
  135. package/packages/core/src/storage/usage.ts +61 -123
  136. package/packages/core/src/tools/agents/index.ts +199 -27
  137. package/packages/core/src/tools/index.ts +2 -1
  138. package/packages/core/src/tools/web/browser-backend.ts +129 -0
  139. package/packages/core/src/tools/web/browser-service.ts +75 -35
  140. package/packages/core/src/tools/web/webview-backend.ts +412 -0
  141. package/packages/core/src/voice/index.ts +108 -17
  142. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +2 -1
  143. package/packages/skills/src/bundled-data.generated.ts +2 -23
  144. package/dist/ui/assets/A2UIPage-D4nUFe5q.js +0 -8
  145. package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
  146. package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
  147. package/dist/ui/assets/SettingsPage-B6FTSkOn.js +0 -9
  148. package/dist/ui/assets/arrow-left-0EBE7nsF.js +0 -1
  149. package/dist/ui/assets/arrow-right-5QIaph-z.js +0 -1
  150. package/dist/ui/assets/arrow-up-right-DQQCY007.js +0 -1
  151. package/dist/ui/assets/check-Dp6tzwax.js +0 -1
  152. package/dist/ui/assets/chevron-down-33N886NY.js +0 -1
  153. package/dist/ui/assets/chevron-left-C6itJXh3.js +0 -1
  154. package/dist/ui/assets/chevron-right-CFodBS-b.js +0 -1
  155. package/dist/ui/assets/chevron-up-BvSmyBEs.js +0 -1
  156. package/dist/ui/assets/circle-check-BJWNbLuF.js +0 -1
  157. package/dist/ui/assets/gauge-BRGwuN8G.js +0 -1
  158. package/dist/ui/assets/index-XoTT41Hr.css +0 -2
  159. package/dist/ui/assets/loader-circle-BhqRN2nO.js +0 -1
  160. package/dist/ui/assets/play-CfYDHD6h.js +0 -1
  161. package/dist/ui/assets/plus-C5BxJeOX.js +0 -1
  162. package/dist/ui/assets/search-rfBcmohK.js +0 -1
  163. package/dist/ui/assets/terminal-Bjfu-TkS.js +0 -1
  164. package/packages/core/src/agent/acceptance-verifier.ts +0 -300
  165. package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +0 -26
@@ -0,0 +1,150 @@
1
+ // ─── Narration delivery policy for messaging channels ─────────────────────────
2
+ // WebChat renders narration as ephemeral, collapsible "process" widgets. A
3
+ // messaging channel (WhatsApp, Telegram, Slack, Discord) has no such surface:
4
+ // every narration event becomes a permanent chat message. Without a filter a
5
+ // single turn with a few tools and two delegated workers produces dozens of
6
+ // messages before the actual answer — noise for the user and a rate-limit /
7
+ // ban risk on WhatsApp. This module decides what reaches those channels.
8
+
9
+ import { col } from "../storage/hive";
10
+ import type { ChannelDoc, NarrationEventDoc } from "../storage/collections";
11
+ import { logger } from "../utils/logger";
12
+
13
+ const log = logger.child("narration:channel");
14
+
15
+ /** `off` = silent, `milestones` = delegation lifecycle only, `all` = + per-tool steps. */
16
+ export type NarrationMode = "off" | "milestones" | "all";
17
+
18
+ export const DEFAULT_NARRATION_MODE: NarrationMode = "milestones";
19
+
20
+ /** Legacy `step_delivery_mode` values predate this feature — map them forward. */
21
+ function coerceMode(raw: string | null | undefined): NarrationMode {
22
+ switch (raw) {
23
+ case "off":
24
+ case "milestones":
25
+ case "all":
26
+ return raw;
27
+ // "new_messages" was the original (never-read) default.
28
+ case "new_messages":
29
+ return DEFAULT_NARRATION_MODE;
30
+ default:
31
+ return DEFAULT_NARRATION_MODE;
32
+ }
33
+ }
34
+
35
+ /** High-level events: what the user actually cares about seeing in a chat. */
36
+ const MILESTONE_KINDS = new Set<NarrationEventDoc["kind"]>([
37
+ "delegated",
38
+ "worker_started",
39
+ "verified",
40
+ "failed",
41
+ "group_ready",
42
+ ]);
43
+
44
+ const KIND_PREFIX: Record<NarrationEventDoc["kind"], string> = {
45
+ delegated: "📋",
46
+ worker_started: "▶️",
47
+ tool_call: "⚙️",
48
+ tool_result: "⚠️",
49
+ verified: "✅",
50
+ failed: "❌",
51
+ group_ready: "📝",
52
+ };
53
+
54
+ const DETAIL_MAX_CHARS = 200;
55
+
56
+ // ─── Mode lookup (cached) ─────────────────────────────────────────────────────
57
+ // Resolved per channel *type* because narration events only carry the type, not
58
+ // the account id. Short TTL so a settings change takes effect without a restart.
59
+
60
+ const MODE_CACHE_TTL_MS = 30_000;
61
+ const modeCache = new Map<string, { mode: NarrationMode; expiresAt: number }>();
62
+
63
+ export function invalidateNarrationModeCache(channelType?: string): void {
64
+ if (channelType) modeCache.delete(channelType);
65
+ else modeCache.clear();
66
+ }
67
+
68
+ export async function resolveNarrationMode(channelType: string): Promise<NarrationMode> {
69
+ const cached = modeCache.get(channelType);
70
+ if (cached && cached.expiresAt > Date.now()) return cached.mode;
71
+
72
+ let mode = DEFAULT_NARRATION_MODE;
73
+ try {
74
+ const channels = await col<ChannelDoc>("channels");
75
+ const row = (await channels.scan({})).find((e) => e.doc.type === channelType);
76
+ mode = coerceMode(row?.doc.step_delivery_mode);
77
+ } catch (error) {
78
+ log.debug(`Could not resolve narration mode for ${channelType}: ${(error as Error).message}`);
79
+ }
80
+
81
+ modeCache.set(channelType, { mode, expiresAt: Date.now() + MODE_CACHE_TTL_MS });
82
+ return mode;
83
+ }
84
+
85
+ // ─── Filtering ────────────────────────────────────────────────────────────────
86
+
87
+ export function shouldDeliverToChannel(event: NarrationEventDoc, mode: NarrationMode): boolean {
88
+ if (mode === "off") return false;
89
+ if (MILESTONE_KINDS.has(event.kind)) return true;
90
+ if (mode !== "all") return false;
91
+ // Even in `all`, a successful tool_result only restates the tool_call that
92
+ // preceded it. Errors are the part worth surfacing.
93
+ if (event.kind === "tool_result") return event.status === "error";
94
+ return true;
95
+ }
96
+
97
+ // ─── Formatting ───────────────────────────────────────────────────────────────
98
+
99
+ /** Collapses whitespace and trims — raw error details carry stacks and paths. */
100
+ function compactDetail(detail: string): string {
101
+ const flat = detail.replace(/\s+/g, " ").trim();
102
+ if (flat.length <= DETAIL_MAX_CHARS) return flat;
103
+ return `${flat.slice(0, DETAIL_MAX_CHARS - 1)}…`;
104
+ }
105
+
106
+ export function formatNarrationForChannel(event: NarrationEventDoc): string {
107
+ const prefix = KIND_PREFIX[event.kind] ?? "•";
108
+ const detail = event.detail ? compactDetail(event.detail) : "";
109
+ return detail ? `${prefix} ${event.label}\n${detail}` : `${prefix} ${event.label}`;
110
+ }
111
+
112
+ // ─── Ordered, off-critical-path delivery ──────────────────────────────────────
113
+ // `publishNarration` awaits the delivery adapter, so sending inline would put a
114
+ // round-trip to the channel's servers inside the agent loop for every event.
115
+ // Each conversation gets its own promise chain: the agent loop is never blocked,
116
+ // and messages still arrive in the order they were produced.
117
+
118
+ const sendQueues = new Map<string, Promise<void>>();
119
+
120
+ export function enqueueChannelNarration(
121
+ key: string,
122
+ send: () => Promise<void>,
123
+ ): void {
124
+ const previous = sendQueues.get(key) ?? Promise.resolve();
125
+ const next = previous
126
+ .then(send)
127
+ .catch((error: Error) => {
128
+ log.warn(`Narration delivery failed for ${key}: ${error.message}`);
129
+ })
130
+ .finally(() => {
131
+ // Drop the entry once this send is the last one queued, so the map does
132
+ // not grow with one retained promise per conversation seen.
133
+ if (sendQueues.get(key) === next) sendQueues.delete(key);
134
+ });
135
+ sendQueues.set(key, next);
136
+ }
137
+
138
+ /**
139
+ * Resolves once the narration queued for one conversation has been sent. Call
140
+ * before sending a turn's final answer so it cannot overtake pending progress
141
+ * messages, which would show the user the outcome before the steps.
142
+ */
143
+ export async function awaitChannelNarration(key: string): Promise<void> {
144
+ await (sendQueues.get(key) ?? Promise.resolve());
145
+ }
146
+
147
+ /** Test/shutdown helper: resolves once every queued narration has been sent. */
148
+ export async function flushChannelNarration(): Promise<void> {
149
+ await Promise.allSettled([...sendQueues.values()]);
150
+ }
@@ -0,0 +1,62 @@
1
+ // ─── Tool narration map ───────────────────────────────────────────────────────
2
+ // Maps tool name prefixes/exact names to human-readable Spanish narrations.
3
+ // Shown to the user while the agent executes a tool.
4
+ const TOOL_NARRATIONS: Record<string, string> = {
5
+ // Web
6
+ web_search: "Buscando en la web...",
7
+ web_fetch: "Leyendo página web...",
8
+ // Files
9
+ read: "Leyendo archivo...",
10
+ write: "Escribiendo archivo...",
11
+ edit: "Editando archivo...",
12
+ exec: "Ejecutando comando...",
13
+ // Cron
14
+ "cron.create": "Programando tarea...",
15
+ "cron.list": "Consultando tareas programadas...",
16
+ "cron.update": "Actualizando tarea programada...",
17
+ "cron.delete": "Eliminando tarea programada...",
18
+ "cron.pause": "Pausando tarea programada...",
19
+ "cron.resume": "Reanudando tarea programada...",
20
+ "cron.trigger": "Ejecutando tarea ahora...",
21
+ "cron.history": "Consultando historial...",
22
+ // Agents
23
+ agent_create: "Creando agente worker...",
24
+ agent_find: "Buscando agente disponible...",
25
+ agent_archive: "Archivando agente...",
26
+ get_available_models: "Consultando modelos disponibles...",
27
+ task_delegate: "Delegando tarea a un agente...",
28
+ task_list: "Listando tareas en ejecución...",
29
+ task_status: "Consultando estado de la tarea...",
30
+ bus_publish: "Coordinando con otro agente...",
31
+ bus_read: "Leyendo mensajes de los agentes...",
32
+ // Discovery
33
+ search_knowledge: "Buscando capacidades disponibles...",
34
+ // Memory
35
+ save_note: "Guardando nota...",
36
+ memory_write: "Guardando en memoria...",
37
+ memory_read: "Leyendo memoria...",
38
+ memory_search: "Buscando en memoria...",
39
+ memory_delete: "Eliminando de memoria...",
40
+ memory_list: "Listando notas...",
41
+ // Browser
42
+ browser_navigate: "Navegando a la página...",
43
+ browser_click: "Haciendo clic...",
44
+ browser_type: "Escribiendo en la página...",
45
+ browser_screenshot: "Tomando captura de pantalla...",
46
+ browser_extract: "Extrayendo información de la página...",
47
+ // Canvas
48
+ canvas_add_node: "Actualizando canvas...",
49
+ canvas_update: "Actualizando canvas...",
50
+ // Notify
51
+ notify: "Enviando notificación...",
52
+ report_progress: "Reportando progreso...",
53
+ }
54
+
55
+ export function getNarration(toolName: string): string {
56
+ if (TOOL_NARRATIONS[toolName]) return TOOL_NARRATIONS[toolName]
57
+ // Prefix matching for MCP tools like "github__create_pr" → "Ejecutando github..."
58
+ const prefix = toolName.split("__")[0]
59
+ if (prefix && prefix !== toolName) return `Ejecutando ${prefix}...`
60
+ // Fallback
61
+ return `Ejecutando ${toolName.replace(/_/g, " ")}...`
62
+ }
@@ -19,7 +19,7 @@ type SendFn = (
19
19
  channel: string,
20
20
  sessionId: string,
21
21
  message: string,
22
- metadata?: { notificationId?: string },
22
+ metadata?: { notificationId?: string; accountId?: string },
23
23
  ) => Promise<void>
24
24
 
25
25
  let _sendFn: SendFn | null = null
@@ -31,18 +31,22 @@ export function setChannelSendFn(fn: SendFn): void {
31
31
  }
32
32
 
33
33
  /**
34
- * Resuelve el sessionId real (chat ID de Telegram, etc.) desde user_identities.
34
+ * Resuelve el sessionId real (chat ID de Telegram, etc.) desde user_identities,
35
+ * junto con la cuenta del canal por la que llegó — con varias cuentas del mismo
36
+ * tipo conectadas, la respuesta debe salir por la misma.
35
37
  * Necesario porque config.thread_id es el userId interno, no el chat ID externo.
36
38
  */
37
- async function resolveSessionId(userId: string, channel: string): Promise<string> {
39
+ async function resolveSession(userId: string, channel: string): Promise<{ sessionId: string; accountId?: string }> {
38
40
  try {
39
41
  const identitiesCol = await col<UserIdentityDoc>("userIdentities")
40
42
  const identity = await identitiesCol.get(`${userId}:${channel}`)
41
- if (identity?.doc.channel_user_id) return identity.doc.channel_user_id
43
+ if (identity?.doc.channel_user_id) {
44
+ return { sessionId: identity.doc.channel_user_id, accountId: identity.doc.account_id }
45
+ }
42
46
  } catch {
43
47
  // DB no lista — fallback al userId
44
48
  }
45
- return userId
49
+ return { sessionId: userId }
46
50
  }
47
51
 
48
52
  /**
@@ -75,11 +79,11 @@ export async function sendToUserChannel(
75
79
  return { ok: false, error: "Channel send not initialized" }
76
80
  }
77
81
 
78
- const sessionId = await resolveSessionId(userId, channel)
82
+ const { sessionId, accountId } = await resolveSession(userId, channel)
79
83
  log.info(`[channel-notify] Sending to ${channel}/${sessionId}: ${message.substring(0, 80)}`)
80
84
 
81
85
  try {
82
- await _sendFn(channel, sessionId, message, { notificationId })
86
+ await _sendFn(channel, sessionId, message, { notificationId, accountId })
83
87
  if (notificationId) await markNotificationDelivered(notificationId, userId)
84
88
  return { ok: true, queued: false, notificationId }
85
89
  } catch (err) {
@@ -106,22 +106,35 @@ function isComplete(group: DelegationGroupDoc): boolean {
106
106
  return expected.size > 0 && [...expected].every((id) => completed.has(id));
107
107
  }
108
108
 
109
+ function summarize(value: unknown, maxLen = 800): unknown {
110
+ if (typeof value !== "string") return value;
111
+ return value.length > maxLen ? `${value.slice(0, maxLen)}…` : value;
112
+ }
113
+
109
114
  function summaryPrompt(group: DelegationGroupDoc): string {
110
- const factual = outcomes(group).map((outcome) => ({
111
- task_id: outcome.task_id,
112
- worker_id: outcome.worker_id,
113
- task: outcome.task_name,
114
- ok: outcome.ok,
115
- result: outcome.result,
116
- error: outcome.error,
117
- }));
115
+ const factual = outcomes(group).map((outcome) => {
116
+ const result = outcome.result as { content?: unknown; acceptance?: unknown; checks?: { status?: string; summary?: string } } | null;
117
+ return {
118
+ task_id: outcome.task_id,
119
+ worker_id: outcome.worker_id,
120
+ task: outcome.task_name,
121
+ ok: outcome.ok,
122
+ content: summarize(result?.content ?? outcome.result),
123
+ acceptance: result?.acceptance ?? null,
124
+ checks: result?.checks ? { status: result.checks.status, summary: summarize(result.checks.summary) } : null,
125
+ error: outcome.error,
126
+ };
127
+ });
118
128
  // No manual framing here — persisted with source:"delegation_summary" and
119
129
  // framed at serialization time by formatInternalEvent (conversation-store.ts).
120
130
  return [
121
131
  "Todas las tareas delegadas de este turno alcanzaron estado terminal.",
122
- "Sintetiza UNA sola respuesta final para el usuario basándote exclusivamente en estos resultados y sus verificaciones.",
123
- "No declares éxito para resultados con ok=false y no inventes trabajo ni evidencia.",
124
- "Escribí en lenguaje natural para un humano: nunca expongas task_id, worker_id, verification_id, nombres de tools ni JSON crudo.",
132
+ "Para cada una, comprobá la entrega contra sus criterios de aceptación (`acceptance`):",
133
+ '- checks.status="passed" → verificado determinísticamente, aceptá.',
134
+ '- checks.status="failed" → NO cumplió (ok=false). No lo reportes como éxito.',
135
+ '- checks.status="unchecked" o ausente → juzgalo vos con el contenido y la evidencia adjunta.',
136
+ "Si una entrega no cumple sus criterios: usá `task_revise` con el task_id y un feedback concreto, o arreglala vos si es trivial y tenés las tools. No inventes trabajo ni evidencia, y no declares éxito para ok=false.",
137
+ "Si todas cumplen, escribí UNA sola respuesta final para el usuario, en lenguaje natural: nunca expongas task_id, worker_id, nombres de tools ni JSON crudo.",
125
138
  JSON.stringify(factual),
126
139
  ].join("\n\n");
127
140
  }
@@ -1,62 +1,4 @@
1
- // ─── Tool narration map ───────────────────────────────────────────────────────
2
- // Maps tool name prefixes/exact names to human-readable Spanish narrations.
3
- // Shown to the user while the agent executes a tool.
4
- const TOOL_NARRATIONS: Record<string, string> = {
5
- // Web
6
- web_search: "Buscando en la web...",
7
- web_fetch: "Leyendo página web...",
8
- // Files
9
- read: "Leyendo archivo...",
10
- write: "Escribiendo archivo...",
11
- edit: "Editando archivo...",
12
- exec: "Ejecutando comando...",
13
- // Cron
14
- "cron.create": "Programando tarea...",
15
- "cron.list": "Consultando tareas programadas...",
16
- "cron.update": "Actualizando tarea programada...",
17
- "cron.delete": "Eliminando tarea programada...",
18
- "cron.pause": "Pausando tarea programada...",
19
- "cron.resume": "Reanudando tarea programada...",
20
- "cron.trigger": "Ejecutando tarea ahora...",
21
- "cron.history": "Consultando historial...",
22
- // Agents
23
- agent_create: "Creando agente worker...",
24
- agent_find: "Buscando agente disponible...",
25
- agent_archive: "Archivando agente...",
26
- get_available_models: "Consultando modelos disponibles...",
27
- task_delegate: "Delegando tarea a un agente...",
28
- task_list: "Listando tareas en ejecución...",
29
- task_status: "Consultando estado de la tarea...",
30
- bus_publish: "Coordinando con otro agente...",
31
- bus_read: "Leyendo mensajes de los agentes...",
32
- // Discovery
33
- search_knowledge: "Buscando capacidades disponibles...",
34
- // Memory
35
- save_note: "Guardando nota...",
36
- memory_write: "Guardando en memoria...",
37
- memory_read: "Leyendo memoria...",
38
- memory_search: "Buscando en memoria...",
39
- memory_delete: "Eliminando de memoria...",
40
- memory_list: "Listando notas...",
41
- // Browser
42
- browser_navigate: "Navegando a la página...",
43
- browser_click: "Haciendo clic...",
44
- browser_type: "Escribiendo en la página...",
45
- browser_screenshot: "Tomando captura de pantalla...",
46
- browser_extract: "Extrayendo información de la página...",
47
- // Canvas
48
- canvas_add_node: "Actualizando canvas...",
49
- canvas_update: "Actualizando canvas...",
50
- // Notify
51
- notify: "Enviando notificación...",
52
- report_progress: "Reportando progreso...",
53
- }
54
-
55
- export function getNarration(toolName: string): string {
56
- if (TOOL_NARRATIONS[toolName]) return TOOL_NARRATIONS[toolName]
57
- // Prefix matching for MCP tools like "github__create_pr" → "Ejecutando github..."
58
- const prefix = toolName.split("__")[0]
59
- if (prefix && prefix !== toolName) return `Ejecutando ${prefix}...`
60
- // Fallback
61
- return `Ejecutando ${toolName.replace(/_/g, " ")}...`
62
- }
1
+ // The tool narration map lives in the narration domain (`events/`) so the agent
2
+ // loop can label its own events without depending on the gateway. Re-exported
3
+ // here to keep the existing `gateway/helpers` import path working.
4
+ export { getNarration } from "../../events/tool-narration.ts";
@@ -0,0 +1,67 @@
1
+ import * as path from "node:path";
2
+ import { existsSync } from "node:fs";
3
+
4
+ /**
5
+ * De dónde sale la UI que sirve el gateway en producción.
6
+ *
7
+ * `disk` gana siempre que haya un `index.html` real, porque esa copia se
8
+ * construye en el mismo paso que la publica (la etapa `ui-builder` del
9
+ * Dockerfile, o `packages/hive-ui/dist` en el monorepo). `embedded` es el
10
+ * bundle que `generate-ui-bundle.ts` compila dentro del ejecutable standalone,
11
+ * que es la única forma de que un binario suelto tenga UI pero que también
12
+ * puede quedar viejo respecto del disco.
13
+ */
14
+ export type UISource =
15
+ | { kind: "disk"; dir: string }
16
+ | { kind: "embedded" }
17
+ | { kind: "none"; dir: string };
18
+
19
+ export type UISourceInput = {
20
+ uiDirEnv?: string;
21
+ distDirEnv?: string;
22
+ hiveDir: string;
23
+ cwd: string;
24
+ hasEmbedded: boolean;
25
+ /** Inyectable para poder testear sin tocar el filesystem. */
26
+ exists?: (candidate: string) => boolean;
27
+ };
28
+
29
+ /**
30
+ * Orden:
31
+ * HIVE_UI_DIR > bundle embebido > ~/.hive/ui > HIVE_DIST_DIR/ui > cwd/packages/hive-ui/dist
32
+ *
33
+ * La elección es una sola por request y no por path: mezclar dos fuentes
34
+ * serviría un `index.html` de un build con los `assets/index-<hash>.js` de otro.
35
+ */
36
+ export function resolveUISource(input: UISourceInput): UISource {
37
+ const exists = input.exists ?? existsSync;
38
+ const hasIndex = (dir: string) => exists(path.join(dir, "index.html"));
39
+
40
+ // HIVE_UI_DIR es un override explícito y le gana al embed. Es lo que usa la
41
+ // imagen Docker, cuya etapa ui-builder compila la UI en cada build y la deja
42
+ // en /app/ui. Cuando el embed ganaba, el contenedor servía la copia que
43
+ // viajaba dentro del binario —commiteada y congelada— y /app/ui quedaba
44
+ // inerte.
45
+ if (input.uiDirEnv && hasIndex(input.uiDirEnv)) {
46
+ return { kind: "disk", dir: input.uiDirEnv };
47
+ }
48
+
49
+ // El embed va compilado dentro del ejecutable, así que siempre corresponde a
50
+ // su versión. Le gana a los directorios heredados: ~/.hive/ui puede haber
51
+ // quedado de una instalación anterior y taparía la UI del binario nuevo.
52
+ if (input.hasEmbedded) return { kind: "embedded" };
53
+
54
+ const fallbacks = [
55
+ path.join(input.hiveDir, "ui"),
56
+ input.distDirEnv ? path.join(input.distDirEnv, "ui") : undefined,
57
+ path.join(input.cwd, "packages/hive-ui/dist"),
58
+ ].filter((dir): dir is string => Boolean(dir));
59
+
60
+ for (const dir of fallbacks) {
61
+ if (hasIndex(dir)) return { kind: "disk", dir };
62
+ }
63
+
64
+ // Sin UI en ningún lado: se devuelve el candidato preferido para poder
65
+ // nombrarlo en el mensaje de error.
66
+ return { kind: "none", dir: input.uiDirEnv ?? fallbacks[0]! };
67
+ }
@@ -22,7 +22,7 @@ import { getDurableQueue } from "./durable-queue";
22
22
  import { sendToUserChannel } from "./channel-notify";
23
23
  import { verifyGoal } from "../agent/goal-runner";
24
24
  import { buildProofPacket } from "../agent/proof-packet";
25
- import { verifyAgentDelivery } from "../agent/acceptance-verifier";
25
+ import { runAcceptanceChecks, recordAgentOutcome } from "../agent/acceptance-checks";
26
26
  import { prepareDelegation, type PreparedDelegation } from "../agent/delegation-runtime";
27
27
  import { runWebchatTurn, type WebchatTurnPayload } from "./webchat-turn";
28
28
  import { agentBus } from "../events/agent-bus";
@@ -32,11 +32,8 @@ import { publishNarration } from "../events/narration";
32
32
  import {
33
33
  emitDelegationStarted,
34
34
  emitDelegationFinished,
35
- emitVerificationStarted,
36
- emitVerificationFinished,
37
35
  emitWorkEvent,
38
36
  } from "../canvas/emitter";
39
- import { VERIFIER_AGENT_ID } from "../agent/acceptance-verifier";
40
37
 
41
38
  const log = logger.child("job-executors");
42
39
 
@@ -174,44 +171,24 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
174
171
  }
175
172
 
176
173
  const finishedRun = runId ? await getRun(runId) : null;
177
- if (turnId && originThreadId) {
178
- await publishNarration({
179
- turnId,
180
- threadId: originThreadId,
181
- channel: originChannel,
182
- userId: originUserId,
183
- sessionId: originSessionId,
184
- agentId: workerId,
185
- agentName: workerName,
186
- kind: "verifying",
187
- status: "running",
188
- label: `El verificador está revisando la entrega de ${workerName}`,
189
- dedupeKey: `verifying:${taskId ?? job.id}`,
190
- });
191
- }
192
- emitVerificationStarted({ verifierId: VERIFIER_AGENT_ID, workerId, taskRef: delegationRef, taskName });
193
- const verification = await verifyAgentDelivery({
194
- runId,
195
- taskId,
196
- executorAgentId: workerId,
174
+ const resolvedAcceptance = acceptance ?? (finishedRun ? deserializeAcceptance(finishedRun) : null);
175
+ const evidence = [result, ...execution.toolEvidence];
176
+ const checks = await runAcceptanceChecks({
197
177
  objective: taskDescription,
198
- acceptance: acceptance ?? (finishedRun ? deserializeAcceptance(finishedRun) : null),
178
+ acceptance: resolvedAcceptance,
199
179
  delivery: result,
200
- evidence: [result, ...execution.toolEvidence],
201
- executorEpoch: finishedRun ? deserializeEpoch(finishedRun) : null,
202
- mcpServerIds: prepared.mcpServerIds,
203
- mcpManager,
180
+ evidence,
204
181
  });
205
- const verdict = JSON.parse(verification.verdict_json);
206
- emitVerificationFinished({ verifierId: VERIFIER_AGENT_ID, taskRef: delegationRef });
207
- if (verification.status !== "verified") {
182
+
183
+ if (checks.status === "failed") {
184
+ await recordAgentOutcome(workerId, "harmful");
208
185
  emitWorkEvent({
209
186
  phase: "review_failed",
210
187
  taskRef: delegationRef,
211
188
  taskName,
212
- actorId: VERIFIER_AGENT_ID,
189
+ actorId: parentAgentId || workerId,
213
190
  targetId: workerId,
214
- detail: verdict.summary || "La entrega no superó la verificación",
191
+ detail: checks.summary,
215
192
  });
216
193
  if (turnId && originThreadId) {
217
194
  await publishNarration({
@@ -224,29 +201,31 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
224
201
  agentName: workerName,
225
202
  kind: "failed",
226
203
  status: "error",
227
- label: `El verificador no aprobó la entrega de ${workerName}`,
228
- detail: verdict.summary || "Falta evidencia independiente.",
204
+ label: `La entrega de ${workerName} no pasó los checks automáticos`,
205
+ detail: checks.summary,
229
206
  dedupeKey: `verification_failed:${taskId ?? job.id}`,
230
207
  });
231
208
  }
232
209
  if (taskId) {
233
210
  await updateDoc<TaskDoc>("tasks", taskId, {
234
211
  status: "blocked",
235
- error: verdict.summary || "Independent verification did not authorize success.",
212
+ error: checks.summary,
236
213
  updated_at: Date.now(),
237
214
  } as Partial<TaskDoc>).catch(() => {});
238
215
  }
239
216
  return {
240
217
  ok: false,
241
- error: verdict.summary || "Independent verification did not authorize success.",
218
+ error: checks.summary,
242
219
  retryable: false,
243
220
  };
244
221
  }
222
+
223
+ await recordAgentOutcome(workerId, "helpful");
245
224
  emitWorkEvent({
246
225
  phase: "review_passed",
247
226
  taskRef: delegationRef,
248
227
  taskName,
249
- actorId: VERIFIER_AGENT_ID,
228
+ actorId: parentAgentId || workerId,
250
229
  targetId: workerId,
251
230
  });
252
231
  if (turnId && originThreadId) {
@@ -260,8 +239,8 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
260
239
  agentName: workerName,
261
240
  kind: "verified",
262
241
  status: "done",
263
- label: `El verificador aprobó la entrega de ${workerName}`,
264
- detail: `verification_id=${verification.id}`,
242
+ label: `${workerName} completó “${taskName}”`,
243
+ detail: checks.status === "passed" ? checks.summary : "El coordinador revisa el resultado.",
265
244
  dedupeKey: `verified:${taskId ?? job.id}`,
266
245
  });
267
246
  }
@@ -284,10 +263,9 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
284
263
  agentId: workerId,
285
264
  intendedOutcome: taskDescription,
286
265
  met: true,
287
- checksRun: acceptance?.map((criterion) => criterion.checkTool ?? "acceptance_verifier") ?? ["acceptance_verifier"],
288
- evidence: [result, ...execution.toolEvidence],
266
+ checksRun: checks.results.length ? checks.results.map((r) => r.check) : ["none"],
267
+ evidence,
289
268
  epoch: finishedRun ? deserializeEpoch(finishedRun) : null,
290
- verificationId: verification.id,
291
269
  catalogAgentId: isCatalogAgent ? workerId : null,
292
270
  });
293
271
 
@@ -304,7 +282,8 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
304
282
  result: {
305
283
  content: result,
306
284
  evidence: execution.toolEvidence,
307
- verification_id: verification.id,
285
+ acceptance: resolvedAcceptance,
286
+ checks,
308
287
  },
309
288
  };
310
289
  } catch (err) {
@@ -346,8 +325,6 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
346
325
 
347
326
  return { ok: false, error: errorMsg, retryable: isRetryableError(err) };
348
327
  } finally {
349
- // Idempotente: cubre también el caso en que verifyAgentDelivery lance
350
- emitVerificationFinished({ verifierId: VERIFIER_AGENT_ID, taskRef: delegationRef });
351
328
  emitDelegationFinished({ workerId, taskRef: delegationRef });
352
329
  await prepared?.release();
353
330
  }
@@ -355,7 +332,8 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
355
332
 
356
333
  // ─── goal_run executor ──────────────────────────────────────────────────────
357
334
  // Multi-turn orchestration: run a turn → verify the goal → continue with the
358
- // verifier's feedback until the goal is met or the budget runs out. The goal
335
+ // verifier's feedback (verifyGoal, goal-runner.ts) until the goal is met or
336
+ // the budget runs out. The goal
359
337
  // AgentRun row (job.run_id) is the orchestrator record: goal_attempts,
360
338
  // turns_used and tokens_used accumulate across turns and the budget is HARD.
361
339
  // Turns are plain (non-durable) runs on the same thread — a mid-turn crash
@@ -454,8 +432,9 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
454
432
  updated_at: Date.now(),
455
433
  } as Partial<AgentRunDoc>).catch(() => {});
456
434
 
457
- // Verify: deterministic tool when configured, LLM verifier otherwise
458
- // (or one check per acceptance criterion when the run has them)
435
+ // Verify: deterministic tool when configured, a single LLM judgment
436
+ // otherwise (one call total, covering every acceptance criterion —
437
+ // see verifyGoal in goal-runner.ts).
459
438
  const providerCfg = await resolveGoalProviderCfg(agentId);
460
439
  const verdict = await verifyGoal(goal, checkTool, [
461
440
  { role: "user", content: `Meta: ${goal}` },
@@ -463,22 +442,6 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
463
442
  ], providerCfg, acceptance);
464
443
 
465
444
  if (verdict.met) {
466
- const independent = await verifyAgentDelivery({
467
- runId: goalRunId,
468
- executorAgentId: agentId,
469
- objective: goal,
470
- acceptance,
471
- delivery: lastContent,
472
- evidence: [verdict.reason],
473
- executorEpoch: epoch,
474
- mcpManager,
475
- });
476
- if (independent.status !== "verified") {
477
- const independentVerdict = JSON.parse(independent.verdict_json);
478
- lastReason = independentVerdict.summary || "La verificación independiente no autorizó el éxito.";
479
- log.info(`[goal_run] Independent verifier rejected attempt ${attempts}: ${lastReason}`);
480
- continue;
481
- }
482
445
  await completeRun(goalRunId, lastContent);
483
446
  await notify(`✅ Meta cumplida: "${goal}". ${verdict.reason}`);
484
447
  log.info(`[goal_run] Goal met after ${attempts} attempt(s): ${verdict.reason}`);
@@ -491,7 +454,6 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
491
454
  checksRun: acceptance ? acceptance.map((a) => a.checkTool ?? "llm_verifier") : [checkTool ?? "llm_verifier"],
492
455
  evidence: [verdict.reason, lastContent].filter(Boolean),
493
456
  epoch,
494
- verificationId: independent.id,
495
457
  catalogAgentId: null,
496
458
  });
497
459
  return { ok: true, result: { met: true, attempts, reason: verdict.reason, content: lastContent } };