@johpaz/hive-agents 1.0.4 → 1.1.0
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 +5 -5
- package/dist/hive.js +88127 -103024
- package/dist/tool-worker.js +13243 -17002
- package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
- package/dist/ui/assets/AgentCreateForm-DXkjtXaS.js +1 -0
- package/dist/ui/assets/AgentDetailPage-DUIX_cuQ.js +1 -0
- package/dist/ui/assets/AgentNewPage-SNXz2wik.js +1 -0
- package/dist/ui/assets/AgentsPage-CGsdgx5F.js +10 -0
- package/dist/ui/assets/{ApiClientPage-6a6KFwsQ.js → ApiClientPage-MNMjfSDs.js} +2 -2
- package/dist/ui/assets/ChannelsPage-BEwxWUcE.js +8 -0
- package/dist/ui/assets/DashboardPage-D6cRFKWW.js +6 -0
- package/dist/ui/assets/LoginPage-ByYmIa2p.js +1 -0
- package/dist/ui/assets/LogsPage-Bmk9rohg.js +1 -0
- package/dist/ui/assets/MeetingPage-Dm97Mbiw.js +1 -0
- package/dist/ui/assets/ModelSelector-gubC8j_Q.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-Bfi-S2kG.js +727 -0
- package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +1 -0
- package/dist/ui/assets/RecoverPage-YY2QU-qh.js +1 -0
- package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
- package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
- package/dist/ui/assets/Vignette-BcPWkNhm.js +4302 -0
- package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -0
- package/dist/ui/assets/VoicePage-uLWdtoD4.css +1 -0
- package/dist/ui/assets/WebChatPage-B61ZDjQ8.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/bia-4LFKOyxR.webp +0 -0
- package/dist/ui/assets/bia-BFcUpOu3.glb +0 -0
- package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
- package/dist/ui/assets/conversationsStore-BlwA3yd2.js +1 -0
- package/dist/ui/assets/dialog-B04KpdNt.js +1 -0
- package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
- package/dist/ui/assets/{dist-js-CLxM1g2B.js → dist-js-q7C_AB0j.js} +1 -1
- package/dist/ui/assets/index-ByTufXPh.css +2 -0
- package/dist/ui/assets/index-DKJFLL3a.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/{square-psq7k_CB.js → mic-CpDU_2as.js} +1 -1
- package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
- package/dist/ui/assets/rotate-ccw-LoM1AuqK.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/square-D5zdNkAY.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-B2stUHvr.js +41 -0
- package/dist/ui/assets/useHiveAgentsModelLoad-B4EjHvj4.js +1 -0
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
- package/dist/ui/assets/{useProviders-CiLSc05q.js → useProviders-B1NS24md.js} +1 -1
- package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
- package/dist/ui/assets/volume-2-EaA0JRvD.js +1 -0
- package/dist/ui/assets/volume-x-CROXNMGT.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 +101 -46
- package/packages/cli/src/commands/onboard.ts +4 -2
- package/packages/core/src/agent/agent-catalog.ts +47 -47
- 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 +166 -28
- package/packages/core/src/agent/conversation-store.ts +26 -2
- package/packages/core/src/agent/goal-runner.ts +2 -2
- package/packages/core/src/agent/jev-decisions.ts +148 -0
- package/packages/core/src/agent/jev-planner.ts +293 -0
- package/packages/core/src/agent/llm-client.ts +29 -7
- 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/prompt-builder.ts +1 -1
- package/packages/core/src/agent/realtime-providers/gemini-live.ts +233 -0
- package/packages/core/src/agent/realtime-providers/index.ts +29 -0
- package/packages/core/src/agent/realtime-providers/interface.ts +108 -0
- package/packages/core/src/agent/skill-selector.ts +5 -3
- 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 +2 -0
- package/packages/core/src/agent/tracer.ts +2 -0
- package/packages/core/src/canvas/canvas-manager.ts +145 -27
- 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 +9 -6
- package/packages/core/src/events/tool-narration.ts +1 -0
- package/packages/core/src/gateway/channel-notify.ts +24 -5
- package/packages/core/src/gateway/delegation-groups.ts +5 -5
- 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/initializer.ts +17 -10
- package/packages/core/src/gateway/job-executors.ts +3 -3
- package/packages/core/src/gateway/realtime/bridge-tools.ts +470 -0
- package/packages/core/src/gateway/realtime/index.ts +305 -0
- package/packages/core/src/gateway/realtime/prompt.ts +182 -0
- package/packages/core/src/gateway/realtime/protocol.ts +60 -0
- package/packages/core/src/gateway/realtime/voice-session.ts +442 -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 +16 -1
- package/packages/core/src/gateway/routes/setup.ts +25 -14
- 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 +171 -13
- package/packages/core/src/gateway/slash-commands.ts +48 -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 +23 -0
- package/packages/core/src/storage/collections.ts +38 -1
- package/packages/core/src/storage/crypto.ts +23 -12
- package/packages/core/src/storage/onboarding.ts +39 -39
- package/packages/core/src/storage/reconcile.ts +6 -1
- package/packages/core/src/storage/seed.ts +82 -8
- 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/core/index.ts +39 -4
- package/packages/core/src/tools/cron/index.ts +4 -4
- package/packages/core/src/tools/index.ts +2 -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 +141 -44
- package/packages/core/src/tools/web/browser-click.ts +2 -2
- package/packages/core/src/tools/web/browser-extract.ts +2 -2
- package/packages/core/src/tools/web/browser-navigate.ts +2 -2
- package/packages/core/src/tools/web/browser-screenshot.ts +12 -5
- package/packages/core/src/tools/web/browser-script.ts +2 -2
- package/packages/core/src/tools/web/browser-service.ts +63 -384
- package/packages/core/src/tools/web/browser-session.ts +125 -0
- package/packages/core/src/tools/web/browser-type.ts +2 -2
- package/packages/core/src/tools/web/browser-wait.ts +2 -2
- package/packages/core/src/tools/web/computer-use.ts +553 -0
- package/packages/core/src/tools/web/index.ts +5 -1
- package/packages/core/src/tools/web/webview-backend.ts +559 -21
- 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/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/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 +837 -783
- package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +0 -8
- package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +0 -1
- package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +0 -1
- package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +0 -1
- package/dist/ui/assets/AgentsPage-YZrDmgNI.js +0 -10
- package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +0 -8
- package/dist/ui/assets/DashboardPage-B9r0sc0F.js +0 -6
- package/dist/ui/assets/LoginPage-BkAAX_tu.js +0 -1
- package/dist/ui/assets/LogsPage-8-H1OJs3.js +0 -1
- package/dist/ui/assets/MeetingPage-14JoQo71.js +0 -1
- package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +0 -1
- package/dist/ui/assets/NotFound-B06kVW7N.js +0 -1
- package/dist/ui/assets/Office3DPage-BMUZWkFS.js +0 -4614
- package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +0 -1
- package/dist/ui/assets/RecoverPage-D1o8yxNz.js +0 -1
- package/dist/ui/assets/SettingsPage-GP8UwQIL.js +0 -9
- package/dist/ui/assets/SetupPage-B_gU1YQU.js +0 -1
- package/dist/ui/assets/WebChatPage-Yahufnth.js +0 -29
- package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +0 -1
- package/dist/ui/assets/alert-DChoEVJw.js +0 -1
- package/dist/ui/assets/badge-uRjRSt86.js +0 -1
- package/dist/ui/assets/card-DwQizslL.js +0 -1
- package/dist/ui/assets/dialog--mljnfAi.js +0 -1
- package/dist/ui/assets/dist-js-B0s_TDau.js +0 -1
- package/dist/ui/assets/index-BHHUQZJd.js +0 -116
- package/dist/ui/assets/index-CEFhf4dF.css +0 -2
- package/dist/ui/assets/label-BceoUB2w.js +0 -1
- package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
- package/dist/ui/assets/scroll-area-DMEaZZUp.js +0 -1
- package/dist/ui/assets/select-BBEBtcLm.js +0 -1
- package/dist/ui/assets/slider-DcmBdvYD.js +0 -1
- package/dist/ui/assets/switch-CgiDezVR.js +0 -1
- package/dist/ui/assets/tabs-gUXIjjZv.js +0 -1
- package/dist/ui/assets/textarea-DedxQYBx.js +0 -1
- package/dist/ui/assets/useHiveAgentsModelLoad-C7bhWPDG.js +0 -1
- package/dist/ui/assets/useOfficeModel-BAFasrg8.js +0 -1
- package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
- package/dist/ui/assets/volume-x-BDlMCDYT.js +0 -1
- /package/dist/ui/assets/{core-Sjunb8Z1.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-BZj_2-jf.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/{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/{search-ykSx-zZU.js → search-BMwCI-pX.js} +0 -0
- /package/dist/ui/assets/{send-DAhlz2i9.js → send-D6fgWV7m.js} +0 -0
- /package/dist/ui/assets/{settings-DL0REysC.js → settings-qV3kVkeG.js} +0 -0
- /package/dist/ui/assets/{shield-BPZZhjCT.js → shield-CIarwBvx.js} +0 -0
- /package/dist/ui/assets/{sparkles-BViXTAh7.js → sparkles-DVvY6jDT.js} +0 -0
- /package/dist/ui/assets/{terminal-CzxPKG-h.js → terminal-BEcTK780.js} +0 -0
- /package/dist/ui/assets/{trash-2-SgYCWiVk.js → trash-2-D6oziYAK.js} +0 -0
- /package/dist/ui/assets/{utils-SGUggNJc.js → utils-DEmd_M8c.js} +0 -0
- /package/dist/ui/assets/{vendor-router-Dsg8fxNQ.js → vendor-router-DP84b3LQ.js} +0 -0
- /package/dist/ui/assets/{wifi-CyPHteEm.js → wifi-BUJuOcgP.js} +0 -0
- /package/dist/ui/assets/{zap-OVVrfEHr.js → zap-DSoX9NDk.js} +0 -0
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RealtimeVoiceSession — puente entre el socket del navegador y la sesión Live
|
|
3
|
+
* del proveedor.
|
|
4
|
+
*
|
|
5
|
+
* Flujo: PCM16 16 kHz del micrófono → proveedor → PCM 24 kHz de vuelta al
|
|
6
|
+
* navegador. Cuando el modelo llama a una función puente, el trabajo real se
|
|
7
|
+
* encola en el agent-loop de siempre; la narración de ese trabajo vuelve acá
|
|
8
|
+
* como texto inyectado (speak) y el modelo la cuenta con su propia voz.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { ServerWebSocket } from "bun";
|
|
12
|
+
import { addMessage } from "../../agent/conversation-store";
|
|
13
|
+
import {
|
|
14
|
+
getRealtimeProvider,
|
|
15
|
+
type RealtimeSession,
|
|
16
|
+
type RealtimeToolCall,
|
|
17
|
+
} from "../../agent/realtime-providers";
|
|
18
|
+
import { logger } from "../../utils/logger";
|
|
19
|
+
import { executeBridgeTool, olvidarPeticiones, BRIDGE_TOOLS, CONSULT_TOOL } from "./bridge-tools";
|
|
20
|
+
import type { NarrationFrame, ServerFrame } from "./protocol";
|
|
21
|
+
|
|
22
|
+
const log = logger.child("realtime:session");
|
|
23
|
+
|
|
24
|
+
/** Silencio total (ni el usuario ni el modelo dicen nada) que cierra la sesión. */
|
|
25
|
+
const IDLE_TIMEOUT_MS = 3 * 60_000;
|
|
26
|
+
/** Reintentos de reconexión antes de rendirse. */
|
|
27
|
+
const MAX_RECONNECTS = 3;
|
|
28
|
+
/**
|
|
29
|
+
* Ventana para juntar hitos antes de hablarlos. El agent-loop emite ráfagas
|
|
30
|
+
* (delegated + worker_started + tool_result en el mismo par de cientos de ms):
|
|
31
|
+
* inyectarlos de a uno hace que cada texto corte la frase anterior y el usuario
|
|
32
|
+
* escuche tartamudeo en vez de narración.
|
|
33
|
+
*/
|
|
34
|
+
const NARRATION_COALESCE_MS = 1_500;
|
|
35
|
+
/** Lo mismo para resultados y errores, que sí corren prisa. */
|
|
36
|
+
const URGENT_COALESCE_MS = 250;
|
|
37
|
+
/** Cuánto esperamos a que termine de hablar antes de forzar la inyección. */
|
|
38
|
+
const GENERATING_MAX_MS = 20_000;
|
|
39
|
+
/** Hitos que se acumulan mientras habla; sólo interesan los últimos. */
|
|
40
|
+
const MAX_QUEUED_NARRATION = 4;
|
|
41
|
+
|
|
42
|
+
export interface VoiceSessionOptions {
|
|
43
|
+
ws: ServerWebSocket<unknown>;
|
|
44
|
+
/** sessionId del WebChat: lane de la cola y, a la vez, hilo de conversación. */
|
|
45
|
+
sessionId: string;
|
|
46
|
+
userId: string;
|
|
47
|
+
threadId: string;
|
|
48
|
+
providerId: string;
|
|
49
|
+
model: string;
|
|
50
|
+
apiKey: string;
|
|
51
|
+
voice?: string;
|
|
52
|
+
/** BCP-47 con acento regional (es-CO, es-MX…). */
|
|
53
|
+
language?: string;
|
|
54
|
+
/** La voz sale por un altavoz abierto y el micrófono la recoge. */
|
|
55
|
+
speakerMode?: boolean;
|
|
56
|
+
systemInstruction: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class RealtimeVoiceSession {
|
|
60
|
+
private session: RealtimeSession | null = null;
|
|
61
|
+
private resumptionHandle: string | undefined;
|
|
62
|
+
private closed = false;
|
|
63
|
+
private reconnects = 0;
|
|
64
|
+
private lastActivityAt = Date.now();
|
|
65
|
+
private idleTimer: ReturnType<typeof setInterval> | null = null;
|
|
66
|
+
|
|
67
|
+
/** Transcripciones del turno en curso, para persistir la charla que no delegó. */
|
|
68
|
+
private userTurnText = "";
|
|
69
|
+
private modelTurnText = "";
|
|
70
|
+
private delegatedThisTurn = false;
|
|
71
|
+
|
|
72
|
+
/** Cola de textos a inyectar (narración, resultados) con su temporizador. */
|
|
73
|
+
private speechQueue: string[] = [];
|
|
74
|
+
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
75
|
+
/** El modelo está hablando: inyectar ahora lo cortaría a media frase. */
|
|
76
|
+
private generatingSince = 0;
|
|
77
|
+
|
|
78
|
+
/** Qué está viendo ahora mismo, para anunciarlo sólo cuando cambia. */
|
|
79
|
+
private fuenteVisual: "camera" | "screen" | null = null;
|
|
80
|
+
|
|
81
|
+
/** Consumo de la sesión y el acumulado de tramos anteriores (reconexiones). */
|
|
82
|
+
private usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
83
|
+
private usageBase = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
84
|
+
|
|
85
|
+
/** Nº de conexión: los callbacks de generaciones viejas se descartan. */
|
|
86
|
+
private generation = 0;
|
|
87
|
+
/** Evita que goAway y onClose disparen dos reconexiones a la vez. */
|
|
88
|
+
private reconnecting = false;
|
|
89
|
+
|
|
90
|
+
constructor(private readonly opts: VoiceSessionOptions) {}
|
|
91
|
+
|
|
92
|
+
get sessionId(): string {
|
|
93
|
+
return this.opts.sessionId;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
get isAlive(): boolean {
|
|
97
|
+
return !this.closed && this.opts.ws.readyState === 1;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async start(): Promise<void> {
|
|
101
|
+
await this.connect();
|
|
102
|
+
this.idleTimer = setInterval(() => {
|
|
103
|
+
if (Date.now() - this.lastActivityAt > IDLE_TIMEOUT_MS) {
|
|
104
|
+
log.info(`sesión ${this.opts.sessionId} cerrada por inactividad`);
|
|
105
|
+
this.send({ type: "closed", reason: "inactividad" });
|
|
106
|
+
this.close();
|
|
107
|
+
}
|
|
108
|
+
}, 15_000);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private async connect(): Promise<void> {
|
|
112
|
+
const provider = getRealtimeProvider(this.opts.providerId);
|
|
113
|
+
|
|
114
|
+
// Número de conexión. Gemini avisa con `goAway` y cierra el socket casi en
|
|
115
|
+
// el mismo milisegundo; si las dos señales llegan a crear sesiones, la que
|
|
116
|
+
// pierde la carrera queda huérfana pero con sus callbacks intactos, y sigue
|
|
117
|
+
// ejecutando herramientas contra la colmena. Comparando la generación al
|
|
118
|
+
// entrar, una sesión ya reemplazada deja de tener efecto.
|
|
119
|
+
const gen = ++this.generation;
|
|
120
|
+
const vigente = () => gen === this.generation && !this.closed;
|
|
121
|
+
|
|
122
|
+
const session = await provider.connect({
|
|
123
|
+
model: this.opts.model,
|
|
124
|
+
apiKey: this.opts.apiKey,
|
|
125
|
+
systemInstruction: this.opts.systemInstruction,
|
|
126
|
+
tools: BRIDGE_TOOLS,
|
|
127
|
+
voice: this.opts.voice,
|
|
128
|
+
language: this.opts.language,
|
|
129
|
+
silenceDurationMs: 600,
|
|
130
|
+
// En manos libres se le sube el listón para darse por interrumpido: el
|
|
131
|
+
// eco de un televisor al fondo de la sala no debe contar como alguien
|
|
132
|
+
// hablándole encima.
|
|
133
|
+
startOfSpeechSensitivity: this.opts.speakerMode ? "START_SENSITIVITY_LOW" : undefined,
|
|
134
|
+
resumptionHandle: this.resumptionHandle,
|
|
135
|
+
callbacks: {
|
|
136
|
+
onAudio: (pcm) => {
|
|
137
|
+
if (!vigente()) return;
|
|
138
|
+
this.lastActivityAt = Date.now();
|
|
139
|
+
if (!this.generatingSince) this.generatingSince = Date.now();
|
|
140
|
+
this.sendBinary(pcm);
|
|
141
|
+
},
|
|
142
|
+
onInputTranscript: (text) => {
|
|
143
|
+
if (!vigente()) return;
|
|
144
|
+
this.lastActivityAt = Date.now();
|
|
145
|
+
this.userTurnText += text;
|
|
146
|
+
this.send({ type: "transcript", role: "user", text });
|
|
147
|
+
},
|
|
148
|
+
onOutputTranscript: (text) => {
|
|
149
|
+
if (!vigente()) return;
|
|
150
|
+
this.lastActivityAt = Date.now();
|
|
151
|
+
this.modelTurnText += text;
|
|
152
|
+
this.send({ type: "transcript", role: "assistant", text });
|
|
153
|
+
},
|
|
154
|
+
onInterrupted: () => {
|
|
155
|
+
if (!vigente()) return;
|
|
156
|
+
this.generatingSince = 0;
|
|
157
|
+
this.send({ type: "interrupted" });
|
|
158
|
+
},
|
|
159
|
+
onTurnComplete: () => {
|
|
160
|
+
if (!vigente()) return;
|
|
161
|
+
this.generatingSince = 0;
|
|
162
|
+
void this.persistTurn();
|
|
163
|
+
this.send({ type: "turn_complete" });
|
|
164
|
+
// Lo que se acumuló mientras hablaba puede salir ya.
|
|
165
|
+
if (this.speechQueue.length) this.scheduleFlush(URGENT_COALESCE_MS);
|
|
166
|
+
},
|
|
167
|
+
onToolCall: (calls) => {
|
|
168
|
+
// La comprobación más importante de todas: una sesión reemplazada que
|
|
169
|
+
// pida ejecutar una herramienta duplicaría trabajo real en la colmena.
|
|
170
|
+
if (!vigente()) {
|
|
171
|
+
log.warn(`toolCall descartada: llegó de una sesión ya reemplazada (gen ${gen})`);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
void this.runToolCalls(calls);
|
|
175
|
+
},
|
|
176
|
+
onUsage: (usage) => {
|
|
177
|
+
if (!vigente()) return;
|
|
178
|
+
// El proveedor reporta el acumulado de la sesión, no el delta; una
|
|
179
|
+
// reconexión reinicia su contador, así que se suma por tramo.
|
|
180
|
+
this.usage = {
|
|
181
|
+
inputTokens: this.usageBase.inputTokens + usage.inputTokens,
|
|
182
|
+
outputTokens: this.usageBase.outputTokens + usage.outputTokens,
|
|
183
|
+
totalTokens: this.usageBase.totalTokens + usage.totalTokens,
|
|
184
|
+
};
|
|
185
|
+
this.send({ type: "usage", ...this.usage });
|
|
186
|
+
},
|
|
187
|
+
onResumptionHandle: (handle) => {
|
|
188
|
+
if (!vigente()) return;
|
|
189
|
+
this.resumptionHandle = handle;
|
|
190
|
+
},
|
|
191
|
+
onGoAway: (timeLeftMs) => {
|
|
192
|
+
if (!vigente()) return;
|
|
193
|
+
log.info(`goAway en ${timeLeftMs}ms — reconectando con handle`);
|
|
194
|
+
void this.reconnect();
|
|
195
|
+
},
|
|
196
|
+
onError: (error) => {
|
|
197
|
+
if (!vigente()) return;
|
|
198
|
+
log.warn(`error del proveedor: ${error.message}`);
|
|
199
|
+
this.send({ type: "error", error: error.message });
|
|
200
|
+
},
|
|
201
|
+
onClose: (reason) => {
|
|
202
|
+
if (!vigente()) return;
|
|
203
|
+
// Cierre no solicitado: la sesión sigue viva del lado del navegador,
|
|
204
|
+
// así que se retoma con el handle en vez de dejar al usuario mudo.
|
|
205
|
+
log.info(`sesión upstream cerrada (${reason || "sin motivo"}) — reconectando`);
|
|
206
|
+
void this.reconnect();
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// Si mientras se abría esta conexión llegó otra generación (o se cerró la
|
|
212
|
+
// sesión), la recién creada sobra: se cierra en el acto en vez de quedar
|
|
213
|
+
// hablando con Gemini sin que nadie la escuche.
|
|
214
|
+
if (gen !== this.generation || this.closed) {
|
|
215
|
+
try {
|
|
216
|
+
session.close();
|
|
217
|
+
} catch {
|
|
218
|
+
/* nunca llegó a abrirse del todo */
|
|
219
|
+
}
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
this.session = session;
|
|
224
|
+
this.send({ type: "ready", model: this.opts.model, voice: this.opts.voice ?? null });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async reconnect(): Promise<void> {
|
|
228
|
+
if (this.closed) return;
|
|
229
|
+
// goAway y el cierre del socket llegan juntos: sin esta guarda cada uno
|
|
230
|
+
// abría su propia sesión y quedaban dos vivas contra el mismo hilo.
|
|
231
|
+
if (this.reconnecting) return;
|
|
232
|
+
if (this.reconnects >= MAX_RECONNECTS) {
|
|
233
|
+
this.send({ type: "error", error: "No pude reconectar con el modelo de voz." });
|
|
234
|
+
this.close();
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
this.reconnecting = true;
|
|
238
|
+
this.reconnects++;
|
|
239
|
+
// El contador del proveedor arranca de cero en la conexión nueva.
|
|
240
|
+
this.usageBase = { ...this.usage };
|
|
241
|
+
try {
|
|
242
|
+
this.session?.close();
|
|
243
|
+
} catch {
|
|
244
|
+
/* ya estaba cerrada */
|
|
245
|
+
}
|
|
246
|
+
this.session = null;
|
|
247
|
+
try {
|
|
248
|
+
await this.connect();
|
|
249
|
+
this.reconnects = 0;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
log.warn(`reconexión ${this.reconnects} falló: ${(error as Error).message}`);
|
|
252
|
+
// El reintento se agenda con la guarda ya liberada, si no quedaría mudo.
|
|
253
|
+
setTimeout(() => void this.reconnect(), 1_000 * this.reconnects);
|
|
254
|
+
} finally {
|
|
255
|
+
this.reconnecting = false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ── Entrada desde el navegador ─────────────────────────────────────────────
|
|
260
|
+
|
|
261
|
+
handleAudio(pcm: ArrayBufferLike): void {
|
|
262
|
+
if (!this.session || this.closed) return;
|
|
263
|
+
this.session.sendAudio(pcm);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Fotograma de imagen del usuario: cámara o pantalla compartida.
|
|
268
|
+
*
|
|
269
|
+
* Cuenta como actividad para el temporizador de inactividad: alguien que
|
|
270
|
+
* comparte pantalla en silencio sigue esperando ayuda, y cerrarle la sesión
|
|
271
|
+
* a los tres minutos sería absurdo.
|
|
272
|
+
*/
|
|
273
|
+
handleVideoFrame(base64: string, mimeType: string, source: "camera" | "screen" = "camera"): void {
|
|
274
|
+
if (!this.session || this.closed || !base64) return;
|
|
275
|
+
this.lastActivityAt = Date.now();
|
|
276
|
+
if (this.fuenteVisual !== source) {
|
|
277
|
+
this.fuenteVisual = source;
|
|
278
|
+
// Un aviso al entrar, no en cada fotograma: el modelo necesita saber qué
|
|
279
|
+
// empieza a ver, pero repetirlo 60 veces por minuto ahogaría la charla.
|
|
280
|
+
this.speak(
|
|
281
|
+
source === "screen"
|
|
282
|
+
? "[HIVE] La persona empezó a compartir su pantalla. Ya la ves."
|
|
283
|
+
: "[HIVE] La persona encendió su cámara. Ya la ves.",
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
this.session.sendVideoFrame(base64, mimeType);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Deja de ver: la próxima fuente vuelve a anunciarse. */
|
|
290
|
+
olvidarFuenteVisual(): void {
|
|
291
|
+
this.fuenteVisual = null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Texto tipeado por el usuario: va directo, es él quien decide interrumpir. */
|
|
295
|
+
handleText(text: string): void {
|
|
296
|
+
if (!this.session || this.closed) return;
|
|
297
|
+
this.lastActivityAt = Date.now();
|
|
298
|
+
this.session.sendText(text);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Inyecta un hito de la colmena para que el modelo lo cuente hablando. No se
|
|
303
|
+
* envía en el acto: se junta con los que vengan detrás y espera a que el
|
|
304
|
+
* modelo termine la frase en curso.
|
|
305
|
+
*/
|
|
306
|
+
speak(text: string): void {
|
|
307
|
+
this.enqueueSpeech(text, NARRATION_COALESCE_MS);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Resultados y errores: mismo camino, pero sin esperar a más hitos. */
|
|
311
|
+
speakUrgent(text: string): void {
|
|
312
|
+
this.enqueueSpeech(text, URGENT_COALESCE_MS);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Manda el hito a la UI. Va aparte de `speak()` porque el panel muestra TODO
|
|
317
|
+
* lo que hace la colmena, mientras que la voz sólo cuenta los hitos: leer en
|
|
318
|
+
* voz alta cada paso sería insoportable, pero verlos escritos es justamente
|
|
319
|
+
* lo que hace que la espera se entienda.
|
|
320
|
+
*/
|
|
321
|
+
sendNarration(frame: Omit<NarrationFrame, "type">): void {
|
|
322
|
+
this.send({ type: "narration", ...frame });
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
private enqueueSpeech(text: string, delay: number): void {
|
|
326
|
+
if (!this.session || this.closed || !text.trim()) return;
|
|
327
|
+
this.lastActivityAt = Date.now();
|
|
328
|
+
this.speechQueue.push(text);
|
|
329
|
+
if (this.speechQueue.length > MAX_QUEUED_NARRATION) {
|
|
330
|
+
this.speechQueue.splice(0, this.speechQueue.length - MAX_QUEUED_NARRATION);
|
|
331
|
+
}
|
|
332
|
+
this.scheduleFlush(delay);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private scheduleFlush(delay: number): void {
|
|
336
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
337
|
+
this.flushTimer = setTimeout(() => this.flushSpeech(), delay);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private flushSpeech(): void {
|
|
341
|
+
this.flushTimer = null;
|
|
342
|
+
if (!this.speechQueue.length || !this.session || this.closed) return;
|
|
343
|
+
|
|
344
|
+
// Sigue hablando: reintentamos en breve en vez de cortarlo. El tope evita
|
|
345
|
+
// que un turnComplete perdido deje la narración muda para siempre.
|
|
346
|
+
if (this.generatingSince && Date.now() - this.generatingSince < GENERATING_MAX_MS) {
|
|
347
|
+
this.scheduleFlush(400);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const text = this.speechQueue.join("\n");
|
|
352
|
+
this.speechQueue = [];
|
|
353
|
+
this.session.sendText(text);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ── Funciones puente ───────────────────────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
private async runToolCalls(calls: RealtimeToolCall[]): Promise<void> {
|
|
359
|
+
for (const call of calls) {
|
|
360
|
+
if (call.name === CONSULT_TOOL) this.delegatedThisTurn = true;
|
|
361
|
+
let result: Record<string, unknown>;
|
|
362
|
+
try {
|
|
363
|
+
result = await executeBridgeTool(call.name, call.args, {
|
|
364
|
+
sessionId: this.opts.sessionId,
|
|
365
|
+
threadId: this.opts.threadId,
|
|
366
|
+
userId: this.opts.userId,
|
|
367
|
+
speak: (text) => this.speakUrgent(text),
|
|
368
|
+
isAlive: () => this.isAlive,
|
|
369
|
+
});
|
|
370
|
+
} catch (error) {
|
|
371
|
+
result = { ok: false, error: (error as Error).message };
|
|
372
|
+
}
|
|
373
|
+
this.send({ type: "tool", name: call.name, ok: result.ok !== false });
|
|
374
|
+
this.session?.sendToolResult(call.id, call.name, result);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ── Persistencia ───────────────────────────────────────────────────────────
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Guarda en el hilo la charla hablada que NO pasó por la colmena. Cuando se
|
|
382
|
+
* delegó, el chat_turn ya persistió la petición y la respuesta: escribirlas
|
|
383
|
+
* otra vez acá duplicaría el historial.
|
|
384
|
+
*/
|
|
385
|
+
private async persistTurn(): Promise<void> {
|
|
386
|
+
const user = this.userTurnText.trim();
|
|
387
|
+
const model = this.modelTurnText.trim();
|
|
388
|
+
this.userTurnText = "";
|
|
389
|
+
this.modelTurnText = "";
|
|
390
|
+
const delegated = this.delegatedThisTurn;
|
|
391
|
+
this.delegatedThisTurn = false;
|
|
392
|
+
|
|
393
|
+
if (delegated || (!user && !model)) return;
|
|
394
|
+
|
|
395
|
+
try {
|
|
396
|
+
// `realtime_chat` (no `realtime`): esto ya se respondió hablando. Marcarlo
|
|
397
|
+
// como turno normal hacía que el coordinador lo leyera como pedido nuevo y
|
|
398
|
+
// delegara una tarea por cada frase suelta de la llamada.
|
|
399
|
+
if (user) await addMessage(this.opts.threadId, "user", user, { channel: "webchat", source: "realtime_chat" });
|
|
400
|
+
if (model) await addMessage(this.opts.threadId, "assistant", model, { channel: "webchat", source: "realtime_chat" });
|
|
401
|
+
} catch (error) {
|
|
402
|
+
log.warn(`no pude persistir el turno hablado: ${(error as Error).message}`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ── Salida hacia el navegador ──────────────────────────────────────────────
|
|
407
|
+
|
|
408
|
+
private send(frame: ServerFrame): void {
|
|
409
|
+
if (this.opts.ws.readyState !== 1) return;
|
|
410
|
+
try {
|
|
411
|
+
this.opts.ws.send(JSON.stringify(frame));
|
|
412
|
+
} catch {
|
|
413
|
+
/* el navegador se fue */
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private sendBinary(pcm: Buffer): void {
|
|
418
|
+
if (this.opts.ws.readyState !== 1) return;
|
|
419
|
+
try {
|
|
420
|
+
this.opts.ws.send(pcm);
|
|
421
|
+
} catch {
|
|
422
|
+
/* el navegador se fue */
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
close(): void {
|
|
427
|
+
if (this.closed) return;
|
|
428
|
+
this.closed = true;
|
|
429
|
+
if (this.idleTimer) clearInterval(this.idleTimer);
|
|
430
|
+
this.idleTimer = null;
|
|
431
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
432
|
+
this.flushTimer = null;
|
|
433
|
+
this.speechQueue = [];
|
|
434
|
+
olvidarPeticiones(this.opts.sessionId);
|
|
435
|
+
try {
|
|
436
|
+
this.session?.close();
|
|
437
|
+
} catch {
|
|
438
|
+
/* ya estaba cerrada */
|
|
439
|
+
}
|
|
440
|
+
this.session = null;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { col } from "../storage/hive"
|
|
2
2
|
import type { UserIdentityDoc, UserDoc, AgentDoc } from "../storage/collections"
|
|
3
|
+
import { ensureThread, mostRecentWebThread, createWebConversation } from "../agent/thread-store"
|
|
3
4
|
|
|
4
5
|
export interface ResolveContextResult {
|
|
5
6
|
userId: string
|
|
@@ -13,6 +14,13 @@ export interface ResolveContextOptions {
|
|
|
13
14
|
channelUserId: string
|
|
14
15
|
/** Channel account the message arrived on — persisted so replies can be routed back to it. */
|
|
15
16
|
accountId?: string
|
|
17
|
+
/**
|
|
18
|
+
* Conversación concreta dentro del canal: el contacto o grupo en mensajería, el id
|
|
19
|
+
* de conversación en la web. Si falta, en los canales se usa `channelUserId` y en
|
|
20
|
+
* la web la conversación más reciente (o una nueva, si no hay ninguna).
|
|
21
|
+
*/
|
|
22
|
+
peerId?: string
|
|
23
|
+
peerKind?: "direct" | "group"
|
|
16
24
|
}
|
|
17
25
|
|
|
18
26
|
export async function resolveContext(options: ResolveContextOptions): Promise<ResolveContextResult> {
|
|
@@ -57,10 +65,29 @@ export async function resolveContext(options: ResolveContextOptions): Promise<Re
|
|
|
57
65
|
|
|
58
66
|
const coordinators = await agentsCol.findBy("role", "coordinator", { limit: 1 })
|
|
59
67
|
const agentId = coordinators[0]?.id || "bee"
|
|
60
|
-
|
|
61
|
-
//
|
|
62
|
-
|
|
68
|
+
|
|
69
|
+
// Un hilo por canal Y por contacto (`${user}/${canal}/${peer}` — ver
|
|
70
|
+
// agent/thread-id.ts). Antes todos los canales compartían un único hilo
|
|
71
|
+
// (`threadId = userId`), así que lo hablado por Telegram entraba en el mismo
|
|
72
|
+
// contexto que la web y un grupo de WhatsApp escribía en el chat privado del
|
|
73
|
+
// dueño. Los session IDs de transporte siguen enrutando las respuestas.
|
|
74
|
+
const threadId = options.peerId
|
|
75
|
+
? await ensureThread({
|
|
76
|
+
userId,
|
|
77
|
+
channel,
|
|
78
|
+
peerId: options.peerId,
|
|
79
|
+
peerKind: options.peerKind,
|
|
80
|
+
})
|
|
81
|
+
: channel === "webchat"
|
|
82
|
+
// Sin conversación indicada, la web sigue donde se quedó: la más reciente
|
|
83
|
+
// —que puede ser el hilo previo a la separación por canal— o una nueva.
|
|
84
|
+
? ((await mostRecentWebThread(userId))?.id ?? (await createWebConversation(userId)).id)
|
|
85
|
+
: await ensureThread({
|
|
86
|
+
userId,
|
|
87
|
+
channel,
|
|
88
|
+
peerId: channelUserId,
|
|
89
|
+
peerKind: options.peerKind,
|
|
90
|
+
})
|
|
63
91
|
|
|
64
92
|
return { userId, threadId, agentId, isNewUser }
|
|
65
93
|
}
|
|
66
|
-
|
|
@@ -41,11 +41,24 @@ export async function handleDownloadArtifact(
|
|
|
41
41
|
return addCorsHeaders(Response.json({ ok: false, error: "Artifact binary is missing" }, { status: 404 }), req);
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// Los artefactos son inmutables y ya traen su sha256, así que sirve tal cual
|
|
45
|
+
// de ETag fuerte. Sin esto, cada recarga del cliente se traía el binario
|
|
46
|
+
// entero de nuevo: `new Response(BunFile)` resuelve los rangos (206) por su
|
|
47
|
+
// cuenta, pero no emite ETag ni Last-Modified, así que no había forma de
|
|
48
|
+
// contestar 304.
|
|
49
|
+
const etag = `"${entry.doc.sha256}"`;
|
|
50
|
+
const ifNoneMatch = req.headers.get("if-none-match");
|
|
51
|
+
if (ifNoneMatch && ifNoneMatch.split(",").some((t) => t.trim() === etag)) {
|
|
52
|
+
return addCorsHeaders(new Response(null, { status: 304, headers: { ETag: etag } }), req);
|
|
53
|
+
}
|
|
54
|
+
|
|
44
55
|
return addCorsHeaders(
|
|
45
56
|
new Response(file, {
|
|
46
57
|
headers: {
|
|
47
58
|
"Content-Type": entry.doc.mime_type,
|
|
48
59
|
"Cache-Control": "private, max-age=3600",
|
|
60
|
+
ETag: etag,
|
|
61
|
+
"Accept-Ranges": "bytes",
|
|
49
62
|
},
|
|
50
63
|
}),
|
|
51
64
|
req,
|
|
@@ -16,6 +16,7 @@ import { getDefaultLLM } from "../../agent/llm-client";
|
|
|
16
16
|
import { logger } from "../../utils/logger";
|
|
17
17
|
import { saveScratchpadNote, listAllScratchpadNotes, isInternalSource } from "../../agent/conversation-store";
|
|
18
18
|
import { col, fromIndexable } from "../../storage/hive";
|
|
19
|
+
import { mostRecentWebThread } from "../../agent/thread-store";
|
|
19
20
|
import type { UserDoc, AgentDoc, ConversationDoc } from "../../storage/collections";
|
|
20
21
|
|
|
21
22
|
const log = logger.child("api:chat");
|
|
@@ -36,9 +37,18 @@ export interface ChatResponse {
|
|
|
36
37
|
error?: string;
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
/**
|
|
41
|
+
* El hilo pedido manda; si no viene ninguno se usa la conversación activa de la web
|
|
42
|
+
* y, sólo si tampoco la hay, el hilo del usuario (el previo a la separación por
|
|
43
|
+
* canal). Nunca se genera un hilo por petición: sería una conversación sin pasado.
|
|
44
|
+
*/
|
|
45
|
+
export function resolveChatThreadId(
|
|
46
|
+
finalUserId: string,
|
|
47
|
+
requestedThreadId?: string,
|
|
48
|
+
activeThreadId?: string,
|
|
49
|
+
): string {
|
|
40
50
|
const trimmedThreadId = requestedThreadId?.trim();
|
|
41
|
-
return trimmedThreadId || finalUserId || "default";
|
|
51
|
+
return trimmedThreadId || activeThreadId || finalUserId || "default";
|
|
42
52
|
}
|
|
43
53
|
|
|
44
54
|
export async function handleChat(
|
|
@@ -66,7 +76,8 @@ export async function handleChat(
|
|
|
66
76
|
const finalAgentId = agentId || (await resolveAgentId(null)) || "main";
|
|
67
77
|
|
|
68
78
|
// conversations.thread_id is the context key; never generate a per-request thread.
|
|
69
|
-
const
|
|
79
|
+
const active = channel === "webchat" ? await mostRecentWebThread(finalUserId) : null;
|
|
80
|
+
const threadId = resolveChatThreadId(finalUserId, thread_id, active?.id);
|
|
70
81
|
|
|
71
82
|
log.info(`[chat] Processing message from user=${finalUserId} agent=${finalAgentId} thread=${threadId}`);
|
|
72
83
|
|
|
@@ -114,6 +125,7 @@ export async function handleChat(
|
|
|
114
125
|
payload: {
|
|
115
126
|
source: "api",
|
|
116
127
|
sessionId: threadId,
|
|
128
|
+
threadId,
|
|
117
129
|
content: messageContent,
|
|
118
130
|
rawContent: message,
|
|
119
131
|
userId: finalUserId,
|
|
@@ -190,7 +202,11 @@ export async function handleChat(
|
|
|
190
202
|
|
|
191
203
|
export async function handleGetChatHistory(req: Request, addCorsHeaders: (r: Response, req: Request) => Response): Promise<Response> {
|
|
192
204
|
const url = new URL(req.url)
|
|
193
|
-
const
|
|
205
|
+
const requested = url.searchParams.get("threadId") || url.searchParams.get("sessionId")
|
|
206
|
+
// Sin hilo pedido, el historial es el de la conversación activa de la web —igual
|
|
207
|
+
// que el que verá el siguiente turno—, no el de un hilo "default" inexistente.
|
|
208
|
+
const active = requested ? null : await mostRecentWebThread((await resolveUserId({ channel: "webchat" })) || "")
|
|
209
|
+
const threadId = requested || active?.id || "default"
|
|
194
210
|
const limit = parseInt(url.searchParams.get("limit") || String(DEFAULT_CHAT_HISTORY_LIMIT))
|
|
195
211
|
|
|
196
212
|
const conversationsCol = await col<ConversationDoc>("conversations")
|