@johpaz/hive-agents 1.0.5 → 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 +85466 -101014
- package/dist/tool-worker.js +13241 -17001
- package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
- package/dist/ui/assets/{AgentCreateForm-Bcp3HN8D.js → AgentCreateForm-DXkjtXaS.js} +1 -1
- 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-DHfIlSAg.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-BaX6cAPa.js → LoginPage-ByYmIa2p.js} +1 -1
- 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-C_Id9WM-.js → RecoverPage-YY2QU-qh.js} +1 -1
- package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
- package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
- package/dist/ui/assets/{Vignette-Cyi27LQH.js → Vignette-BcPWkNhm.js} +17 -17
- package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -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/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-Bg0g3vPS.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/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-B2stUHvr.js +41 -0
- package/dist/ui/assets/{useHiveAgentsModelLoad-CHmtvNp4.js → useHiveAgentsModelLoad-B4EjHvj4.js} +1 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
- package/dist/ui/assets/{useProviders-C7FA6z4M.js → useProviders-B1NS24md.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/core/src/agent/agent-catalog.ts +31 -31
- 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 +148 -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 +1 -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 +23 -0
- package/packages/core/src/storage/collections.ts +29 -1
- package/packages/core/src/storage/crypto.ts +23 -12
- package/packages/core/src/storage/reconcile.ts +6 -1
- package/packages/core/src/storage/seed.ts +63 -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/core/index.ts +39 -4
- package/packages/core/src/tools/cron/index.ts +4 -4
- package/packages/core/src/tools/index.ts +1 -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/webview-backend.ts +140 -20
- 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-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
|
@@ -1,4 +1,29 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
2
|
+
import pkg from "../../../../../package.json"
|
|
1
3
|
import { OpenAICompatBase } from "./openai-compat-base"
|
|
4
|
+
import type { LLMCallOptions } from "../llm-client"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* OpenCode Go rechaza con 400 `MissingSessionID` toda petición sin
|
|
8
|
+
* `x-opencode-session` (verificado 2026-09-10 con una key real: sin el header
|
|
9
|
+
* 400, con él 200). Su documentación pide además que el cliente se identifique
|
|
10
|
+
* con su propio User-Agent en vez del genérico del SDK:
|
|
11
|
+
* https://opencode.ai/docs/go/#where-can-i-use-it
|
|
12
|
+
*/
|
|
13
|
+
const USER_AGENT = `hive/${pkg.version}`
|
|
14
|
+
|
|
15
|
+
/** Sesión de respaldo para llamadas sin conversación (compactación, metas). */
|
|
16
|
+
const PROCESS_SESSION = randomUUID()
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* La sesión tiene que ser estable por conversación —OpenCode la usa para rutear
|
|
20
|
+
* y cachear el prompt—, pero el threadId lleva usuario, canal y contacto: a
|
|
21
|
+
* OpenCode sólo le llega un hash.
|
|
22
|
+
*/
|
|
23
|
+
function sessionHeader(sessionId: string | undefined): string {
|
|
24
|
+
if (!sessionId) return PROCESS_SESSION
|
|
25
|
+
return createHash("sha256").update(`hive:${sessionId}`).digest("hex").slice(0, 32)
|
|
26
|
+
}
|
|
2
27
|
|
|
3
28
|
export class OpenCodeGoProvider extends OpenAICompatBase {
|
|
4
29
|
static readonly secretKey = "OPENCODE_GO_API_KEY"
|
|
@@ -6,4 +31,16 @@ export class OpenCodeGoProvider extends OpenAICompatBase {
|
|
|
6
31
|
constructor() {
|
|
7
32
|
super("opencode-go")
|
|
8
33
|
}
|
|
34
|
+
|
|
35
|
+
protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, options?: LLMCallOptions): Promise<any> {
|
|
36
|
+
const { default: OpenAI } = await import("openai")
|
|
37
|
+
return new OpenAI({
|
|
38
|
+
apiKey,
|
|
39
|
+
baseURL,
|
|
40
|
+
defaultHeaders: {
|
|
41
|
+
"x-opencode-session": sessionHeader(options?.sessionId),
|
|
42
|
+
"User-Agent": USER_AGENT,
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
}
|
|
9
46
|
}
|
|
@@ -7,7 +7,10 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Verificado contra gemini-3.1-flash-live-preview (2026-08): la inyección de
|
|
9
9
|
* texto va por `sendRealtimeInput({text})`; `sendClientContent` quedó restringido
|
|
10
|
-
* al contexto inicial en 3.x, así que no se usa acá.
|
|
10
|
+
* al contexto inicial en 3.x, así que no se usa acá. La guía actual de la Live
|
|
11
|
+
* API (2026-09) dice que en 3.8 Live `send_client_content` funciona durante toda
|
|
12
|
+
* la sesión y que con `turn_complete=false` agrega contexto sin que el modelo
|
|
13
|
+
* responda: pendiente de verificar con una llamada real antes de usarlo.
|
|
11
14
|
*/
|
|
12
15
|
|
|
13
16
|
import { logger } from "../../utils/logger";
|
|
@@ -22,7 +25,7 @@ import type {
|
|
|
22
25
|
const log = logger.child("realtime:gemini");
|
|
23
26
|
|
|
24
27
|
/** Modelos con `bidiGenerateContent`. El id vive en la BD; esto es sólo el fallback. */
|
|
25
|
-
export const DEFAULT_GEMINI_LIVE_MODEL = "gemini-3.
|
|
28
|
+
export const DEFAULT_GEMINI_LIVE_MODEL = "gemini-3.8-live";
|
|
26
29
|
|
|
27
30
|
class GeminiLiveSession implements RealtimeSession {
|
|
28
31
|
closed = false;
|
|
@@ -165,9 +165,11 @@ function matchTriggers(message: string, triggersJson: string | null): boolean {
|
|
|
165
165
|
const triggers: string[] = triggersJson.split(",").map(t => t.trim()).filter(t => t.length > 0)
|
|
166
166
|
if (triggers.length === 0) return false
|
|
167
167
|
|
|
168
|
-
|
|
168
|
+
// Accent-insensitive: "recuérdame" must match "recuerdame" typed without tildes
|
|
169
|
+
const fold = (s: string) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase()
|
|
170
|
+
const foldedMessage = fold(message)
|
|
169
171
|
return triggers.some(trigger =>
|
|
170
|
-
|
|
172
|
+
foldedMessage.includes(fold(trigger))
|
|
171
173
|
)
|
|
172
174
|
} catch (err) {
|
|
173
175
|
log.warn(`[skill-selector] Failed to parse triggers: ${(err as Error).message}`)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thread identity — `${userId}/${channel}/${peerId}`.
|
|
3
|
+
*
|
|
4
|
+
* Un hilo por canal Y por contacto: el chat privado de Telegram, cada grupo de
|
|
5
|
+
* WhatsApp y cada conversación de la web tienen historial propio. Antes había un
|
|
6
|
+
* único hilo por usuario (`threadId = userId`) compartido por todos los canales.
|
|
7
|
+
*
|
|
8
|
+
* Dos reglas de formato que no son cosméticas:
|
|
9
|
+
*
|
|
10
|
+
* 1. El separador es "/" y NO ":". Los mensajes viven en `conversations` con id
|
|
11
|
+
* `${threadId}:${seq}` y se leen por prefijo (`scan({ prefix: "${threadId}:" })`),
|
|
12
|
+
* sin índice secundario. El hilo legacy (id = userId pelado) se lee con prefijo
|
|
13
|
+
* `${userId}:`; si los hilos nuevos fueran `${userId}:webchat:...` ese scan se los
|
|
14
|
+
* tragaría enteros. Con "/" el historial viejo queda aislado sin migrar una fila.
|
|
15
|
+
*
|
|
16
|
+
* 2. Ningún segmento puede contener ":" — se sustituye por "_". Sin esto los peerIds
|
|
17
|
+
* compuestos rompen el aislamiento por prefijo: el DM de Telegram `12345` y el grupo
|
|
18
|
+
* `12345:678` (telegram.ts arma así el peerId de grupo) producirían los prefijos
|
|
19
|
+
* `.../12345:` y `.../12345:678:`, y el primero es prefijo del segundo — el DM leería
|
|
20
|
+
* los mensajes del grupo. Colapsar ":" hace que `${threadId}:` sea siempre un
|
|
21
|
+
* separador inequívoco, y mantiene válido el `lastIndexOf(":")` con que
|
|
22
|
+
* conversation-store extrae el número de secuencia.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export const THREAD_SEP = "/"
|
|
26
|
+
|
|
27
|
+
/** Canal sintético de las tareas programadas: un hilo estable por cron job. */
|
|
28
|
+
export const CRON_CHANNEL = "cron"
|
|
29
|
+
|
|
30
|
+
export interface ThreadParts {
|
|
31
|
+
userId: string
|
|
32
|
+
channel: string
|
|
33
|
+
peerId: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Deja un segmento apto para formar parte de un threadId: sin "/" (rompería el
|
|
38
|
+
* parseo) y sin ":" (rompería el aislamiento por prefijo — ver cabecera).
|
|
39
|
+
*/
|
|
40
|
+
export function sanitizeSegment(value: string): string {
|
|
41
|
+
return value.replace(/[/:]/g, "_").trim()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function makeThreadId(userId: string, channel: string, peerId: string): string {
|
|
45
|
+
const parts = [userId, channel, peerId].map((p) => sanitizeSegment(p || "") || "default")
|
|
46
|
+
return parts.join(THREAD_SEP)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Descompone un threadId con formato. Devuelve null para todo lo que no lo tenga:
|
|
51
|
+
* el hilo legacy (`userId` pelado), los hilos aislados de los workers
|
|
52
|
+
* (`task-<id>-<agente>`) y cualquier id heredado. Quien llame debe conservar su
|
|
53
|
+
* comportamiento anterior ante un null, nunca inventar partes.
|
|
54
|
+
*/
|
|
55
|
+
export function parseThreadId(threadId: string): ThreadParts | null {
|
|
56
|
+
if (!threadId) return null
|
|
57
|
+
const parts = threadId.split(THREAD_SEP)
|
|
58
|
+
if (parts.length !== 3) return null
|
|
59
|
+
const [userId, channel, peerId] = parts
|
|
60
|
+
if (!userId || !channel || !peerId) return null
|
|
61
|
+
return { userId, channel, peerId }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isStructuredThreadId(threadId: string): boolean {
|
|
65
|
+
return parseThreadId(threadId) !== null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Id de una conversación nueva de la web. No lo elige el cliente. */
|
|
69
|
+
export function newWebConversationId(): string {
|
|
70
|
+
return `conv-${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`
|
|
71
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thread store — el registro de conversaciones (`conversationThreads`).
|
|
3
|
+
*
|
|
4
|
+
* `conversations` no tiene índice secundario: los mensajes se leen por prefijo del
|
|
5
|
+
* threadId. Esta colección es el catálogo que permite listar las conversaciones de
|
|
6
|
+
* un usuario, ponerles título y borrarlas sin escanear todos los mensajes.
|
|
7
|
+
*
|
|
8
|
+
* El id de cada fila ES el threadId. La única fila cuyo id no tiene formato
|
|
9
|
+
* `${user}/${canal}/${peer}` es la del hilo legacy anterior a la separación por
|
|
10
|
+
* canal (ver ensureLegacyThread).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { col, updateDoc } from "../storage/hive"
|
|
14
|
+
import { logger } from "../utils/logger"
|
|
15
|
+
import type { ConversationThreadDoc, ConversationDoc, SummaryDoc } from "../storage/collections"
|
|
16
|
+
import { makeThreadId, parseThreadId, newWebConversationId } from "./thread-id"
|
|
17
|
+
|
|
18
|
+
const log = logger.child("thread-store")
|
|
19
|
+
|
|
20
|
+
const TITLE_MAX_CHARS = 60
|
|
21
|
+
|
|
22
|
+
export interface EnsureThreadInput {
|
|
23
|
+
userId: string
|
|
24
|
+
channel: string
|
|
25
|
+
peerId: string
|
|
26
|
+
peerKind?: "direct" | "group"
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function threadsCol() {
|
|
30
|
+
return col<ConversationThreadDoc>("conversationThreads")
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function getThread(threadId: string): Promise<ConversationThreadDoc | null> {
|
|
34
|
+
const c = await threadsCol()
|
|
35
|
+
const entry = await c.get(threadId)
|
|
36
|
+
return entry?.doc ?? null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Crea la fila de la conversación si aún no existe y devuelve su threadId.
|
|
41
|
+
* Idempotente: se llama en cada turno desde resolveContext.
|
|
42
|
+
*/
|
|
43
|
+
export async function ensureThread(input: EnsureThreadInput): Promise<string> {
|
|
44
|
+
const threadId = makeThreadId(input.userId, input.channel, input.peerId)
|
|
45
|
+
const c = await threadsCol()
|
|
46
|
+
const existing = await c.get(threadId)
|
|
47
|
+
if (existing) return threadId
|
|
48
|
+
|
|
49
|
+
const now = Date.now()
|
|
50
|
+
try {
|
|
51
|
+
await c.put(threadId, {
|
|
52
|
+
id: threadId,
|
|
53
|
+
user_id: input.userId,
|
|
54
|
+
channel: input.channel,
|
|
55
|
+
peer_id: input.peerId,
|
|
56
|
+
peer_kind: input.peerKind ?? "direct",
|
|
57
|
+
title: null,
|
|
58
|
+
archived: false,
|
|
59
|
+
created_at: now,
|
|
60
|
+
last_message_at: now,
|
|
61
|
+
message_count: 0,
|
|
62
|
+
}, { expectedVersion: 0 })
|
|
63
|
+
} catch {
|
|
64
|
+
// Otro turno del mismo canal la creó primero — ambos quieren lo mismo.
|
|
65
|
+
}
|
|
66
|
+
return threadId
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Conversación nueva de la web. El id lo elige el servidor, nunca el cliente. */
|
|
70
|
+
export async function createWebConversation(userId: string, title?: string): Promise<ConversationThreadDoc> {
|
|
71
|
+
const peerId = newWebConversationId()
|
|
72
|
+
const threadId = await ensureThread({ userId, channel: "webchat", peerId, peerKind: "direct" })
|
|
73
|
+
if (title?.trim()) await renameThread(threadId, title)
|
|
74
|
+
const doc = await getThread(threadId)
|
|
75
|
+
if (!doc) throw new Error(`No pude crear la conversación ${threadId}`)
|
|
76
|
+
return doc
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Título derivado del primer mensaje del usuario. El contenido llega con el
|
|
81
|
+
* prefijo `[Timestamp: ...]` que le añaden el gateway y las rutas REST: esa línea
|
|
82
|
+
* no describe nada, así que se descarta antes de recortar.
|
|
83
|
+
*/
|
|
84
|
+
export function deriveTitle(text: string): string | null {
|
|
85
|
+
const withoutTimestamp = text.replace(/^\[Timestamp:[^\]]*\]\s*/, "").trim()
|
|
86
|
+
const firstLine = withoutTimestamp.split("\n").find((l) => l.trim().length > 0)?.trim()
|
|
87
|
+
if (!firstLine) return null
|
|
88
|
+
return firstLine.length > TITLE_MAX_CHARS
|
|
89
|
+
? `${firstLine.slice(0, TITLE_MAX_CHARS - 1)}…`
|
|
90
|
+
: firstLine
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Registra actividad en el hilo: contador, fecha del último mensaje y —la primera
|
|
95
|
+
* vez que habla el usuario— el título.
|
|
96
|
+
*
|
|
97
|
+
* Si el hilo tiene formato y no existe la fila, la crea (es el caso de un hilo que
|
|
98
|
+
* nació fuera de resolveContext, como el de una tarea programada). Si no lo tiene
|
|
99
|
+
* —hilo legacy, hilos aislados `task-*`— solo actualiza una fila ya existente:
|
|
100
|
+
* nunca inventa conversaciones para los hilos internos de los workers.
|
|
101
|
+
*/
|
|
102
|
+
export async function touchThread(
|
|
103
|
+
threadId: string,
|
|
104
|
+
opts: { role: "user" | "assistant" | "tool"; text?: string; internal?: boolean }
|
|
105
|
+
): Promise<void> {
|
|
106
|
+
try {
|
|
107
|
+
const c = await threadsCol()
|
|
108
|
+
let existing = await c.get(threadId)
|
|
109
|
+
|
|
110
|
+
if (!existing) {
|
|
111
|
+
const parts = parseThreadId(threadId)
|
|
112
|
+
if (!parts) return
|
|
113
|
+
await ensureThread({ userId: parts.userId, channel: parts.channel, peerId: parts.peerId })
|
|
114
|
+
existing = await c.get(threadId)
|
|
115
|
+
if (!existing) return
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const patch: Partial<ConversationThreadDoc> = {
|
|
119
|
+
last_message_at: Date.now(),
|
|
120
|
+
message_count: existing.doc.message_count + 1,
|
|
121
|
+
}
|
|
122
|
+
// El título sale del primer mensaje humano: ni de la respuesta del agente ni
|
|
123
|
+
// de un evento interno (fan-in de delegación), que no describen el tema.
|
|
124
|
+
if (!existing.doc.title && opts.role === "user" && !opts.internal && opts.text) {
|
|
125
|
+
const title = deriveTitle(opts.text)
|
|
126
|
+
if (title) patch.title = title
|
|
127
|
+
}
|
|
128
|
+
await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, patch)
|
|
129
|
+
} catch (err) {
|
|
130
|
+
// El registro es un catálogo, no la fuente de verdad: nunca debe tumbar un turno.
|
|
131
|
+
log.warn(`no pude actualizar el hilo ${threadId}: ${(err as Error).message}`)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function listThreads(
|
|
136
|
+
userId: string,
|
|
137
|
+
opts?: { channel?: string; includeArchived?: boolean }
|
|
138
|
+
): Promise<ConversationThreadDoc[]> {
|
|
139
|
+
const c = await threadsCol()
|
|
140
|
+
const rows = await c.findBy("user_id", userId)
|
|
141
|
+
return rows
|
|
142
|
+
.map((r) => r.doc)
|
|
143
|
+
.filter((d) => (opts?.channel ? d.channel === opts.channel : true))
|
|
144
|
+
.filter((d) => (opts?.includeArchived ? true : !d.archived))
|
|
145
|
+
.sort((a, b) => b.last_message_at - a.last_message_at)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** La conversación de webchat en la que seguiría escribiendo el usuario. */
|
|
149
|
+
export async function mostRecentWebThread(userId: string): Promise<ConversationThreadDoc | null> {
|
|
150
|
+
const threads = await listThreads(userId, { channel: "webchat" })
|
|
151
|
+
return threads[0] ?? null
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function renameThread(threadId: string, title: string): Promise<void> {
|
|
155
|
+
const clean = title.trim().slice(0, 200)
|
|
156
|
+
await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, { title: clean || null })
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Borra la conversación entera: mensajes, resumen, notas y la fila del registro.
|
|
161
|
+
* Los mensajes se localizan por prefijo, igual que los lee conversation-store.
|
|
162
|
+
*/
|
|
163
|
+
export async function deleteThread(threadId: string): Promise<void> {
|
|
164
|
+
const conversations = await col<ConversationDoc>("conversations")
|
|
165
|
+
const messages = await conversations.scan({ prefix: `${threadId}:` })
|
|
166
|
+
for (const m of messages) await conversations.delete(m.id)
|
|
167
|
+
|
|
168
|
+
const summaries = await col<SummaryDoc>("summaries")
|
|
169
|
+
await summaries.delete(threadId).catch(() => {})
|
|
170
|
+
|
|
171
|
+
const scratchpad = await col<{ threadId: string }>("scratchpad")
|
|
172
|
+
const notes = await scratchpad.scan({ prefix: `${threadId}:` })
|
|
173
|
+
for (const n of notes) await scratchpad.delete(n.id)
|
|
174
|
+
|
|
175
|
+
const c = await threadsCol()
|
|
176
|
+
await c.delete(threadId).catch(() => {})
|
|
177
|
+
|
|
178
|
+
log.info(`conversación ${threadId} borrada (${messages.length} mensajes)`)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* El hilo por el que hablarle a alguien en un canal cuando no venimos de un
|
|
183
|
+
* mensaje suyo (avisos de tareas programadas, por ejemplo).
|
|
184
|
+
*
|
|
185
|
+
* En la web es la conversación activa; en los demás canales, el contacto al que
|
|
186
|
+
* apunta `userIdentities`. Devuelve null si no hay ninguno, y quien llame decide
|
|
187
|
+
* el fallback.
|
|
188
|
+
*/
|
|
189
|
+
export async function threadForChannel(userId: string, channel: string): Promise<string | null> {
|
|
190
|
+
if (channel === "webchat") return (await mostRecentWebThread(userId))?.id ?? null
|
|
191
|
+
|
|
192
|
+
const identities = await col<{ channel_user_id?: string }>("userIdentities")
|
|
193
|
+
const identity = await identities.get(`${userId}:${channel}`)
|
|
194
|
+
const peerId = identity?.doc.channel_user_id
|
|
195
|
+
return peerId ? makeThreadId(userId, channel, peerId) : null
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Registra el hilo anterior a la separación por canal —`thread_id = userId`, un
|
|
200
|
+
* único hilo compartido por todos los canales— como una conversación más de la
|
|
201
|
+
* web, para que su historial siga siendo accesible. No mueve ni reescribe ningún
|
|
202
|
+
* mensaje: la fila apunta al mismo prefijo de siempre.
|
|
203
|
+
*/
|
|
204
|
+
export async function ensureLegacyThread(userId: string): Promise<boolean> {
|
|
205
|
+
const c = await threadsCol()
|
|
206
|
+
if (await c.get(userId)) return false
|
|
207
|
+
|
|
208
|
+
const conversations = await col<ConversationDoc>("conversations")
|
|
209
|
+
const sample = await conversations.scan({ prefix: `${userId}:`, limit: 1 })
|
|
210
|
+
if (sample.length === 0) return false
|
|
211
|
+
|
|
212
|
+
const all = await conversations.scan({ prefix: `${userId}:` })
|
|
213
|
+
const lastAt = all.reduce((max, e) => Math.max(max, e.doc.created_at), 0)
|
|
214
|
+
|
|
215
|
+
await c.put(userId, {
|
|
216
|
+
id: userId,
|
|
217
|
+
user_id: userId,
|
|
218
|
+
channel: "webchat",
|
|
219
|
+
peer_id: "legacy",
|
|
220
|
+
peer_kind: "direct",
|
|
221
|
+
title: "Conversación anterior",
|
|
222
|
+
archived: false,
|
|
223
|
+
created_at: all[0]?.doc.created_at ?? Date.now(),
|
|
224
|
+
last_message_at: lastAt || Date.now(),
|
|
225
|
+
message_count: all.length,
|
|
226
|
+
}, { expectedVersion: 0 }).catch(() => {})
|
|
227
|
+
|
|
228
|
+
log.info(`hilo legacy ${userId} registrado como conversación (${all.length} mensajes)`)
|
|
229
|
+
return true
|
|
230
|
+
}
|
|
@@ -196,6 +196,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
196
196
|
|
|
197
197
|
// Capability discovery
|
|
198
198
|
{ name: "search_knowledge", description: "Search everything Hive knows: native tools, MCP tools, skills, catalog agents and playbook rules. Spanish keywords: buscar herramienta, descubrir capacidades, qué puedo hacer, buscar skill, buscar conocimiento", category: "core", abstractionLevel: "atomic" },
|
|
199
|
+
{ name: "conversation_read", description: "Read earlier messages from this conversation by ID or search text when context is missing. Spanish keywords: recuperar contexto, leer historial, conversación anterior", category: "core", abstractionLevel: "atomic" },
|
|
199
200
|
|
|
200
201
|
// HTTP / REST
|
|
201
202
|
{ name: "api_request", description: "Perform an authorized HTTP request against a REST endpoint and validate the response. Spanish keywords: llamar api, request rest, consumir endpoint, petición http, hacer get, hacer post", category: "api", abstractionLevel: "atomic" },
|
|
@@ -95,6 +95,7 @@ export function recordLLMUsage(opts: {
|
|
|
95
95
|
model: string
|
|
96
96
|
inputTokens: number
|
|
97
97
|
outputTokens: number
|
|
98
|
+
latencyMs?: number
|
|
98
99
|
}): void {
|
|
99
100
|
Promise.resolve().then(async () => {
|
|
100
101
|
try {
|
|
@@ -104,6 +105,7 @@ export function recordLLMUsage(opts: {
|
|
|
104
105
|
model: opts.model,
|
|
105
106
|
inputTokens: opts.inputTokens,
|
|
106
107
|
outputTokens: opts.outputTokens,
|
|
108
|
+
latencyMs: opts.latencyMs,
|
|
107
109
|
})
|
|
108
110
|
} catch { /* ignore */ }
|
|
109
111
|
})
|
|
@@ -42,6 +42,15 @@ interface A2UISurfaceCache {
|
|
|
42
42
|
dataModel?: Record<string, unknown>;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
/** Overlays `incoming` on `current` by component id, keeping the order of first appearance. */
|
|
46
|
+
export function mergeComponentsById(current: unknown[], incoming: unknown[]): unknown[] {
|
|
47
|
+
const byId = new Map<string, unknown>()
|
|
48
|
+
const idOf = (c: unknown) => (c && typeof c === "object" ? String((c as { id?: unknown }).id ?? "") : "")
|
|
49
|
+
for (const c of current) byId.set(idOf(c), c)
|
|
50
|
+
for (const c of incoming) byId.set(idOf(c), c)
|
|
51
|
+
return [...byId.values()]
|
|
52
|
+
}
|
|
53
|
+
|
|
45
54
|
export class CanvasManager {
|
|
46
55
|
/**
|
|
47
56
|
* Clientes por sesión, no *un* cliente por sesión.
|
|
@@ -197,6 +206,11 @@ export class CanvasManager {
|
|
|
197
206
|
);
|
|
198
207
|
}
|
|
199
208
|
|
|
209
|
+
/** What the client is rendering for a surface: every component sent so far, merged by id. */
|
|
210
|
+
getCachedComponents(sessionId: string, surfaceId: string): unknown[] {
|
|
211
|
+
return this.a2uiCache.get(sessionId)?.get(surfaceId)?.components ?? [];
|
|
212
|
+
}
|
|
213
|
+
|
|
200
214
|
async sendA2UIMessage(sessionId: string, messageType: string, data: Record<string, unknown>): Promise<void> {
|
|
201
215
|
// Update A2UI cache so late-connecting clients can receive current state
|
|
202
216
|
const surfaceId = data.surfaceId as string | undefined;
|
|
@@ -207,7 +221,9 @@ export class CanvasManager {
|
|
|
207
221
|
sessionSurfaces.set(surfaceId, { createData: data });
|
|
208
222
|
} else if (messageType === "a2ui:updateComponents") {
|
|
209
223
|
const cached = sessionSurfaces.get(surfaceId);
|
|
210
|
-
|
|
224
|
+
// Merge by id, like the client: replacing the list made a reconnect
|
|
225
|
+
// replay a different surface from the one the user was looking at.
|
|
226
|
+
if (cached) cached.components = mergeComponentsById(cached.components ?? [], data.components as unknown[]);
|
|
211
227
|
} else if (messageType === "a2ui:updateDataModel") {
|
|
212
228
|
const cached = sessionSurfaces.get(surfaceId);
|
|
213
229
|
if (cached) {
|
|
@@ -15,6 +15,8 @@ export type CanvasEventType =
|
|
|
15
15
|
| "canvas:edge_add"
|
|
16
16
|
| "canvas:edge_remove"
|
|
17
17
|
| "canvas:work_event"
|
|
18
|
+
| "canvas:jev_decision"
|
|
19
|
+
| "canvas:jev_status"
|
|
18
20
|
| "ag-ui:event"
|
|
19
21
|
|
|
20
22
|
export type CanvasWorkPhase =
|
|
@@ -37,6 +39,23 @@ export interface CanvasWorkEvent {
|
|
|
37
39
|
detail?: string | null
|
|
38
40
|
}
|
|
39
41
|
|
|
42
|
+
/** One Jev decision, shown by the office's oracle as a beam to the agent it advised. */
|
|
43
|
+
export interface CanvasJevDecision {
|
|
44
|
+
eventId: string
|
|
45
|
+
agentId: string
|
|
46
|
+
kind: "context" | "iteration" | "parallel"
|
|
47
|
+
/** Short Spanish description of what was selected ("4/15 mensajes · 9/24 herramientas"). */
|
|
48
|
+
summary: string
|
|
49
|
+
/** Estimated main-model input tokens this decision avoided (chars/4); negative when it added context. */
|
|
50
|
+
savedTokens: number
|
|
51
|
+
latencyMs: number
|
|
52
|
+
costUsd: number
|
|
53
|
+
recommendedAgentId?: string | null
|
|
54
|
+
/** MCP servers the recommended specialist needs that are off; the coordinator asks the user to turn them on. */
|
|
55
|
+
mcpOff?: string[]
|
|
56
|
+
totals: { decisions: number; savedTokens: number; costUsd: number }
|
|
57
|
+
}
|
|
58
|
+
|
|
40
59
|
const subscribers = new Set<{ send: (data: string) => void }>()
|
|
41
60
|
let workEventSequence = 0
|
|
42
61
|
|
|
@@ -57,6 +76,11 @@ const LIVE_DEFAULTS: AgentLiveState = {
|
|
|
57
76
|
delegatedBy: null,
|
|
58
77
|
}
|
|
59
78
|
|
|
79
|
+
/** What each agent is doing right now (the same state the 3D office draws). */
|
|
80
|
+
export function getAgentLiveStates(): Array<{ agentId: string } & AgentLiveState> {
|
|
81
|
+
return [...agentLiveState.entries()].map(([agentId, state]) => ({ agentId, ...state }))
|
|
82
|
+
}
|
|
83
|
+
|
|
60
84
|
export function subscribeCanvas(ws: { send: (data: string) => void }) {
|
|
61
85
|
subscribers.add(ws)
|
|
62
86
|
}
|
|
@@ -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: {
|