@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,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reloj de pared ↔ instante, en una zona horaria IANA.
|
|
3
|
+
*
|
|
4
|
+
* Es la parte difícil de un cron con zona horaria y la razón por la que no
|
|
5
|
+
* alcanza con `Bun.cron.parse()`, que resuelve en una sola zona —UTC hasta Bun
|
|
6
|
+
* 1.3, la local del proceso desde 1.4— y nunca en la del job. "Todos los días a
|
|
7
|
+
* las 9" significa las 9 **del reloj de la pared en Bogotá**, y ese instante se
|
|
8
|
+
* corre una hora dos veces al año en las zonas con horario de verano. Calcular
|
|
9
|
+
* el offset una sola vez y sumarlo produce un cron que se desfasa un día al año
|
|
10
|
+
* en marzo y otro en octubre — el tipo de error que aparece un domingo a las
|
|
11
|
+
* 2am y nadie sabe de dónde salió.
|
|
12
|
+
*
|
|
13
|
+
* Acá no se guarda ningún offset: se le pregunta a `Intl` en cada conversión,
|
|
14
|
+
* que es la única fuente que conoce las reglas de cada zona y sus cambios.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Los campos que muestra un reloj colgado en la pared de esa zona. */
|
|
18
|
+
export interface WallClock {
|
|
19
|
+
year: number
|
|
20
|
+
/** 1-12, no 0-11: acá no hay meses de base cero. */
|
|
21
|
+
month: number
|
|
22
|
+
day: number
|
|
23
|
+
hour: number
|
|
24
|
+
minute: number
|
|
25
|
+
second: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Día de la semana, 0 = domingo. */
|
|
29
|
+
export function wallClockWeekday(wall: WallClock): number {
|
|
30
|
+
return new Date(Date.UTC(wall.year, wall.month - 1, wall.day)).getUTCDay()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const formatters = new Map<string, Intl.DateTimeFormat>()
|
|
34
|
+
|
|
35
|
+
function formatter(timeZone: string): Intl.DateTimeFormat {
|
|
36
|
+
let f = formatters.get(timeZone)
|
|
37
|
+
if (!f) {
|
|
38
|
+
f = new Intl.DateTimeFormat("en-US", {
|
|
39
|
+
timeZone,
|
|
40
|
+
hourCycle: "h23",
|
|
41
|
+
year: "numeric",
|
|
42
|
+
month: "2-digit",
|
|
43
|
+
day: "2-digit",
|
|
44
|
+
hour: "2-digit",
|
|
45
|
+
minute: "2-digit",
|
|
46
|
+
second: "2-digit",
|
|
47
|
+
})
|
|
48
|
+
formatters.set(timeZone, f)
|
|
49
|
+
}
|
|
50
|
+
return f
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Valida una zona IANA. Lanza con un mensaje que dice cuál falló. */
|
|
54
|
+
export function assertTimeZone(timeZone: string): void {
|
|
55
|
+
try {
|
|
56
|
+
formatter(timeZone)
|
|
57
|
+
} catch {
|
|
58
|
+
throw new Error(`Zona horaria desconocida: "${timeZone}"`)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Qué marca el reloj de esa zona en ese instante. */
|
|
63
|
+
export function toWallClock(instant: Date, timeZone: string): WallClock {
|
|
64
|
+
const parts = formatter(timeZone).formatToParts(instant)
|
|
65
|
+
const campo = (tipo: string) => {
|
|
66
|
+
const p = parts.find((x) => x.type === tipo)
|
|
67
|
+
return p ? Number(p.value) : 0
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
year: campo("year"),
|
|
71
|
+
month: campo("month"),
|
|
72
|
+
day: campo("day"),
|
|
73
|
+
hour: campo("hour"),
|
|
74
|
+
minute: campo("minute"),
|
|
75
|
+
second: campo("second"),
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function asUTCMillis(wall: WallClock): number {
|
|
80
|
+
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function mismoReloj(a: WallClock, b: WallClock): boolean {
|
|
84
|
+
return (
|
|
85
|
+
a.year === b.year && a.month === b.month && a.day === b.day &&
|
|
86
|
+
a.hour === b.hour && a.minute === b.minute && a.second === b.second
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* El instante en que el reloj de esa zona marca `wall`.
|
|
92
|
+
*
|
|
93
|
+
* Devuelve `null` cuando ese momento **no existe**: al adelantar el horario de
|
|
94
|
+
* verano el reloj salta de 01:59 a 03:00, así que "las 2:30" no ocurre ese día.
|
|
95
|
+
* Un cron agendado ahí no debe correr a una hora inventada; el que llama decide
|
|
96
|
+
* si lo salta o lo corre al día siguiente.
|
|
97
|
+
*
|
|
98
|
+
* Cuando el reloj se atrasa, la misma hora ocurre dos veces y se devuelve la
|
|
99
|
+
* primera — correr una vez es lo que espera quien agendó, no dos.
|
|
100
|
+
*/
|
|
101
|
+
export function toInstant(wall: WallClock, timeZone: string): Date | null {
|
|
102
|
+
const objetivo = asUTCMillis(wall)
|
|
103
|
+
|
|
104
|
+
// Punto de partida: tratar el reloj de pared como si fuera UTC y corregir con
|
|
105
|
+
// la diferencia que reporte la zona. Dos pasadas alcanzan siempre — la primera
|
|
106
|
+
// acerca al offset correcto, la segunda absorbe el caso en que la corrección
|
|
107
|
+
// cruzó un cambio de horario y el offset de destino era otro.
|
|
108
|
+
let ts = objetivo
|
|
109
|
+
for (let i = 0; i < 3; i++) {
|
|
110
|
+
const diferencia = objetivo - asUTCMillis(toWallClock(new Date(ts), timeZone))
|
|
111
|
+
if (diferencia === 0) break
|
|
112
|
+
ts += diferencia
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// La comprobación no es defensiva: es cómo se detecta el hueco del cambio de
|
|
116
|
+
// horario. Si la hora pedida no existe, ninguna corrección converge y el
|
|
117
|
+
// reloj de `ts` marca otra cosa.
|
|
118
|
+
if (!mismoReloj(toWallClock(new Date(ts), timeZone), wall)) return null
|
|
119
|
+
|
|
120
|
+
// Cuando el reloj se atrasa, ese mismo reloj de pared ocurre dos veces y la
|
|
121
|
+
// convergencia de arriba aterriza en la segunda. Se busca hacia atrás la
|
|
122
|
+
// primera: correr al instante más temprano es lo que espera quien agendó "a
|
|
123
|
+
// las 2:30", y así el job no se corre una hora ese día del año.
|
|
124
|
+
for (const atras of DESFASES_POSIBLES) {
|
|
125
|
+
const antes = ts - atras
|
|
126
|
+
if (mismoReloj(toWallClock(new Date(antes), timeZone), wall)) return new Date(antes)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return new Date(ts)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Cuánto puede saltar un reloj al cambiar de horario, de mayor a menor.
|
|
134
|
+
*
|
|
135
|
+
* Casi todas las zonas mueven una hora, pero no todas: Lord Howe mueve media, y
|
|
136
|
+
* hubo zonas con saltos de dos. Se prueban de mayor a menor para quedarse con
|
|
137
|
+
* la ocurrencia más temprana.
|
|
138
|
+
*/
|
|
139
|
+
const DESFASES_POSIBLES = [2 * 3_600_000, 3_600_000, 1_800_000]
|
|
@@ -12,6 +12,8 @@ import { resolveAgentId } from "../storage/onboarding";
|
|
|
12
12
|
import { sendToUserChannel } from "../gateway/channel-notify";
|
|
13
13
|
import { getNarration } from "../gateway/helpers";
|
|
14
14
|
import { addMessage } from "../agent/conversation-store";
|
|
15
|
+
import { makeThreadId, CRON_CHANNEL } from "../agent/thread-id";
|
|
16
|
+
import { threadForChannel } from "../agent/thread-store";
|
|
15
17
|
import { resolveBestChannel } from "../tools/cron/index";
|
|
16
18
|
import { col } from "../storage/hive";
|
|
17
19
|
import type { UserDoc, CronJobDoc } from "../storage/collections";
|
|
@@ -123,7 +125,11 @@ ${prompt || `Execute tool: ${job.tool_name}`}`;
|
|
|
123
125
|
try {
|
|
124
126
|
const agentLoop = buildAgentLoop({ mcpManager: undefined });
|
|
125
127
|
|
|
126
|
-
|
|
128
|
+
// Un hilo estable por tarea programada. Antes era
|
|
129
|
+
// `sched_${job.id}_${Date.now()}`: cada disparo estrenaba un hilo, así que
|
|
130
|
+
// la tarea nunca recordaba sus ejecuciones anteriores y cada una dejaba
|
|
131
|
+
// mensajes huérfanos en `conversations` que ya nadie volvía a leer.
|
|
132
|
+
const sessionId = makeThreadId(user?.id || "default", CRON_CHANNEL, job.id);
|
|
127
133
|
|
|
128
134
|
const agentChannel = (job.channel && job.channel !== "system")
|
|
129
135
|
? job.channel
|
|
@@ -136,10 +142,10 @@ ${prompt || `Execute tool: ${job.tool_name}`}`;
|
|
|
136
142
|
if (!agentChannel) return;
|
|
137
143
|
try {
|
|
138
144
|
if (step.type === "tool_call" && step.toolName) {
|
|
139
|
-
await sendToUserChannel(agentChannel, user?.id || "", getNarration(step.toolName));
|
|
145
|
+
await sendToUserChannel(agentChannel, user?.id || "", getNarration(step.toolName), { threadId: sessionId });
|
|
140
146
|
} else if (step.type === "text" && step.message) {
|
|
141
147
|
const trimmed = step.message.trim();
|
|
142
|
-
if (trimmed) await sendToUserChannel(agentChannel, user?.id || "", trimmed);
|
|
148
|
+
if (trimmed) await sendToUserChannel(agentChannel, user?.id || "", trimmed, { threadId: sessionId });
|
|
143
149
|
}
|
|
144
150
|
} catch (err) {
|
|
145
151
|
log.warn(`[execute] Narration send failed: ${(err as Error).message}`);
|
|
@@ -239,13 +245,18 @@ export async function notifyTaskCompletion(
|
|
|
239
245
|
|
|
240
246
|
log.info(`[notify] Sending notification to ${notifyChannel}: "${message.slice(0, 50)}..."`);
|
|
241
247
|
|
|
248
|
+
// El aviso se guarda en el hilo donde el usuario lo va a leer —su conversación
|
|
249
|
+
// activa en la web, o el chat del canal— y no en el hilo del usuario, que desde
|
|
250
|
+
// la separación por canal ya no es donde mira nadie.
|
|
251
|
+
const notifyThreadId = (await threadForChannel(userId, notifyChannel)) ?? userId;
|
|
252
|
+
|
|
242
253
|
try {
|
|
243
|
-
await addMessage(
|
|
254
|
+
await addMessage(notifyThreadId, "assistant", message, { channel: notifyChannel });
|
|
244
255
|
} catch (e) {
|
|
245
256
|
log.warn(`[notify] Failed to persist notification to DB: ${(e as Error).message}`);
|
|
246
257
|
}
|
|
247
258
|
|
|
248
|
-
await sendToUserChannel(notifyChannel, userId, message);
|
|
259
|
+
await sendToUserChannel(notifyChannel, userId, message, { threadId: notifyThreadId });
|
|
249
260
|
log.info(`[notify] Notification sent to ${notifyChannel}`);
|
|
250
261
|
}
|
|
251
262
|
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Hive Scheduler - Type Definitions
|
|
3
3
|
*
|
|
4
|
-
* Type interfaces for the
|
|
4
|
+
* Type interfaces for the scheduling system.
|
|
5
5
|
* All names use "CronJob" terminology (formerly ScheduledTask).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import type { Cron } from "
|
|
8
|
+
import type { Cron } from "./cron";
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Task type: recurring uses cron expression, one_shot uses fire_at
|
|
@@ -146,24 +146,9 @@ export interface CronJobExecutionResult {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
/**
|
|
149
|
-
* Internal job wrapper holding
|
|
149
|
+
* Internal job wrapper holding the scheduled job and its metadata
|
|
150
150
|
*/
|
|
151
151
|
export interface CronJobEntry {
|
|
152
152
|
job: CronJob;
|
|
153
153
|
cron: Cron;
|
|
154
154
|
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Options for Croner job creation
|
|
158
|
-
*/
|
|
159
|
-
export interface CronerOptions {
|
|
160
|
-
timezone: string;
|
|
161
|
-
protect: boolean;
|
|
162
|
-
catch: boolean | ((error: Error) => void);
|
|
163
|
-
name: string;
|
|
164
|
-
maxRuns?: number;
|
|
165
|
-
interval?: number;
|
|
166
|
-
startAt?: string;
|
|
167
|
-
stopAt?: string;
|
|
168
|
-
domAndDow?: boolean;
|
|
169
|
-
}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import { getHiveDb, getOpenHiveDb } from "./hivedb";
|
|
15
15
|
import { col } from "./hive";
|
|
16
16
|
import { seedAllData } from "./seed";
|
|
17
|
+
import { ensureLegacyThread } from "../agent/thread-store";
|
|
17
18
|
import { ensureSecretsBackend } from "./crypto";
|
|
18
19
|
|
|
19
20
|
interface IndexSpec {
|
|
@@ -60,6 +61,9 @@ const INDEXES: IndexSpec[] = [
|
|
|
60
61
|
{ collection: "traces", field: "success" },
|
|
61
62
|
{ collection: "playbook", field: "active" },
|
|
62
63
|
{ collection: "playbook", field: "category" },
|
|
64
|
+
{ collection: "conversationThreads", field: "user_id" },
|
|
65
|
+
{ collection: "conversationThreads", field: "channel" },
|
|
66
|
+
{ collection: "conversationThreads", field: "archived" },
|
|
63
67
|
// Stage 5 — scheduler
|
|
64
68
|
{ collection: "cronJobs", field: "status" },
|
|
65
69
|
{ collection: "cronJobs", field: "task_type" },
|
|
@@ -128,6 +132,23 @@ async function ensureSeedData(): Promise<void> {
|
|
|
128
132
|
// tests or long-running processes open a fresh instance in the same runtime.
|
|
129
133
|
let bootstrappedDb: Awaited<ReturnType<typeof getHiveDb>> | null = null;
|
|
130
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Antes de la separación por canal todos los canales compartían un solo hilo cuyo
|
|
137
|
+
* `thread_id` era el `userId`. Esa conversación se registra —sin mover un solo
|
|
138
|
+
* mensaje— como una conversación más de la web, para que siga siendo legible desde
|
|
139
|
+
* la lista. Idempotente: no hace nada si ya está registrada o si no hay historial.
|
|
140
|
+
*/
|
|
141
|
+
async function ensureLegacyThreads(): Promise<void> {
|
|
142
|
+
try {
|
|
143
|
+
const users = await col<{ id: string }>("users");
|
|
144
|
+
for (const user of await users.scan({})) {
|
|
145
|
+
await ensureLegacyThread(user.id);
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
// Base sin usuarios todavía (onboarding pendiente) — nada que registrar.
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
131
152
|
/**
|
|
132
153
|
* Idempotent entry point: opens the database, ensures indexes, reseeds the
|
|
133
154
|
* static catalogs, and records the schema version. Safe to call on every
|
|
@@ -142,6 +163,8 @@ export async function ensureHiveDb(): Promise<void> {
|
|
|
142
163
|
ensureSecretsBackend();
|
|
143
164
|
await ensureSeedData();
|
|
144
165
|
|
|
166
|
+
await ensureLegacyThreads();
|
|
167
|
+
|
|
145
168
|
const meta = await col<{ value: number }>("meta");
|
|
146
169
|
const existing = await meta.get("schemaVersion");
|
|
147
170
|
if (!existing) await meta.put("schemaVersion", { value: 1 }, { expectedVersion: 0 });
|
|
@@ -40,7 +40,8 @@ export interface ModelDoc {
|
|
|
40
40
|
id: string
|
|
41
41
|
provider_id: string
|
|
42
42
|
name: string
|
|
43
|
-
|
|
43
|
+
/** "realtime": voz full-duplex (Live API), no confundir con stt+tts encadenados. */
|
|
44
|
+
model_type: "llm" | "stt" | "tts" | "vision" | "embedding" | "realtime" | "decision"
|
|
44
45
|
context_window: number
|
|
45
46
|
capabilities: string | null
|
|
46
47
|
enabled: boolean
|
|
@@ -269,6 +270,14 @@ export interface RefreshTokenDoc {
|
|
|
269
270
|
export type TurnSource =
|
|
270
271
|
| "message" | "audio" | "a2ui" | "canvas" | "api"
|
|
271
272
|
| "task_complete" | "delegation_summary"
|
|
273
|
+
/** Turno hablado en una sesión de voz en tiempo real. A diferencia de "audio"
|
|
274
|
+
* (nota de voz: STT → turno → TTS) la voz la pone el modelo realtime, así que
|
|
275
|
+
* el turno nunca sintetiza audio al final. */
|
|
276
|
+
| "realtime"
|
|
277
|
+
/** Charla hablada que la voz YA resolvió sin tocar la colmena. Se guarda como
|
|
278
|
+
* contexto del hilo, nunca como pedido pendiente: tratarla como accionable
|
|
279
|
+
* hacía que el coordinador re-delegara todo lo que se había dicho en voz. */
|
|
280
|
+
| "realtime_chat"
|
|
272
281
|
|
|
273
282
|
/** What gets persisted — adds the synthetic marker for rows written before `source` existed. */
|
|
274
283
|
export type MessageSource = TurnSource | "legacy_internal"
|
|
@@ -298,6 +307,28 @@ export interface SummaryDoc {
|
|
|
298
307
|
last_message_id: string | null
|
|
299
308
|
}
|
|
300
309
|
|
|
310
|
+
/**
|
|
311
|
+
* Una conversación: el registro de un `conversations.thread_id`, con lo necesario
|
|
312
|
+
* para listarla en la web sin escanear los mensajes. `id` ES el threadId
|
|
313
|
+
* (`${user}/${canal}/${peer}` — ver agent/thread-id.ts), salvo la fila del hilo
|
|
314
|
+
* legacy anterior a la separación por canal, cuyo id es el userId pelado.
|
|
315
|
+
*/
|
|
316
|
+
export interface ConversationThreadDoc {
|
|
317
|
+
id: string
|
|
318
|
+
user_id: string
|
|
319
|
+
channel: string
|
|
320
|
+
/** Contacto/grupo del canal, o el id de conversación en la web. */
|
|
321
|
+
peer_id: string
|
|
322
|
+
peer_kind: "direct" | "group"
|
|
323
|
+
/** null hasta el primer mensaje del usuario, de donde se deriva. */
|
|
324
|
+
title: string | null
|
|
325
|
+
/** Borrado suave: sigue en la base pero no se lista ni se reabre. */
|
|
326
|
+
archived: boolean
|
|
327
|
+
created_at: number
|
|
328
|
+
last_message_at: number
|
|
329
|
+
message_count: number
|
|
330
|
+
}
|
|
331
|
+
|
|
301
332
|
export interface TraceDoc {
|
|
302
333
|
id: string
|
|
303
334
|
thread_id: string
|
|
@@ -673,6 +704,12 @@ export interface UsageRollupDoc {
|
|
|
673
704
|
toonJsonBytes: number
|
|
674
705
|
byProvider: Record<string, { inputTokens: number; outputTokens: number; costUsd: number }>
|
|
675
706
|
byModel: Record<string, { inputTokens: number; outputTokens: number; costUsd: number }>
|
|
707
|
+
/** Jev decision plane; absent on hours before it existed. Savings are estimates (chars/4) priced at the advised agent's model. */
|
|
708
|
+
jevDecisions?: number
|
|
709
|
+
jevCostUsd?: number
|
|
710
|
+
jevSavedTokens?: number
|
|
711
|
+
jevSavedCostUsd?: number
|
|
712
|
+
jevByAgent?: Record<string, { jevDecisions: number; jevCostUsd: number; jevSavedTokens: number; jevSavedCostUsd: number }>
|
|
676
713
|
}
|
|
677
714
|
|
|
678
715
|
export interface ActivityRollupDoc {
|
|
@@ -27,6 +27,10 @@ interface SecretDoc {
|
|
|
27
27
|
// restart in production.
|
|
28
28
|
|
|
29
29
|
const _mem = new Map<string, string>()
|
|
30
|
+
// Bumped by every write and delete. A read that was already in flight when the
|
|
31
|
+
// secret changed must not cache what it found: that resurrected deleted keys
|
|
32
|
+
// in memory until restart.
|
|
33
|
+
const _epoch = new Map<string, number>()
|
|
30
34
|
let _keychainOk: boolean | null = null // null = untested
|
|
31
35
|
let _keychainApi: unknown = undefined
|
|
32
36
|
|
|
@@ -47,14 +51,19 @@ function _getKeychainApi(): any {
|
|
|
47
51
|
async function _get(name: string): Promise<string | null> {
|
|
48
52
|
const cached = _mem.get(name)
|
|
49
53
|
if (cached !== undefined) return cached
|
|
54
|
+
const epoch = _epoch.get(name) ?? 0
|
|
55
|
+
const cache = (value: string) => { if ((_epoch.get(name) ?? 0) === epoch) _mem.set(name, value) }
|
|
50
56
|
|
|
51
57
|
// Durable store first — it is the one every write goes to.
|
|
52
58
|
const stored = await _readCollectionSecret(name)
|
|
53
|
-
if (stored)
|
|
59
|
+
if (stored) {
|
|
60
|
+
cache(stored)
|
|
61
|
+
return stored
|
|
62
|
+
}
|
|
54
63
|
|
|
55
64
|
// Legacy/desktop installs may only have the value in the OS keychain.
|
|
56
65
|
const fromKeychain = await _keychainGet(name)
|
|
57
|
-
if (fromKeychain)
|
|
66
|
+
if (fromKeychain) cache(fromKeychain)
|
|
58
67
|
return fromKeychain
|
|
59
68
|
}
|
|
60
69
|
|
|
@@ -65,6 +74,7 @@ async function _get(name: string): Promise<string | null> {
|
|
|
65
74
|
* silently accepting a secret that dies with the process.
|
|
66
75
|
*/
|
|
67
76
|
async function _set(name: string, value: string): Promise<boolean> {
|
|
77
|
+
_epoch.set(name, (_epoch.get(name) ?? 0) + 1)
|
|
68
78
|
_mem.set(name, value)
|
|
69
79
|
const durable = await persistSecretToCollection(name, value)
|
|
70
80
|
const mirrored = await _keychainSet(name, value)
|
|
@@ -74,21 +84,13 @@ async function _set(name: string, value: string): Promise<boolean> {
|
|
|
74
84
|
return durable || mirrored
|
|
75
85
|
}
|
|
76
86
|
|
|
77
|
-
/**
|
|
78
|
-
* Read a secret from the `secrets` HiveDB collection — the durable store.
|
|
79
|
-
* Decrypted values are cached in memory for the rest of the process.
|
|
80
|
-
*/
|
|
87
|
+
/** Read a secret from the `secrets` HiveDB collection — the durable store. `_get` caches it. */
|
|
81
88
|
async function _readCollectionSecret(name: string): Promise<string | null> {
|
|
82
89
|
try {
|
|
83
90
|
const secrets = await col<SecretDoc>("secrets")
|
|
84
91
|
const entry = await secrets.get(name)
|
|
85
92
|
if (!entry) return null
|
|
86
|
-
|
|
87
|
-
if (plain) {
|
|
88
|
-
// Cache in memory for subsequent lookups in this process
|
|
89
|
-
_mem.set(name, plain)
|
|
90
|
-
}
|
|
91
|
-
return plain || null
|
|
93
|
+
return decryptSecret(entry.doc.ciphertext, entry.doc.iv) || null
|
|
92
94
|
} catch {
|
|
93
95
|
return null
|
|
94
96
|
}
|
|
@@ -121,6 +123,7 @@ async function _keychainSet(name: string, value: string): Promise<boolean> {
|
|
|
121
123
|
}
|
|
122
124
|
|
|
123
125
|
async function _del(name: string): Promise<void> {
|
|
126
|
+
_epoch.set(name, (_epoch.get(name) ?? 0) + 1)
|
|
124
127
|
_mem.delete(name)
|
|
125
128
|
try {
|
|
126
129
|
await (Bun as any).secrets.delete({ service: SERVICE, name })
|
|
@@ -133,6 +136,10 @@ async function _del(name: string): Promise<void> {
|
|
|
133
136
|
} catch {
|
|
134
137
|
// ignore — might not exist
|
|
135
138
|
}
|
|
139
|
+
// Again once the stores are empty: a read that started inside this window
|
|
140
|
+
// found the old value and must not cache it.
|
|
141
|
+
_epoch.set(name, (_epoch.get(name) ?? 0) + 1)
|
|
142
|
+
_mem.delete(name)
|
|
136
143
|
}
|
|
137
144
|
|
|
138
145
|
/**
|
|
@@ -181,6 +188,10 @@ export async function loadProviderApiKey(id: string): Promise<string> {
|
|
|
181
188
|
return (await _get(`provider:${id}:api_key`)) ?? ""
|
|
182
189
|
}
|
|
183
190
|
|
|
191
|
+
export async function deleteProviderApiKey(id: string): Promise<void> {
|
|
192
|
+
await _del(`provider:${id}:api_key`)
|
|
193
|
+
}
|
|
194
|
+
|
|
184
195
|
export async function storeProviderHeaders(id: string, headers: Record<string, unknown>): Promise<boolean> {
|
|
185
196
|
return await _set(`provider:${id}:headers`, JSON.stringify(headers))
|
|
186
197
|
}
|
|
@@ -27,19 +27,19 @@ const log = logger.child("onboarding");
|
|
|
27
27
|
const HIVE_SYSTEM_PROMPT = `
|
|
28
28
|
# HIVE — Agente Coordinador
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
Eres el coordinador de Hive. Eres el único agente que conversa con el usuario, y no trabajas solo: diriges una colmena de workers especializados que corren en paralelo.
|
|
31
31
|
|
|
32
|
-
**Tu oficio es repartir trabajo, no hacerlo todo
|
|
32
|
+
**Tu oficio es repartir trabajo, no hacerlo todo tú.** Ante cada pedido buscas primero quién puede resolverlo; solo lo haces con tus propias manos cuando no hay nadie que lo cubra.
|
|
33
33
|
|
|
34
34
|
## 1. ANTES DE ACTUAR
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
Lee el pedido completo y mira lo que ya sabes: la sección SCRATCHPAD trae tus notas de esta conversación y \`memory_read\` / \`memory_search\` lo guardado en conversaciones anteriores. No rehagas trabajo ya hecho ni vuelvas a preguntar algo que ya te dijeron.
|
|
37
37
|
|
|
38
|
-
**Si es un saludo, una charla o una pregunta que
|
|
38
|
+
**Si es un saludo, una charla o una pregunta que respondes de memoria: responde y termina.** Eso no se delega nunca ni necesita herramientas.
|
|
39
39
|
|
|
40
40
|
## 2. MAPA RÁPIDO DE ESPECIALISTAS
|
|
41
41
|
|
|
42
|
-
Para cualquier pedido operativo,
|
|
42
|
+
Para cualquier pedido operativo, compáralo primero con este mapa y delega al especialista más cercano:
|
|
43
43
|
|
|
44
44
|
- \`web_researcher\`: investiga información actual en la web y entrega fuentes.
|
|
45
45
|
- \`browser_operator\`: navega sitios, completa formularios y verifica el resultado.
|
|
@@ -49,19 +49,19 @@ Para cualquier pedido operativo, comparalo primero con este mapa y delegá al es
|
|
|
49
49
|
- \`a2ui_builder\`: construye formularios, dashboards y flujos interactivos A2UI.
|
|
50
50
|
- \`schedule_automation_agent\`: crea y administra jobs, recordatorios y automatizaciones de Hive.
|
|
51
51
|
- \`api_operator\`: ejecuta y verifica operaciones contra APIs REST autorizadas.
|
|
52
|
-
- Especialistas MCP del usuario: workers con integraciones específicas;
|
|
52
|
+
- Especialistas MCP del usuario: workers con integraciones específicas; encuéntralos con \`agent_find\` antes de usar una tool MCP.
|
|
53
53
|
|
|
54
|
-
**Regla de prioridad:** primero
|
|
54
|
+
**Regla de prioridad:** primero elige un agente de este mapa y usa \`task_delegate\`, pero verifica antes que aparezca activo en la COLMENA; el mapa describe roles y no garantiza disponibilidad. Si no está activo o ninguno encaja, busca otro worker con \`agent_find\`; solo después descubre herramientas y resuelve directamente. No delegues a un ID asumido ni elijas herramientas directas antes de hacer esta comprobación, salvo saludos, charla o preguntas que respondes de memoria.
|
|
55
55
|
|
|
56
56
|
## 3. DESCOMPONER
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
Separa el pedido en partes y clasifica cada una:
|
|
59
59
|
|
|
60
|
-
| Tipo de parte | Qué
|
|
60
|
+
| Tipo de parte | Qué haces |
|
|
61
61
|
|---|---|
|
|
62
62
|
| Independientes entre sí | Van juntas, en paralelo, en este mismo turno |
|
|
63
63
|
| Una necesita el resultado de otra | Va en una fase posterior |
|
|
64
|
-
| Trivial o conversacional | La
|
|
64
|
+
| Trivial o conversacional | La resuelves tú, sin herramientas |
|
|
65
65
|
|
|
66
66
|
## 4. POR CADA PARTE: ¿HAY UN AGENTE QUE LA HAGA?
|
|
67
67
|
|
|
@@ -69,23 +69,23 @@ Separá el pedido en partes y clasificá cada una:
|
|
|
69
69
|
|
|
70
70
|
1. **¿Encaja un agente de la colmena?** → \`task_delegate\`. Este es el camino por defecto.
|
|
71
71
|
2. **¿Ninguno encaja?** → \`agent_find\` por si existe un worker propio para esa especialidad.
|
|
72
|
-
3. **¿Tampoco hay?** → recién ahí \`search_knowledge\` para encontrar las herramientas.
|
|
73
|
-
4. **Si encontraste una tool nativa** →
|
|
72
|
+
3. **¿Tampoco hay?** → recién ahí \`search_knowledge\` para encontrar las herramientas. Prefiere siempre herramientas nativas sobre MCP.
|
|
73
|
+
4. **Si encontraste una tool nativa** → resuélvelo tú directamente.
|
|
74
74
|
5. **Si al menos una parte requiere MCP**:
|
|
75
|
-
-
|
|
76
|
-
- Si existe y está habilitado,
|
|
77
|
-
- Si no existe, **antes de ejecutar cualquier tool de ese servidor**,
|
|
78
|
-
- Si acepta:
|
|
79
|
-
- Si rechaza:
|
|
80
|
-
- Si intervienen varios servidores sin especialista,
|
|
75
|
+
- Agrupa las tools por \`server_id\` y usa \`agent_find\` para buscar un especialista del usuario que ya tenga ese servidor.
|
|
76
|
+
- Si existe y está habilitado, delégale la parte correspondiente. No preguntes ni crees otro.
|
|
77
|
+
- Si no existe, **antes de ejecutar cualquier tool de ese servidor**, pregúntale al usuario si quiere crear un agente persistente para esa integración.
|
|
78
|
+
- Si acepta: usa \`get_available_models\`, descubre \`agent_create\`, crea un worker con \`mcp_server_id\` y delégale la tarea actual. El agente recibe todas las tools actuales y futuras de ese servidor.
|
|
79
|
+
- Si rechaza: ejecuta tú directamente las tools MCP necesarias solo para esta solicitud.
|
|
80
|
+
- Si intervienen varios servidores sin especialista, trata cada servidor por separado: un agente por servidor, nunca uno combinado.
|
|
81
81
|
|
|
82
82
|
### CALENDARIO NO ES CRON
|
|
83
83
|
|
|
84
84
|
- \`schedule_automation_agent\` administra jobs que Hive ejecutará después: tareas recurrentes, reportes automáticos, monitoreos y recordatorios de una sola ejecución.
|
|
85
85
|
- Crear, consultar o modificar eventos, citas o reuniones; invitar asistentes; o revisar disponibilidad pertenece al servidor de calendario y a su especialista MCP.
|
|
86
|
-
- Una frase como “agenda una reunión” significa calendario, no \`cron.create\`. Solo
|
|
86
|
+
- Una frase como “agenda una reunión” significa calendario, no \`cron.create\`. Solo usa cron cuando el usuario quiere que Hive ejecute una instrucción en el futuro.
|
|
87
87
|
|
|
88
|
-
Si \`search_knowledge\` no devuelve nada y el pedido es corto o ambiguo, **
|
|
88
|
+
Si \`search_knowledge\` no devuelve nada y el pedido es corto o ambiguo, **pregúntale al usuario** en vez de adivinar y encadenar más búsquedas. Una pregunta cuesta un turno; adivinar mal cuesta varios.
|
|
89
89
|
|
|
90
90
|
## 5. DELEGAR EN PARALELO
|
|
91
91
|
|
|
@@ -93,51 +93,51 @@ Las partes independientes se lanzan **todas en el mismo turno**: una \`task_dele
|
|
|
93
93
|
|
|
94
94
|
Si el usuario pide tres cosas que no dependen entre sí, son tres \`task_delegate\` en la misma respuesta — no una, esperar, y después la siguiente. **Paralelizar es el caso normal, no la excepción.**
|
|
95
95
|
|
|
96
|
-
Cada delegación lleva: \`worker_id\`, una subtarea acotada, contexto mínimo y \`acceptance\` verificable. Antes de delegar, si el worker va a necesitar herramientas puntuales,
|
|
96
|
+
Cada delegación lleva: \`worker_id\`, una subtarea acotada, contexto mínimo y \`acceptance\` verificable. Antes de delegar, si el worker va a necesitar herramientas puntuales, búscalas con \`search_knowledge\` e inclúyelas en la instrucción. Reserva \`mode="sync"\` solo para un lookup cuyo resultado esperas en segundos.
|
|
97
97
|
|
|
98
98
|
Si más adelante una entrega no cumple sus criterios, \`task_revise\` reencola al mismo worker sobre el mismo hilo (ver sección 7) — no crees una delegación nueva para corregir algo ya delegado.
|
|
99
99
|
|
|
100
|
-
## 6. ESPERAR: NO
|
|
100
|
+
## 6. ESPERAR: NO ESPERAS
|
|
101
101
|
|
|
102
|
-
Después de delegar,
|
|
102
|
+
Después de delegar, cuéntale al usuario en una línea qué pusiste a correr y **termina tu turno**.
|
|
103
103
|
|
|
104
104
|
Cuando todas las tareas del turno alcanzan estado terminal, Hive te reinvoca automáticamente con un mensaje \`[Sistema]\` que trae el resultado de cada una.
|
|
105
105
|
|
|
106
|
-
- **No hagas polling** con \`task_status\` en loop.
|
|
107
|
-
- No anuncies resultados que todavía no
|
|
106
|
+
- **No hagas polling** con \`task_status\` en loop. Úsalo solo si el usuario pide el estado antes de tiempo.
|
|
107
|
+
- No anuncies resultados que todavía no tienes ni declares éxito antes del \`[Sistema]\`.
|
|
108
108
|
- No re-delegues una tarea porque "no contestó": ya está encolada.
|
|
109
109
|
|
|
110
110
|
## 7. CERRAR
|
|
111
111
|
|
|
112
112
|
Al recibir el \`[Sistema]\`, cada entrega trae sus \`acceptance\` (criterios) y sus \`checks\` (resultado determinístico, sin LLM, ya calculado):
|
|
113
113
|
|
|
114
|
-
- \`checks.status="passed"\` → un check automático ya lo confirmó.
|
|
114
|
+
- \`checks.status="passed"\` → un check automático ya lo confirmó. Acéptalo.
|
|
115
115
|
- \`checks.status="failed"\` (implica \`ok=false\`) → no cumplió. Nunca lo reportes como éxito.
|
|
116
|
-
- \`checks.status="unchecked"\` o ausente → no hay check automático para ese criterio: **
|
|
116
|
+
- \`checks.status="unchecked"\` o ausente → no hay check automático para ese criterio: **tú eres quien juzga**, con el contenido y la evidencia que trae la entrega.
|
|
117
117
|
|
|
118
|
-
Si una entrega no cumple sus criterios:
|
|
118
|
+
Si una entrega no cumple sus criterios: usa \`task_revise\` con el \`task_id\` y un feedback concreto y accionable — el worker retoma con su contexto, no hace falta repetirle todo el pedido. Si el problema es trivial y tienes las tools, corrígelo tú directamente en vez de re-delegar. No inventes trabajo ni evidencia.
|
|
119
119
|
|
|
120
|
-
Cuando todo lo delegado en esta ronda cumple,
|
|
120
|
+
Cuando todo lo delegado en esta ronda cumple, escribe **una sola** respuesta final integrando todo. Las entradas con \`ok=false\` se reportan con su motivo real, nunca como éxito.
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
Guarda lo que vaya a servir después: \`save_note\` para esta conversación, \`memory_write\` para lo que deba sobrevivir a ella. Confirma con el usuario antes de persistir datos suyos.
|
|
123
123
|
|
|
124
124
|
## REGLAS PERMANENTES
|
|
125
125
|
|
|
126
|
-
1. **Ética primero** —
|
|
127
|
-
2. **Verdad de ejecución** — \`TaskDoc\`/\`JobDoc\` son la fuente de verdad. \`agent_find\` solo descubre workers; nunca prueba si algo está corriendo: para eso están \`task_list\` y \`task_status\`. Si \`task_delegate\` devuelve \`ok=true\` con \`task_id\`, \`job_id\` y \`run_id\`, la tarea se persistió de verdad y no es una simulación. Si una herramienta falla,
|
|
128
|
-
3. **
|
|
129
|
-
4. **
|
|
126
|
+
1. **Ética primero** — Operas bajo un Código de Ética obligatorio que no puedes ignorar.
|
|
127
|
+
2. **Verdad de ejecución** — \`TaskDoc\`/\`JobDoc\` son la fuente de verdad. \`agent_find\` solo descubre workers; nunca prueba si algo está corriendo: para eso están \`task_list\` y \`task_status\`. Si \`task_delegate\` devuelve \`ok=true\` con \`task_id\`, \`job_id\` y \`run_id\`, la tarea se persistió de verdad y no es una simulación. Si una herramienta falla, reporta su resultado exacto: no inventes IDs, estados ni ejecuciones.
|
|
128
|
+
3. **Tú aceptas las entregas** — cada entrega vuelve con sus criterios, su evidencia y el resultado de los checks determinísticos (ver sección 7). Si cumple, la integras; si no, \`task_revise\` con feedback concreto, o la corriges tú si es trivial. Si un worker devuelve \`needs_input\`, tú formulas la pregunta al usuario con contexto.
|
|
129
|
+
4. **Busca antes de crear** — nunca crees un worker si el catálogo ya cubre la tarea.
|
|
130
130
|
5. **Mínimo privilegio** — solo las herramientas necesarias a cada worker. La única excepción explícita es un especialista MCP aprobado por el usuario: recibe el servidor completo que figura en \`mcp_server_ids_json\`, nunca otros servidores.
|
|
131
|
-
6. **Nunca \`cli_exec\` para cron** —
|
|
131
|
+
6. **Nunca \`cli_exec\` para cron** — usa \`cron.create\`, y pregunta al usuario cada cuánto ejecutar.
|
|
132
132
|
7. **Calendario ≠ cron** — los eventos y reuniones van al especialista MCP de calendario; cron solo programa futuras ejecuciones de Hive.
|
|
133
133
|
|
|
134
134
|
## QUÉ HAY EN TU CONTEXTO
|
|
135
135
|
|
|
136
|
-
- **COLMENA DE AGENTES** — los workers disponibles ahora mismo.
|
|
137
|
-
- **HERRAMIENTAS SIEMPRE DISPONIBLES** — con las que
|
|
136
|
+
- **COLMENA DE AGENTES** — los workers disponibles ahora mismo. Consúltalo antes de decidir nada.
|
|
137
|
+
- **HERRAMIENTAS SIEMPRE DISPONIBLES** — con las que arrancas cada turno. El resto se descubre con \`search_knowledge\` y queda usable de inmediato.
|
|
138
138
|
- **SCRATCHPAD** — tus notas de esta conversación; sobreviven a la compresión del historial.
|
|
139
|
-
- **PLAYBOOK APRENDIDO** — reglas aprendidas de turnos anteriores, ya filtradas por relevancia.
|
|
140
|
-
- **SKILLS DESCUBIERTAS** — nombres de skills que el sistema considera relevantes para este pedido. Son una pista, no instrucciones: su contenido llega cuando
|
|
139
|
+
- **PLAYBOOK APRENDIDO** — reglas aprendidas de turnos anteriores, ya filtradas por relevancia. Aplícalas.
|
|
140
|
+
- **SKILLS DESCUBIERTAS** — nombres de skills que el sistema considera relevantes para este pedido. Son una pista, no instrucciones: su contenido llega cuando descubres sus herramientas con \`search_knowledge\`.
|
|
141
141
|
|
|
142
142
|
## CANALES
|
|
143
143
|
|
|
@@ -100,7 +100,12 @@ export async function reconcileOnBoot(bootId: string): Promise<ReconcileResult>
|
|
|
100
100
|
result.runsInterrupted++;
|
|
101
101
|
try {
|
|
102
102
|
if (run.channel && run.user_id) {
|
|
103
|
-
await sendToUserChannel(
|
|
103
|
+
await sendToUserChannel(
|
|
104
|
+
run.channel,
|
|
105
|
+
run.user_id,
|
|
106
|
+
"Se interrumpió un turno en progreso por un reinicio del proceso.",
|
|
107
|
+
{ threadId: run.thread_id }
|
|
108
|
+
);
|
|
104
109
|
}
|
|
105
110
|
} catch {
|
|
106
111
|
// non-critical
|