@johpaz/hive-agents 1.0.5 → 1.1.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.
- package/README.md +17 -11
- package/dist/hive.js +87295 -101789
- package/dist/tool-worker.js +13241 -17001
- package/dist/ui/assets/A2UIPage-F1sUdZV7.js +8 -0
- package/dist/ui/assets/{AgentCreateForm-Bcp3HN8D.js → AgentCreateForm-CN5Gb9UN.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-CzBnoKtH.js +1 -0
- package/dist/ui/assets/AgentNewPage-AGDjfAVf.js +1 -0
- package/dist/ui/assets/AgentsPage-BgKr7pAZ.js +10 -0
- package/dist/ui/assets/{ApiClientPage-DHfIlSAg.js → ApiClientPage-Dq4nPse4.js} +2 -2
- package/dist/ui/assets/ChannelsPage-BuWItmp-.js +8 -0
- package/dist/ui/assets/DashboardPage-CB1aM87o.js +6 -0
- package/dist/ui/assets/{LoginPage-BaX6cAPa.js → LoginPage-DBvwBCG6.js} +1 -1
- package/dist/ui/assets/LogsPage-Bc-oTBwY.js +1 -0
- package/dist/ui/assets/MeetingPage-C2H5SxaQ.js +1 -0
- package/dist/ui/assets/ModelSelector-D0aJvoD9.js +1 -0
- package/dist/ui/assets/NotFound-PUg3gEO0.js +1 -0
- package/dist/ui/assets/{Office3DPage-C3SIzd2H.css → Office3DPage-31AMJ-LN.css} +1 -1
- package/dist/ui/assets/Office3DPage-D5vwZkJa.js +727 -0
- package/dist/ui/assets/ProvidersPage-BBBt4Hcz.js +1 -0
- package/dist/ui/assets/{RecoverPage-C_Id9WM-.js → RecoverPage-nq901JiE.js} +1 -1
- package/dist/ui/assets/SettingsPage-DQ5KZPAd.js +9 -0
- package/dist/ui/assets/SetupPage-DeIGn-Uf.js +1 -0
- package/dist/ui/assets/{Vignette-Cyi27LQH.js → Vignette-BcPWkNhm.js} +17 -17
- package/dist/ui/assets/VoicePage-DJYsOsaU.js +307 -0
- package/dist/ui/assets/WebChatPage-CRDN4OlP.js +29 -0
- package/dist/ui/assets/agentCapabilities-PfTEVxG1.js +1 -0
- package/dist/ui/assets/alert-CjiX20jI.js +1 -0
- package/dist/ui/assets/badge-B5AKge1b.js +1 -0
- package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
- package/dist/ui/assets/conversationsStore-BIs0iMhp.js +1 -0
- package/dist/ui/assets/dialog-DdbsUCv9.js +1 -0
- package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
- package/dist/ui/assets/{dist-js-Bg0g3vPS.js → dist-js-q7C_AB0j.js} +1 -1
- package/dist/ui/assets/index-BD7hBA1d.css +2 -0
- package/dist/ui/assets/index-CpzwBwPg.js +116 -0
- package/dist/ui/assets/label-D_fvqJyD.js +1 -0
- package/dist/ui/assets/lock-3IApZyVy.js +1 -0
- package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
- package/dist/ui/assets/scroll-area-CbH8FOo8.js +1 -0
- package/dist/ui/assets/select-v_3QBYrD.js +1 -0
- package/dist/ui/assets/slider-DXS4h1LB.js +1 -0
- package/dist/ui/assets/switch-ndx8VCpm.js +1 -0
- package/dist/ui/assets/tabs-epu-3Tl4.js +1 -0
- package/dist/ui/assets/textarea-BgZJFZTX.js +1 -0
- package/dist/ui/assets/useAudioDevices-yU-wu-kt.js +41 -0
- package/dist/ui/assets/{useHiveAgentsModelLoad-CHmtvNp4.js → useHiveAgentsModelLoad-29pOYRd9.js} +1 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
- package/dist/ui/assets/{useProviders-C7FA6z4M.js → useProviders-CiBi4Dt6.js} +1 -1
- package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
- package/dist/ui/index.html +6 -6
- package/package.json +10 -6
- package/packages/cli/src/adapters/config.ts +11 -3
- package/packages/cli/src/commands/causal.ts +1 -1
- package/packages/cli/src/commands/doctor.ts +2 -2
- package/packages/cli/src/commands/onboard.ts +1 -1
- package/packages/core/src/agent/acceptance-checks.ts +25 -0
- package/packages/core/src/agent/agent-catalog.ts +53 -33
- package/packages/core/src/agent/agent-loop.ts +67 -14
- package/packages/core/src/agent/capability-search.ts +2 -1
- package/packages/core/src/agent/compaction.ts +19 -7
- package/packages/core/src/agent/context-compiler.ts +165 -27
- package/packages/core/src/agent/conversation-store.ts +12 -1
- package/packages/core/src/agent/goal-runner.ts +2 -2
- package/packages/core/src/agent/jev-decisions.ts +242 -0
- package/packages/core/src/agent/jev-planner.ts +293 -0
- package/packages/core/src/agent/llm-client.ts +27 -5
- package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
- package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
- package/packages/core/src/agent/realtime-providers/gemini-live.ts +5 -2
- package/packages/core/src/agent/skill-selector.ts +4 -2
- package/packages/core/src/agent/thread-id.ts +71 -0
- package/packages/core/src/agent/thread-store.ts +230 -0
- package/packages/core/src/agent/tool-selector.ts +42 -0
- package/packages/core/src/agent/tracer.ts +2 -0
- package/packages/core/src/canvas/canvas-manager.ts +17 -1
- package/packages/core/src/canvas/emitter.ts +24 -0
- package/packages/core/src/channels/telegram.ts +19 -1
- package/packages/core/src/channels/webchat.ts +47 -45
- package/packages/core/src/config/loader.ts +3 -2
- package/packages/core/src/gateway/channel-notify.ts +24 -5
- package/packages/core/src/gateway/delegation-groups.ts +3 -3
- package/packages/core/src/gateway/delegation-notify.ts +34 -5
- package/packages/core/src/gateway/durable-queue.ts +22 -0
- package/packages/core/src/gateway/failure-notify.ts +8 -2
- package/packages/core/src/gateway/job-executors.ts +3 -3
- package/packages/core/src/gateway/realtime/bridge-tools.ts +106 -28
- package/packages/core/src/gateway/realtime/index.ts +63 -7
- package/packages/core/src/gateway/realtime/prompt.ts +45 -0
- package/packages/core/src/gateway/realtime/voice-session.ts +1 -0
- package/packages/core/src/gateway/resolver.ts +31 -4
- package/packages/core/src/gateway/routes/artifacts.ts +13 -0
- package/packages/core/src/gateway/routes/chat.ts +20 -4
- package/packages/core/src/gateway/routes/conversations.ts +121 -0
- package/packages/core/src/gateway/routes/providers.ts +15 -0
- package/packages/core/src/gateway/routes/setup.ts +22 -11
- package/packages/core/src/gateway/routes/system.ts +4 -2
- package/packages/core/src/gateway/routes/tts-local.ts +2 -1
- package/packages/core/src/gateway/server.ts +85 -12
- package/packages/core/src/gateway/slash-commands.ts +46 -10
- package/packages/core/src/gateway/tts/src/server.ts +2 -1
- package/packages/core/src/gateway/webchat-turn.ts +68 -10
- package/packages/core/src/index.ts +2 -0
- package/packages/core/src/scheduler/CronScheduler.ts +20 -8
- package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
- package/packages/core/src/scheduler/cron/expression.ts +165 -0
- package/packages/core/src/scheduler/cron/index.ts +10 -0
- package/packages/core/src/scheduler/cron/job.ts +340 -0
- package/packages/core/src/scheduler/cron/next-run.ts +121 -0
- package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
- package/packages/core/src/scheduler/integration.ts +16 -5
- package/packages/core/src/scheduler/types.ts +3 -18
- package/packages/core/src/storage/bootstrap.ts +24 -1
- package/packages/core/src/storage/collections.ts +29 -1
- package/packages/core/src/storage/crypto.ts +133 -40
- package/packages/core/src/storage/reconcile.ts +6 -1
- package/packages/core/src/storage/seed.ts +101 -7
- package/packages/core/src/storage/usage.ts +53 -1
- package/packages/core/src/tool-runtime/index.ts +19 -1
- package/packages/core/src/tools/a2ui/index.ts +65 -1
- package/packages/core/src/tools/agents/get-available-models.ts +3 -1
- package/packages/core/src/tools/code-agent/adapters.ts +110 -0
- package/packages/core/src/tools/code-agent/index.ts +193 -0
- package/packages/core/src/tools/core/index.ts +39 -4
- package/packages/core/src/tools/cron/index.ts +4 -4
- package/packages/core/src/tools/index.ts +9 -1
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
- package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
- package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
- package/packages/core/src/tools/web/browser-backend.ts +22 -2
- package/packages/core/src/tools/web/index.ts +4 -0
- package/packages/core/src/tools/web/obscura.ts +860 -0
- package/packages/core/src/tools/web/webview-backend.ts +168 -26
- package/packages/core/src/utils/port.ts +33 -0
- package/packages/core/src/voice/index.ts +2 -1
- package/packages/mcp/src/config.ts +2 -1
- package/packages/mcp/src/manager.ts +9 -0
- package/packages/mcp/src/transports/index.ts +42 -1
- package/packages/mcp/src/transports/sse.ts +11 -5
- package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
- package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
- package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
- package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
- package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
- package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
- package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
- package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
- package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
- package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
- package/packages/skills/src/bundled/cli/external_code_agent/SKILL.md +69 -0
- package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
- package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
- package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
- package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
- package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
- package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
- package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
- package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
- package/packages/skills/src/bundled/web/obscura_browser/SKILL.md +69 -0
- package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
- package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
- package/packages/skills/src/bundled-data.generated.ts +845 -773
- package/dist/ui/assets/A2UIPage-DTW79pyL.js +0 -8
- package/dist/ui/assets/AgentDetailPage-10XptMde.js +0 -1
- package/dist/ui/assets/AgentNewPage-CUt49rVS.js +0 -1
- package/dist/ui/assets/AgentsPage-1_e1a9xa.js +0 -10
- package/dist/ui/assets/ChannelsPage-BnCQAGZL.js +0 -8
- package/dist/ui/assets/DashboardPage-BsCCKHgg.js +0 -6
- package/dist/ui/assets/LogsPage-DiFBQt7o.js +0 -1
- package/dist/ui/assets/MeetingPage-Bpv5zVXf.js +0 -1
- package/dist/ui/assets/ModelSelector-DfExlPzx.js +0 -1
- package/dist/ui/assets/NotFound-C8HBdF73.js +0 -1
- package/dist/ui/assets/Office3DPage-ChsGMapf.js +0 -319
- package/dist/ui/assets/ProvidersPage-B39pfWHf.js +0 -1
- package/dist/ui/assets/SettingsPage-BgFqasyg.js +0 -9
- package/dist/ui/assets/SetupPage-YeJFfgbt.js +0 -1
- package/dist/ui/assets/VoicePage-Cp63Abj4.js +0 -307
- package/dist/ui/assets/WebChatPage-DxFLWgtM.js +0 -29
- package/dist/ui/assets/agentCapabilities-DOeepCty.js +0 -1
- package/dist/ui/assets/alert-Cj4DpKv6.js +0 -1
- package/dist/ui/assets/badge-DKpeVCpY.js +0 -1
- package/dist/ui/assets/card-Cag15G4h.js +0 -1
- package/dist/ui/assets/dialog-7E3EoEt3.js +0 -1
- package/dist/ui/assets/dist-js-DwLn9F4C.js +0 -1
- package/dist/ui/assets/index-Bi8qEmrK.js +0 -116
- package/dist/ui/assets/index-D2UhaSb0.css +0 -2
- package/dist/ui/assets/label-C6atPuIh.js +0 -1
- package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
- package/dist/ui/assets/scroll-area-CSoG2z53.js +0 -1
- package/dist/ui/assets/select-DlCT21_r.js +0 -1
- package/dist/ui/assets/slider-Bb_PHFJT.js +0 -1
- package/dist/ui/assets/switch-CUsGuBNi.js +0 -1
- package/dist/ui/assets/tabs-Ckfc7DGG.js +0 -1
- package/dist/ui/assets/textarea-BH6pI9Ax.js +0 -1
- package/dist/ui/assets/useAudioDevices-Dpr_hn6i.js +0 -41
- package/dist/ui/assets/useOfficeModel-Cc5VkReZ.js +0 -1
- package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
- /package/dist/ui/assets/{core-Dz04EE_8.js → core-B_5cyOSV.js} +0 -0
- /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
- /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
- /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
- /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BzQV75Ig.js → gateway-url-BALS_wVh.js} +0 -0
- /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
- /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
- /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
- /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
- /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
- /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
- /package/dist/ui/assets/{mic-Rq4BxU1R.js → mic-CpDU_2as.js} +0 -0
- /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
- /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
- /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
- /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-Dx92orJM.js → rotate-ccw-LoM1AuqK.js} +0 -0
- /package/dist/ui/assets/{search-DB4w9YHW.js → search-BMwCI-pX.js} +0 -0
- /package/dist/ui/assets/{send-xi8HzUdc.js → send-D6fgWV7m.js} +0 -0
- /package/dist/ui/assets/{settings-pV0cF8Kf.js → settings-qV3kVkeG.js} +0 -0
- /package/dist/ui/assets/{shield-nLNsomh_.js → shield-CIarwBvx.js} +0 -0
- /package/dist/ui/assets/{sparkles-CerRDYxk.js → sparkles-DVvY6jDT.js} +0 -0
- /package/dist/ui/assets/{square-CcWzRWyG.js → square-D5zdNkAY.js} +0 -0
- /package/dist/ui/assets/{terminal-C2SUZUAD.js → terminal-BEcTK780.js} +0 -0
- /package/dist/ui/assets/{trash-2-BZsMCfso.js → trash-2-D6oziYAK.js} +0 -0
- /package/dist/ui/assets/{utils-lc8H6VGT.js → utils-DEmd_M8c.js} +0 -0
- /package/dist/ui/assets/{vendor-router-DCsSv_I7.js → vendor-router-DP84b3LQ.js} +0 -0
- /package/dist/ui/assets/{volume-2-CBMYsuF3.js → volume-2-EaA0JRvD.js} +0 -0
- /package/dist/ui/assets/{volume-x-vNFf2e4-.js → volume-x-CROXNMGT.js} +0 -0
- /package/dist/ui/assets/{wifi-DNv53AfN.js → wifi-BUJuOcgP.js} +0 -0
- /package/dist/ui/assets/{zap-Yed86Sh8.js → zap-DSoX9NDk.js} +0 -0
|
@@ -165,7 +165,25 @@ export class TelegramChannel extends BaseChannel {
|
|
|
165
165
|
}
|
|
166
166
|
|
|
167
167
|
if (text === "/new" || text?.startsWith("/new@")) {
|
|
168
|
-
|
|
168
|
+
// Antes sólo contestaba: el contexto seguía intacto y la conversación
|
|
169
|
+
// continuaba como si nada. Ahora borra de verdad el hilo de ESTE chat —los
|
|
170
|
+
// demás canales y las conversaciones de la web no se tocan.
|
|
171
|
+
try {
|
|
172
|
+
const { resolveContext } = await import("../gateway/resolver");
|
|
173
|
+
const { deleteThread } = await import("../agent/thread-store");
|
|
174
|
+
const { threadId } = await resolveContext({
|
|
175
|
+
channel: this.name,
|
|
176
|
+
channelUserId: peerId,
|
|
177
|
+
accountId: this.accountId,
|
|
178
|
+
peerId,
|
|
179
|
+
peerKind: kind,
|
|
180
|
+
});
|
|
181
|
+
await deleteThread(threadId);
|
|
182
|
+
await ctx.reply("🔄 Listo, empezamos de cero.", { parse_mode: "HTML" });
|
|
183
|
+
} catch (err) {
|
|
184
|
+
this.log.warn(`No pude reiniciar el hilo de ${peerId}: ${(err as Error).message}`);
|
|
185
|
+
await ctx.reply("No pude reiniciar la conversación.", { parse_mode: "HTML" });
|
|
186
|
+
}
|
|
169
187
|
return;
|
|
170
188
|
}
|
|
171
189
|
|
|
@@ -20,7 +20,13 @@ export class WebChatChannel extends BaseChannel {
|
|
|
20
20
|
config: WebChatConfig;
|
|
21
21
|
|
|
22
22
|
private explicitAccountId?: string;
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Every open socket of a session. One user can hold several at once — the
|
|
25
|
+
* desktop app and a browser tab, or overlapping reconnects after a gateway
|
|
26
|
+
* restart. Keeping only the last one meant that closing it orphaned the
|
|
27
|
+
* sockets still open: the UI stayed "connected" while every reply was lost.
|
|
28
|
+
*/
|
|
29
|
+
private connections: Map<string, Set<ServerWebSocket<WebSocketData>>> = new Map();
|
|
24
30
|
private log = logger.child("webchat");
|
|
25
31
|
|
|
26
32
|
constructor(config: WebChatConfig) {
|
|
@@ -47,14 +53,39 @@ export class WebChatChannel extends BaseChannel {
|
|
|
47
53
|
|
|
48
54
|
registerConnection(ws: ServerWebSocket<WebSocketData>): void {
|
|
49
55
|
const data = ws.data as WebSocketData;
|
|
50
|
-
this.connections.
|
|
51
|
-
|
|
56
|
+
const sockets = this.connections.get(data.sessionId) ?? new Set();
|
|
57
|
+
sockets.add(ws);
|
|
58
|
+
this.connections.set(data.sessionId, sockets);
|
|
59
|
+
this.log.debug(`WebChat connection registered: ${data.sessionId} (${sockets.size} open)`);
|
|
52
60
|
}
|
|
53
61
|
|
|
62
|
+
/** Without `ws`, forgets every socket of the session. */
|
|
54
63
|
unregisterConnection(sessionId: string, ws?: ServerWebSocket<WebSocketData>): void {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
64
|
+
const sockets = this.connections.get(sessionId);
|
|
65
|
+
if (!sockets) return;
|
|
66
|
+
if (ws) sockets.delete(ws);
|
|
67
|
+
if (!ws || sockets.size === 0) this.connections.delete(sessionId);
|
|
68
|
+
this.log.debug(`WebChat connection unregistered: ${sessionId} (${ws ? sockets.size : 0} open)`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Sends `payload` to every open socket of the session; a socket that throws
|
|
73
|
+
* is dropped. Returns how many received it.
|
|
74
|
+
*/
|
|
75
|
+
private broadcast(sessionId: string, payload: string): number {
|
|
76
|
+
const sockets = this.connections.get(sessionId);
|
|
77
|
+
if (!sockets) return 0;
|
|
78
|
+
let delivered = 0;
|
|
79
|
+
for (const ws of [...sockets]) {
|
|
80
|
+
try {
|
|
81
|
+
ws.send(payload);
|
|
82
|
+
delivered++;
|
|
83
|
+
} catch {
|
|
84
|
+
sockets.delete(ws);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (sockets.size === 0) this.connections.delete(sessionId);
|
|
88
|
+
return delivered;
|
|
58
89
|
}
|
|
59
90
|
|
|
60
91
|
/** Returns the first active WebChat session ID, or undefined if no one is connected */
|
|
@@ -67,56 +98,27 @@ export class WebChatChannel extends BaseChannel {
|
|
|
67
98
|
}
|
|
68
99
|
|
|
69
100
|
async startTyping(sessionId: string): Promise<void> {
|
|
70
|
-
|
|
71
|
-
if (!ws) return;
|
|
72
|
-
|
|
73
|
-
try {
|
|
74
|
-
ws.send(JSON.stringify({ type: "typing", isTyping: true }));
|
|
75
|
-
} catch {
|
|
76
|
-
// Connection closed
|
|
77
|
-
}
|
|
101
|
+
this.broadcast(sessionId, JSON.stringify({ type: "typing", isTyping: true }));
|
|
78
102
|
}
|
|
79
103
|
|
|
80
104
|
async stopTyping(sessionId: string): Promise<void> {
|
|
81
|
-
|
|
82
|
-
if (!ws) return;
|
|
83
|
-
|
|
84
|
-
try {
|
|
85
|
-
ws.send(JSON.stringify({ type: "typing", isTyping: false }));
|
|
86
|
-
} catch {
|
|
87
|
-
// Connection closed
|
|
88
|
-
}
|
|
105
|
+
this.broadcast(sessionId, JSON.stringify({ type: "typing", isTyping: false }));
|
|
89
106
|
}
|
|
90
107
|
|
|
91
108
|
async send(sessionId: string, message: OutboundMessage): Promise<void> {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (!ws) {
|
|
109
|
+
if (this.broadcast(sessionId, JSON.stringify(message)) === 0) {
|
|
95
110
|
throw new Error(`No WebChat connection for session: ${sessionId}`);
|
|
96
111
|
}
|
|
97
|
-
|
|
98
|
-
ws.send(JSON.stringify(message));
|
|
99
112
|
}
|
|
100
113
|
|
|
101
114
|
async sendAudio(sessionId: string, audio: Buffer, mimeType: string): Promise<void> {
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
try {
|
|
110
|
-
const base64Audio = audio.toString("base64");
|
|
111
|
-
ws.send(JSON.stringify({
|
|
112
|
-
type: "audio",
|
|
113
|
-
sessionId,
|
|
114
|
-
audio: base64Audio,
|
|
115
|
-
mimeType,
|
|
116
|
-
}));
|
|
117
|
-
} catch (error) {
|
|
118
|
-
this.log.error(`Failed to send WebChat audio: ${(error as Error).message}`);
|
|
119
|
-
}
|
|
115
|
+
const delivered = this.broadcast(sessionId, JSON.stringify({
|
|
116
|
+
type: "audio",
|
|
117
|
+
sessionId,
|
|
118
|
+
audio: audio.toString("base64"),
|
|
119
|
+
mimeType,
|
|
120
|
+
}));
|
|
121
|
+
if (delivered === 0) this.log.warn(`No WebChat connection for session: ${sessionId}`);
|
|
120
122
|
}
|
|
121
123
|
|
|
122
124
|
createIncomingMessage(
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolvePort } from "../utils/port";
|
|
1
2
|
import * as z from "zod";
|
|
2
3
|
import { mkdirSync, existsSync, readFileSync } from "node:fs";
|
|
3
4
|
import * as path from "node:path";
|
|
@@ -5,7 +6,7 @@ import { availableParallelism, homedir } from "node:os";
|
|
|
5
6
|
|
|
6
7
|
const LogLevelSchema = z.enum(["debug", "info", "warn", "error"]);
|
|
7
8
|
const DMPolicySchema = z.enum(["open", "pairing", "allowlist"]);
|
|
8
|
-
const TransportSchema = z.enum(["stdio", "sse", "websocket"]);
|
|
9
|
+
const TransportSchema = z.enum(["stdio", "sse", "websocket", "http"]);
|
|
9
10
|
|
|
10
11
|
export function loadEnv(hiveDir: string): void {
|
|
11
12
|
const envPath = path.join(hiveDir, ".env");
|
|
@@ -407,7 +408,7 @@ function buildDefaultConfig(): Config {
|
|
|
407
408
|
return {
|
|
408
409
|
gateway: {
|
|
409
410
|
host: process.env.HIVE_HOST || "127.0.0.1",
|
|
410
|
-
port:
|
|
411
|
+
port: resolvePort(process.env.HIVE_PORT, 18790),
|
|
411
412
|
pidFile: path.join(hiveDir, "gateway.pid"),
|
|
412
413
|
authToken: process.env.HIVE_AUTH_TOKEN || undefined,
|
|
413
414
|
tools: {
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
createNotification,
|
|
13
13
|
markNotificationDelivered,
|
|
14
14
|
} from "./notification-inbox"
|
|
15
|
+
import { parseThreadId } from "../agent/thread-id"
|
|
15
16
|
|
|
16
17
|
const log = logger.child("channel-notify")
|
|
17
18
|
|
|
@@ -36,17 +37,33 @@ export function setChannelSendFn(fn: SendFn): void {
|
|
|
36
37
|
* tipo conectadas, la respuesta debe salir por la misma.
|
|
37
38
|
* Necesario porque config.thread_id es el userId interno, no el chat ID externo.
|
|
38
39
|
*/
|
|
39
|
-
async function resolveSession(
|
|
40
|
+
async function resolveSession(
|
|
41
|
+
userId: string,
|
|
42
|
+
channel: string,
|
|
43
|
+
threadId?: string
|
|
44
|
+
): Promise<{ sessionId: string; accountId?: string }> {
|
|
45
|
+
let accountId: string | undefined
|
|
40
46
|
try {
|
|
41
47
|
const identitiesCol = await col<UserIdentityDoc>("userIdentities")
|
|
42
48
|
const identity = await identitiesCol.get(`${userId}:${channel}`)
|
|
49
|
+
accountId = identity?.doc.account_id
|
|
50
|
+
|
|
51
|
+
// El hilo manda sobre la identidad: `userIdentities` guarda UNA fila por
|
|
52
|
+
// (usuario, canal), así que con varios chats o grupos del mismo canal apunta
|
|
53
|
+
// siempre al último que escribió. El threadId sí sabe de qué conversación
|
|
54
|
+
// salió el aviso, y su peerId es justo el destino del canal.
|
|
55
|
+
const parts = threadId ? parseThreadId(threadId) : null
|
|
56
|
+
if (parts && parts.channel === channel && channel !== "webchat") {
|
|
57
|
+
return { sessionId: parts.peerId, accountId }
|
|
58
|
+
}
|
|
59
|
+
|
|
43
60
|
if (identity?.doc.channel_user_id) {
|
|
44
|
-
return { sessionId: identity.doc.channel_user_id, accountId
|
|
61
|
+
return { sessionId: identity.doc.channel_user_id, accountId }
|
|
45
62
|
}
|
|
46
63
|
} catch {
|
|
47
64
|
// DB no lista — fallback al userId
|
|
48
65
|
}
|
|
49
|
-
return { sessionId: userId }
|
|
66
|
+
return { sessionId: userId, accountId }
|
|
50
67
|
}
|
|
51
68
|
|
|
52
69
|
/**
|
|
@@ -56,7 +73,9 @@ async function resolveSession(userId: string, channel: string): Promise<{ sessio
|
|
|
56
73
|
export async function sendToUserChannel(
|
|
57
74
|
channel: string,
|
|
58
75
|
userId: string,
|
|
59
|
-
message: string
|
|
76
|
+
message: string,
|
|
77
|
+
/** Conversación de origen — decide a qué chat o grupo del canal vuelve el aviso. */
|
|
78
|
+
opts?: { threadId?: string }
|
|
60
79
|
): Promise<{ ok: boolean; queued?: boolean; notificationId?: string; error?: string }> {
|
|
61
80
|
let notificationId: string | undefined
|
|
62
81
|
if (channel === "webchat") {
|
|
@@ -79,7 +98,7 @@ export async function sendToUserChannel(
|
|
|
79
98
|
return { ok: false, error: "Channel send not initialized" }
|
|
80
99
|
}
|
|
81
100
|
|
|
82
|
-
const { sessionId, accountId } = await resolveSession(userId, channel)
|
|
101
|
+
const { sessionId, accountId } = await resolveSession(userId, channel, opts?.threadId)
|
|
83
102
|
log.info(`[channel-notify] Sending to ${channel}/${sessionId}: ${message.substring(0, 80)}`)
|
|
84
103
|
|
|
85
104
|
try {
|
|
@@ -130,10 +130,10 @@ function summaryPrompt(group: DelegationGroupDoc): string {
|
|
|
130
130
|
return [
|
|
131
131
|
"Todas las tareas delegadas de este turno alcanzaron estado terminal.",
|
|
132
132
|
"Para cada una, comprueba la entrega contra sus criterios de aceptación (`acceptance`):",
|
|
133
|
-
'- checks.status="passed" → verificado determinísticamente,
|
|
133
|
+
'- checks.status="passed" → verificado determinísticamente, acepta.',
|
|
134
134
|
'- checks.status="failed" → NO cumplió (ok=false). No lo reportes como éxito.',
|
|
135
|
-
'- checks.status="unchecked" o ausente →
|
|
136
|
-
"Si una entrega no cumple sus criterios: usa `task_revise` con el task_id y un feedback concreto, o
|
|
135
|
+
'- checks.status="unchecked" o ausente → júzgalo tú con el contenido y la evidencia adjunta.',
|
|
136
|
+
"Si una entrega no cumple sus criterios: usa `task_revise` con el task_id y un feedback concreto, o arréglala tú si es trivial y tienes las tools. No inventes trabajo ni evidencia, y no declares éxito para ok=false.",
|
|
137
137
|
"Si todas cumplen, escribe UNA sola respuesta final para el usuario, en lenguaje natural: nunca expongas task_id, worker_id, nombres de tools ni JSON crudo.",
|
|
138
138
|
JSON.stringify(factual),
|
|
139
139
|
].join("\n\n");
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
recordDelegationOutcome,
|
|
19
19
|
setDelegationSummaryEnqueuer,
|
|
20
20
|
} from "./delegation-groups";
|
|
21
|
+
import { parseThreadId } from "../agent/thread-id";
|
|
21
22
|
|
|
22
23
|
const log = logger.child("delegation-notify");
|
|
23
24
|
|
|
@@ -29,12 +30,34 @@ interface WorkerTaskPayload {
|
|
|
29
30
|
turnId?: string | null;
|
|
30
31
|
}
|
|
31
32
|
|
|
32
|
-
/**
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Hilo de origen en su forma canónica.
|
|
35
|
+
*
|
|
36
|
+
* Hasta la separación por canal, `createRun` guardaba `thread_id` como
|
|
37
|
+
* `webchat:${sessionId}` mientras `conversations` usaba el id pelado. Ese prefijo
|
|
38
|
+
* ya no se escribe, pero sigue vivo en los runs y jobs anteriores: sin quitarlo,
|
|
39
|
+
* el aviso iría a un hilo que no existe.
|
|
40
|
+
*/
|
|
41
|
+
function normalizeOriginThread(originThreadId: string): string {
|
|
34
42
|
const prefix = "webchat:";
|
|
35
43
|
return originThreadId.startsWith(prefix) ? originThreadId.slice(prefix.length) : originThreadId;
|
|
36
44
|
}
|
|
37
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Destino de TRANSPORTE de un aviso, derivado del hilo de origen.
|
|
48
|
+
*
|
|
49
|
+
* El hilo dice en qué conversación escribir; el sessionId, por dónde sale la
|
|
50
|
+
* respuesta: en la web el socket se identifica con el userId, en los demás canales
|
|
51
|
+
* con el contacto o grupo. Los hilos sin formato (el legacy previo a la separación
|
|
52
|
+
* por canal, y los jobs encolados con el viejo prefijo `webchat:`) se devuelven
|
|
53
|
+
* como estaban.
|
|
54
|
+
*/
|
|
55
|
+
function deriveSessionId(originThreadId: string): string {
|
|
56
|
+
const parts = parseThreadId(originThreadId);
|
|
57
|
+
if (parts) return parts.channel === "webchat" ? parts.userId : parts.peerId;
|
|
58
|
+
return normalizeOriginThread(originThreadId);
|
|
59
|
+
}
|
|
60
|
+
|
|
38
61
|
function summarize(value: unknown, maxLen = 500): string {
|
|
39
62
|
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
40
63
|
return text.length > maxLen ? `${text.slice(0, maxLen)}…` : text;
|
|
@@ -67,9 +90,13 @@ async function notifyWorkerTaskOutcome(job: JobDoc, outcome: JobTerminalOutcome)
|
|
|
67
90
|
: `El agente NO pudo completar la tarea "${taskName}". Motivo: ${summarize(outcome.error ?? "error desconocido")}`;
|
|
68
91
|
|
|
69
92
|
try {
|
|
93
|
+
// El aviso vuelve a la conversación que delegó, no a la más reciente del
|
|
94
|
+
// usuario: con un hilo por canal y contacto, adivinarlo desde el sessionId ya
|
|
95
|
+
// no es posible. La lane es la misma que usa el chat de esa conversación.
|
|
96
|
+
const originThread = normalizeOriginThread(payload.originThreadId);
|
|
70
97
|
await enqueueChatTurn({
|
|
71
|
-
lane:
|
|
72
|
-
payload: { source: "task_complete", sessionId, content },
|
|
98
|
+
lane: originThread,
|
|
99
|
+
payload: { source: "task_complete", sessionId, threadId: originThread, content },
|
|
73
100
|
});
|
|
74
101
|
log.info(`[notifyWorkerTaskOutcome] Enqueued task_complete notice for session ${sessionId} (job ${job.id}, ok=${outcome.ok})`);
|
|
75
102
|
} catch (err) {
|
|
@@ -84,11 +111,13 @@ export function initDelegationNotify(): void {
|
|
|
84
111
|
registerTerminalHook("worker_task", notifyWorkerTaskOutcome);
|
|
85
112
|
setDelegationSummaryEnqueuer(async (group, content, idempotencyKey) => {
|
|
86
113
|
const sessionId = group.session_id || deriveSessionId(group.thread_id);
|
|
114
|
+
const groupThread = normalizeOriginThread(group.thread_id);
|
|
87
115
|
return enqueueChatTurn({
|
|
88
|
-
lane:
|
|
116
|
+
lane: groupThread,
|
|
89
117
|
payload: {
|
|
90
118
|
source: "delegation_summary",
|
|
91
119
|
sessionId,
|
|
120
|
+
threadId: groupThread,
|
|
92
121
|
content,
|
|
93
122
|
rawContent: content,
|
|
94
123
|
userId: group.user_id,
|
|
@@ -109,6 +109,8 @@ export class DurableLaneQueue {
|
|
|
109
109
|
private jobRetryPolicy: JobRetryPolicy;
|
|
110
110
|
private runningCount = 0;
|
|
111
111
|
private runningAborts = new Map<string, { lane: string; controller: AbortController }>();
|
|
112
|
+
/** Lanes with a claim in flight: the gap between findPending and executeJob. */
|
|
113
|
+
private claimingLanes = new Set<string>();
|
|
112
114
|
private dispatchTimers = new Map<string, ReturnType<typeof setInterval>>();
|
|
113
115
|
private leaseCheckTimer: ReturnType<typeof setInterval> | null = null;
|
|
114
116
|
private bootId: string;
|
|
@@ -180,6 +182,12 @@ export class DurableLaneQueue {
|
|
|
180
182
|
if (entry.lane === lane) {
|
|
181
183
|
entry.controller.abort();
|
|
182
184
|
if (await cancelJob(jobId)) count++;
|
|
185
|
+
// Free the lane now: an executor can take a while to notice the abort
|
|
186
|
+
// (a local model mid-generation), and until executeJob's finally ran
|
|
187
|
+
// the one-job-per-lane rule kept the user's next message waiting behind
|
|
188
|
+
// a turn they had already cancelled. completeJob ignores cancelled jobs,
|
|
189
|
+
// so its late result is discarded.
|
|
190
|
+
this.runningAborts.delete(jobId);
|
|
183
191
|
}
|
|
184
192
|
}
|
|
185
193
|
const pending = await findPendingJobsByLane(lane, 100);
|
|
@@ -254,6 +262,20 @@ export class DurableLaneQueue {
|
|
|
254
262
|
* Dispatch pending jobs for a single lane, respecting global concurrency.
|
|
255
263
|
*/
|
|
256
264
|
private async dispatchLane(lane: string): Promise<void> {
|
|
265
|
+
// One running job per lane. Without this check a job enqueued while another
|
|
266
|
+
// ran in the same lane started right away: an A2UI action and a delegation
|
|
267
|
+
// summary ran as two concurrent Bee turns in one conversation, and both
|
|
268
|
+
// re-delegated the whole swarm. executeJob re-dispatches the lane on finish.
|
|
269
|
+
if (this.claimingLanes.has(lane) || [...this.runningAborts.values()].some((r) => r.lane === lane)) return;
|
|
270
|
+
this.claimingLanes.add(lane);
|
|
271
|
+
try {
|
|
272
|
+
await this.dispatchNextInLane(lane);
|
|
273
|
+
} finally {
|
|
274
|
+
this.claimingLanes.delete(lane);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private async dispatchNextInLane(lane: string): Promise<void> {
|
|
257
279
|
for (;;) {
|
|
258
280
|
const pending = await findPendingJobsByLane(lane, 1);
|
|
259
281
|
if (pending.length === 0) break;
|
|
@@ -34,6 +34,7 @@ async function notifyChatTurnFailure(job: JobDoc, outcome: JobTerminalOutcome):
|
|
|
34
34
|
const payload = JSON.parse(job.payload_json) as WebchatTurnPayload;
|
|
35
35
|
const channel = payload.channel ?? "webchat";
|
|
36
36
|
let userId = payload.userId;
|
|
37
|
+
let threadId = payload.threadId;
|
|
37
38
|
|
|
38
39
|
if (!userId) {
|
|
39
40
|
// Live webchat turns ("message"/"audio"/"a2ui") never carry userId in the
|
|
@@ -41,6 +42,9 @@ async function notifyChatTurnFailure(job: JobDoc, outcome: JobTerminalOutcome):
|
|
|
41
42
|
try {
|
|
42
43
|
const ctx = await resolveContext({ channel: "webchat", channelUserId: payload.sessionId });
|
|
43
44
|
userId = ctx.userId;
|
|
45
|
+
// El hilo sólo afina a qué chat del canal vuelve el aviso: si no se puede
|
|
46
|
+
// averiguar, se manda igual por la identidad del canal.
|
|
47
|
+
threadId = threadId ?? ctx.threadId;
|
|
44
48
|
} catch (err) {
|
|
45
49
|
log.warn(`[notifyChatTurnFailure] Could not resolve a recipient for job ${job.id}: ${(err as Error).message}`);
|
|
46
50
|
return;
|
|
@@ -50,7 +54,8 @@ async function notifyChatTurnFailure(job: JobDoc, outcome: JobTerminalOutcome):
|
|
|
50
54
|
await sendToUserChannel(
|
|
51
55
|
channel,
|
|
52
56
|
userId,
|
|
53
|
-
"No pude completar tu solicitud por un error interno. Por favor
|
|
57
|
+
"No pude completar tu solicitud por un error interno. Por favor intenta de nuevo.",
|
|
58
|
+
{ threadId }
|
|
54
59
|
).catch((err) => log.warn(`[notifyChatTurnFailure] Delivery failed for job ${job.id}: ${(err as Error).message}`));
|
|
55
60
|
}
|
|
56
61
|
|
|
@@ -63,7 +68,8 @@ async function notifyGoalRunFailure(job: JobDoc, outcome: JobTerminalOutcome): P
|
|
|
63
68
|
await sendToUserChannel(
|
|
64
69
|
run.channel,
|
|
65
70
|
run.user_id,
|
|
66
|
-
`No pude completar la tarea. Motivo: ${outcome.error ?? "error desconocido"}
|
|
71
|
+
`No pude completar la tarea. Motivo: ${outcome.error ?? "error desconocido"}`,
|
|
72
|
+
{ threadId: run.thread_id }
|
|
67
73
|
).catch((err) => log.warn(`[notifyGoalRunFailure] Delivery failed for job ${job.id}: ${(err as Error).message}`));
|
|
68
74
|
}
|
|
69
75
|
|
|
@@ -361,7 +361,7 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
361
361
|
|
|
362
362
|
const notify = async (text: string) => {
|
|
363
363
|
if (channel && notifyUserId) {
|
|
364
|
-
await sendToUserChannel(channel, notifyUserId, text).catch(() => {});
|
|
364
|
+
await sendToUserChannel(channel, notifyUserId, text, { threadId }).catch(() => {});
|
|
365
365
|
}
|
|
366
366
|
};
|
|
367
367
|
|
|
@@ -404,8 +404,8 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
const turnMessage = attempts === 0
|
|
407
|
-
? `Meta: ${goal}\n\
|
|
408
|
-
: `La meta aún no se verificó como cumplida.\nMeta: "${goal}"\nRazón del verificador: ${lastReason}\nPresupuesto restante: ${maxAttempts - attempts} intento(s), ${maxTurns - turnsUsed} turno(s).\
|
|
407
|
+
? `Meta: ${goal}\n\nTrabaja hasta cumplir esta meta. Explica el resultado al terminar.`
|
|
408
|
+
: `La meta aún no se verificó como cumplida.\nMeta: "${goal}"\nRazón del verificador: ${lastReason}\nPresupuesto restante: ${maxAttempts - attempts} intento(s), ${maxTurns - turnsUsed} turno(s).\nContinúa trabajando para cumplirla.`;
|
|
409
409
|
|
|
410
410
|
// One turn (non-durable: the goal row carries the durable state)
|
|
411
411
|
let turnTokens = 0;
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { col, fromIndexable } from "../../storage/hive";
|
|
19
|
-
import type { AgentRunDoc, JobDoc, TaskDoc } from "../../storage/collections";
|
|
19
|
+
import type { AgentDoc, AgentRunDoc, JobDoc, NarrationEventDoc, TaskDoc } from "../../storage/collections";
|
|
20
|
+
import { getAgentLiveStates } from "../../canvas/emitter";
|
|
20
21
|
import { logger } from "../../utils/logger";
|
|
21
22
|
import type { LLMToolDef } from "../../agent/llm-client";
|
|
22
23
|
import { enqueueChatTurn } from "../webchat-turn";
|
|
@@ -60,8 +61,10 @@ export const BRIDGE_TOOLS: LLMToolDef[] = [
|
|
|
60
61
|
function: {
|
|
61
62
|
name: STATUS_TOOL,
|
|
62
63
|
description:
|
|
63
|
-
"Devuelve
|
|
64
|
-
"
|
|
64
|
+
"Devuelve lo que pasa en la colmena ahora mismo: qué hace Bee, qué especialista tiene cada " +
|
|
65
|
+
"tarea y con qué herramienta trabaja, qué terminó hace poco con su resultado o error, y los " +
|
|
66
|
+
"últimos pasos de esta conversación. Es instantánea: úsala siempre que el usuario pregunte " +
|
|
67
|
+
"qué está pasando, quién trabaja, cómo va, qué salió o por qué tarda, en vez de suponerlo.",
|
|
65
68
|
parameters: { type: "object", properties: {} },
|
|
66
69
|
},
|
|
67
70
|
},
|
|
@@ -78,8 +81,15 @@ export const BRIDGE_TOOLS: LLMToolDef[] = [
|
|
|
78
81
|
];
|
|
79
82
|
|
|
80
83
|
export interface BridgeContext {
|
|
81
|
-
/** sessionId del WebChat del usuario:
|
|
84
|
+
/** sessionId del WebChat del usuario: identifica al usuario y su socket, no la conversación. */
|
|
82
85
|
sessionId: string;
|
|
86
|
+
/**
|
|
87
|
+
* La conversación de la llamada, la misma del chat escrito. Es el lane de la
|
|
88
|
+
* cola: los turnos de voz iban al lane del sessionId mientras Bee trabajaba en
|
|
89
|
+
* la conversación, así que corrían en paralelo con los del chat, y el resumen
|
|
90
|
+
* de lo delegado —que vuelve al lane de la conversación— nunca llegaba a la voz.
|
|
91
|
+
*/
|
|
92
|
+
threadId: string;
|
|
83
93
|
userId: string;
|
|
84
94
|
/** Inyecta texto en la sesión de voz para que Bee lo diga. */
|
|
85
95
|
speak: (text: string) => void;
|
|
@@ -111,7 +121,7 @@ export async function executeBridgeTool(
|
|
|
111
121
|
/**
|
|
112
122
|
* Peticiones vivas por sesión. La sesión de voz reintenta con facilidad: cada
|
|
113
123
|
* hito narrado vuelve a entrar como turno y el modelo, viendo un pedido "sin
|
|
114
|
-
* responder", delega otra vez. Sin esta guarda, un solo "
|
|
124
|
+
* responder", delega otra vez. Sin esta guarda, un solo "lístame los archivos"
|
|
115
125
|
* terminaba en tres tareas idénticas gastando tokens en paralelo.
|
|
116
126
|
*/
|
|
117
127
|
const enCurso = new Map<string, Array<{ peticion: string; jobId: string; at: number }>>();
|
|
@@ -141,7 +151,7 @@ const MINIMO_COMUNES = 3;
|
|
|
141
151
|
* Solapamiento (Szymkiewicz–Simpson), no Jaccard.
|
|
142
152
|
*
|
|
143
153
|
* Lo que se compara son dos reformulaciones que hizo el propio modelo del mismo
|
|
144
|
-
* pedido, y suelen tener largos muy distintos ("
|
|
154
|
+
* pedido, y suelen tener largos muy distintos ("lista los archivos" vs "El
|
|
145
155
|
* usuario pide que liste los archivos del espacio de trabajo"). Jaccard castiga
|
|
146
156
|
* esa asimetría y daba 0.3 a pedidos idénticos; el solapamiento la ignora.
|
|
147
157
|
*
|
|
@@ -228,17 +238,19 @@ async function consultarABee(
|
|
|
228
238
|
: undefined;
|
|
229
239
|
|
|
230
240
|
const job = await enqueueChatTurn({
|
|
231
|
-
lane: ctx.
|
|
241
|
+
lane: ctx.threadId,
|
|
232
242
|
payload: {
|
|
233
243
|
source: "realtime",
|
|
234
244
|
sessionId: ctx.sessionId,
|
|
245
|
+
threadId: ctx.threadId,
|
|
246
|
+
userId: ctx.userId,
|
|
235
247
|
content: peticion,
|
|
236
248
|
// Sin preferAudio: la voz la pone la sesión Live, no el TTS de cascada.
|
|
237
249
|
},
|
|
238
250
|
live,
|
|
239
251
|
});
|
|
240
252
|
|
|
241
|
-
log.info(`[${CONSULT_TOOL}] job=${job.id} lane=${ctx.
|
|
253
|
+
log.info(`[${CONSULT_TOOL}] job=${job.id} lane=${ctx.threadId}`);
|
|
242
254
|
enCurso.set(ctx.sessionId, [...vivas, { peticion, jobId: job.id, at: Date.now() }]);
|
|
243
255
|
void seguirTurno(job.id, ctx);
|
|
244
256
|
|
|
@@ -282,7 +294,7 @@ async function seguirTurno(jobId: string, ctx: BridgeContext): Promise<void> {
|
|
|
282
294
|
delay = Math.min(delay * 1.4, 3_000);
|
|
283
295
|
if (!ctx.isAlive()) return;
|
|
284
296
|
|
|
285
|
-
const jobs = await jobsDelLaneDesde(ctx.
|
|
297
|
+
const jobs = await jobsDelLaneDesde(ctx.threadId, t0, jobId);
|
|
286
298
|
if (!jobs.length) return;
|
|
287
299
|
|
|
288
300
|
for (const job of jobs) {
|
|
@@ -351,30 +363,96 @@ function extraerContenido(resultJson: string | null): string {
|
|
|
351
363
|
}
|
|
352
364
|
}
|
|
353
365
|
|
|
366
|
+
/** Lo que BIA mira del enjambre: una ronda reciente, no toda la historia. */
|
|
367
|
+
const ESTADO_VENTANA_MS = 15 * 60_000;
|
|
368
|
+
const ESTADO_MAX_PASOS = 8;
|
|
369
|
+
|
|
370
|
+
const resumirTexto = (text: string | null | undefined, max: number): string | null => {
|
|
371
|
+
if (!text) return null;
|
|
372
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
373
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* La foto del enjambre para la voz. La Live API no deja darle contexto sin que
|
|
378
|
+
* lo diga en voz alta (todo texto inyectado cuenta como turno del usuario), así
|
|
379
|
+
* que en vez de empujarle cada paso, BIA lo consulta cuando lo necesita: qué
|
|
380
|
+
* hace Bee, qué hace cada especialista con qué herramienta, qué terminó y los
|
|
381
|
+
* últimos pasos de esta conversación. Antes sólo veía nombres de tareas.
|
|
382
|
+
*/
|
|
354
383
|
async function estadoDeLaColmena(ctx: BridgeContext): Promise<Record<string, unknown>> {
|
|
355
384
|
try {
|
|
356
|
-
const
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
385
|
+
const now = Date.now();
|
|
386
|
+
const [tasksCol, runsCol, agentsCol, eventsCol] = await Promise.all([
|
|
387
|
+
col<TaskDoc>("tasks"), col<AgentRunDoc>("agentRuns"), col<AgentDoc>("agents"), col<NarrationEventDoc>("narrationEvents"),
|
|
388
|
+
]);
|
|
389
|
+
const agents = new Map((await agentsCol.scan({})).map((e) => [e.id, e.doc]));
|
|
390
|
+
const nameOf = (id: string | null | undefined) => (id ? agents.get(id)?.name ?? id : "sin asignar");
|
|
391
|
+
const live = new Map(getAgentLiveStates().map((s) => [s.agentId, s]));
|
|
392
|
+
|
|
393
|
+
const coordinator = [...agents.values()].find((a) => a.role === "coordinator");
|
|
394
|
+
const coordLive = coordinator ? live.get(coordinator.id) : undefined;
|
|
395
|
+
const bee = coordLive && coordLive.status !== "idle"
|
|
396
|
+
? { estado: coordLive.status === "tool_call" ? "usando una herramienta" : "pensando", herramienta: coordLive.currentTool }
|
|
397
|
+
: { estado: "libre" };
|
|
398
|
+
|
|
399
|
+
const mine = async (task: TaskDoc) => {
|
|
400
|
+
const run = task.run_id ? await runsCol.get(task.run_id) : null;
|
|
401
|
+
return !!run && run.doc.user_id === ctx.userId;
|
|
402
|
+
};
|
|
403
|
+
const recent = (await tasksCol.scan({})).map((e) => e.doc)
|
|
404
|
+
.filter((t) => t.status === "pending" || t.status === "in_progress" || now - t.updated_at < ESTADO_VENTANA_MS)
|
|
360
405
|
.sort((a, b) => b.updated_at - a.updated_at)
|
|
361
|
-
.slice(0,
|
|
406
|
+
.slice(0, 20);
|
|
362
407
|
|
|
363
408
|
const activas: Array<Record<string, unknown>> = [];
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
if (!
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
409
|
+
const terminadas: Array<Record<string, unknown>> = [];
|
|
410
|
+
for (const task of recent) {
|
|
411
|
+
if (!(await mine(task))) continue;
|
|
412
|
+
const agentId = fromIndexable(task.agent_id);
|
|
413
|
+
if (task.status === "pending" || task.status === "in_progress") {
|
|
414
|
+
const state = agentId ? live.get(agentId) : undefined;
|
|
415
|
+
activas.push({
|
|
416
|
+
tarea: task.name,
|
|
417
|
+
especialista: nameOf(agentId),
|
|
418
|
+
estado: task.status === "in_progress" ? "en curso" : "en cola",
|
|
419
|
+
herramienta_actual: state?.currentTool ?? null,
|
|
420
|
+
progreso: task.progress,
|
|
421
|
+
});
|
|
422
|
+
} else if (task.status === "completed" || task.status === "failed") {
|
|
423
|
+
terminadas.push({
|
|
424
|
+
tarea: task.name,
|
|
425
|
+
especialista: nameOf(agentId),
|
|
426
|
+
resultado: task.status === "completed" ? "completada" : "falló",
|
|
427
|
+
resumen: resumirTexto(task.status === "completed" ? task.result : task.error, 200),
|
|
428
|
+
hace_segundos: Math.round((now - task.updated_at) / 1000),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
373
431
|
}
|
|
374
432
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
433
|
+
const pasos = (await eventsCol.findBy("thread_id", ctx.threadId)).map((e) => e.doc)
|
|
434
|
+
.filter((e) => now - e.created_at < ESTADO_VENTANA_MS)
|
|
435
|
+
.sort((a, b) => b.created_at - a.created_at)
|
|
436
|
+
.slice(0, ESTADO_MAX_PASOS)
|
|
437
|
+
.map((e) => ({
|
|
438
|
+
agente: e.agent_name || nameOf(e.agent_id),
|
|
439
|
+
paso: e.label,
|
|
440
|
+
estado: e.status,
|
|
441
|
+
detalle: resumirTexto(e.detail, 120),
|
|
442
|
+
hace_segundos: Math.round((now - e.created_at) / 1000),
|
|
443
|
+
}));
|
|
444
|
+
|
|
445
|
+
return {
|
|
446
|
+
ok: true,
|
|
447
|
+
bee,
|
|
448
|
+
tareas_activas: activas.length,
|
|
449
|
+
tareas: activas,
|
|
450
|
+
terminadas_recientes: terminadas.slice(0, 8),
|
|
451
|
+
ultimos_pasos: pasos,
|
|
452
|
+
nota: activas.length || bee.estado !== "libre"
|
|
453
|
+
? "Cuenta con tus palabras lo que está pasando; no leas la lista."
|
|
454
|
+
: "No hay nada en curso ahora mismo.",
|
|
455
|
+
};
|
|
378
456
|
} catch (error) {
|
|
379
457
|
return { ok: false, error: `No pude leer el estado: ${(error as Error).message}` };
|
|
380
458
|
}
|
|
@@ -382,9 +460,9 @@ async function estadoDeLaColmena(ctx: BridgeContext): Promise<Record<string, unk
|
|
|
382
460
|
|
|
383
461
|
async function cancelarTarea(ctx: BridgeContext): Promise<Record<string, unknown>> {
|
|
384
462
|
try {
|
|
385
|
-
const cancelados = await getDurableQueue().cancelLane(ctx.
|
|
463
|
+
const cancelados = await getDurableQueue().cancelLane(ctx.threadId);
|
|
386
464
|
return cancelados > 0
|
|
387
|
-
? { ok: true, cancelados, nota: "Trabajo cancelado.
|
|
465
|
+
? { ok: true, cancelados, nota: "Trabajo cancelado. Confírmalo en una frase corta." }
|
|
388
466
|
: { ok: true, cancelados: 0, nota: "No había nada en curso para cancelar." };
|
|
389
467
|
} catch (error) {
|
|
390
468
|
return { ok: false, error: `No pude cancelar: ${(error as Error).message}` };
|