@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
|
@@ -37,12 +37,12 @@ ${s.workflow.map((step, index) => `${index + 1}. ${step}`).join("\n")}
|
|
|
37
37
|
|
|
38
38
|
# QUÉ NO HACES
|
|
39
39
|
${s.prohibitions.map((rule) => `- ${rule}`).join("\n")}
|
|
40
|
-
- No
|
|
41
|
-
- No
|
|
42
|
-
- No
|
|
40
|
+
- No hablas con el usuario, no pides confirmaciones directas y no delegas a otros agentes.
|
|
41
|
+
- No amplías el alcance ni usas tools fuera del loadout autorizado.
|
|
42
|
+
- No declaras éxito sin evidencia comprobable para cada criterio.
|
|
43
43
|
|
|
44
44
|
# FORMATO DE ENTREGA
|
|
45
|
-
|
|
45
|
+
Devuelve exclusivamente un objeto estructurado con:
|
|
46
46
|
- status: completed | needs_input | partial | failed
|
|
47
47
|
- what_was_done: resumen factual
|
|
48
48
|
- artifacts: paths, URLs, surface IDs, job IDs u otros artefactos
|
|
@@ -55,8 +55,8 @@ ${s.quality}`;
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
const COMMON_PROHIBITIONS = [
|
|
58
|
-
"No
|
|
59
|
-
"No
|
|
58
|
+
"No inventas resultados, archivos, status HTTP, capturas ni efectos externos.",
|
|
59
|
+
"No expones credenciales, tokens, cookies, secretos ni datos privados en la entrega.",
|
|
60
60
|
];
|
|
61
61
|
|
|
62
62
|
const CODE_MODEL: AgentModelOverride = {
|
|
@@ -72,12 +72,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
72
72
|
role: "Tu dominio es investigación web, contraste de fuentes y síntesis basada en evidencia.",
|
|
73
73
|
receives: "Una pregunta acotada, contexto relevante, restricciones de actualidad y criterios de aceptación.",
|
|
74
74
|
workflow: [
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
78
|
-
"
|
|
75
|
+
"Convierte la pregunta en consultas concretas y busca fuentes primarias o autorizadas.",
|
|
76
|
+
"Lee las fuentes relevantes y separa hechos, inferencias y datos no confirmados.",
|
|
77
|
+
"Contrasta afirmaciones sensibles o discutidas con más de una fuente.",
|
|
78
|
+
"Entrega una síntesis concisa con referencias y fechas cuando sean relevantes.",
|
|
79
79
|
],
|
|
80
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
80
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No automatizas formularios ni realizas acciones en sitios."],
|
|
81
81
|
quality: "Cada afirmación material debe poder rastrearse a una fuente accesible; los desacuerdos se presentan explícitamente.",
|
|
82
82
|
routingExamples: ["investigar una noticia", "comparar información actual", "buscar fuentes para un informe"],
|
|
83
83
|
tools: ["web_search", "web_fetch"],
|
|
@@ -92,12 +92,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
92
92
|
role: "Tu dominio es navegación y automatización web renderizada.",
|
|
93
93
|
receives: "Una acción web autorizada, URL inicial, datos permitidos, estado final esperado y límites de seguridad.",
|
|
94
94
|
workflow: [
|
|
95
|
-
"
|
|
96
|
-
"
|
|
97
|
-
"
|
|
98
|
-
"
|
|
95
|
+
"Abre el sitio y verifica que corresponda al objetivo.",
|
|
96
|
+
"Inspecciona el estado antes de interactuar y usa selectores estables.",
|
|
97
|
+
"Ejecuta solamente los clicks, escritura y esperas necesarios.",
|
|
98
|
+
"Verifica el estado final mediante extracción y captura de pantalla.",
|
|
99
99
|
],
|
|
100
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
100
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No confirmas compras, envíos, borrados o publicaciones si el principal no autorizó explícitamente ese efecto."],
|
|
101
101
|
quality: "La entrega incluye URL final, estado observado y evidencia visual o estructurada posterior a la acción.",
|
|
102
102
|
routingExamples: ["llenar un formulario", "iniciar sesión", "hacer clic y verificar una página"],
|
|
103
103
|
tools: ["browser_*", "web_fetch"],
|
|
@@ -112,12 +112,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
112
112
|
role: "Tu dominio es operaciones seguras sobre archivos y carpetas del workspace.",
|
|
113
113
|
receives: "Paths relativos o autorizados, contenido solicitado, operación exacta y estado final esperado.",
|
|
114
114
|
workflow: [
|
|
115
|
-
"
|
|
116
|
-
"
|
|
117
|
-
"
|
|
118
|
-
"
|
|
115
|
+
"Resuelve todos los paths contra el workspace y comprueba su estado inicial.",
|
|
116
|
+
"Aplica la mínima operación necesaria sin tocar paths ajenos.",
|
|
117
|
+
"Vuelve a leer o listar el resultado para comprobarlo.",
|
|
118
|
+
"Reporta paths exactos, cambios y evidencia de readback.",
|
|
119
119
|
],
|
|
120
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
120
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No ejecutas comandos shell ni modificas repositorios fuera de la operación de archivos pedida."],
|
|
121
121
|
quality: "Todos los paths permanecen dentro del workspace y su contenido o ausencia final se comprueba después de la operación.",
|
|
122
122
|
routingExamples: ["crear una carpeta", "editar un archivo de texto", "organizar archivos"],
|
|
123
123
|
tools: ["fs_*"],
|
|
@@ -132,12 +132,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
132
132
|
role: "Tu dominio es ingeniería de software, diagnóstico, cambios mínimos y validación automatizada.",
|
|
133
133
|
receives: "Objetivo técnico, repositorio, restricciones, comportamiento esperado y comandos de validación disponibles.",
|
|
134
134
|
workflow: [
|
|
135
|
-
"
|
|
136
|
-
"
|
|
137
|
-
"
|
|
138
|
-
"
|
|
135
|
+
"Inspecciona el repositorio, convenciones y estado antes de editar.",
|
|
136
|
+
"Determina la causa o el diseño mínimo y modifica solo archivos pertinentes.",
|
|
137
|
+
"Ejecuta checks, tests o builds proporcionales al riesgo.",
|
|
138
|
+
"Entrega archivos cambiados, evidencia de validación y riesgos restantes.",
|
|
139
139
|
],
|
|
140
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
140
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No sobrescribes cambios ajenos, no publicas y no delegas a subagentes CLI."],
|
|
141
141
|
quality: "El cambio satisface el comportamiento pedido, preserva compatibilidad y pasa las validaciones relevantes.",
|
|
142
142
|
routingExamples: ["implementar una función", "arreglar un bug", "ejecutar tests de un proyecto"],
|
|
143
143
|
tools: ["fs_*", "cli_exec"],
|
|
@@ -153,12 +153,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
153
153
|
role: "Tu dominio es lectura y generación de archivos Office estructurados.",
|
|
154
154
|
receives: "Archivo de entrada o especificación del documento, formato final, contenido y path autorizado.",
|
|
155
155
|
workflow: [
|
|
156
|
-
"
|
|
157
|
-
"
|
|
158
|
-
"
|
|
159
|
-
"
|
|
156
|
+
"Inspecciona entradas y confirma el formato solicitado.",
|
|
157
|
+
"Genera o extrae contenido preservando estructura y datos.",
|
|
158
|
+
"Comprueba que el archivo existe, no está vacío y puede reabrirse.",
|
|
159
|
+
"Entrega el path final, resumen de contenido y prueba de reapertura.",
|
|
160
160
|
],
|
|
161
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
161
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No editas formatos binarios con tools genéricas de filesystem."],
|
|
162
162
|
quality: "El artefacto debe abrir sin error con la tool lectora correspondiente y contener la estructura solicitada.",
|
|
163
163
|
routingExamples: ["crear un Excel", "leer un PDF", "generar una presentación"],
|
|
164
164
|
tools: ["office_*", "fs_exists"],
|
|
@@ -173,12 +173,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
173
173
|
role: "Tu dominio es superficies A2UI v0.9, componentes planos y data binding.",
|
|
174
174
|
receives: "Sesión, surfaceId, flujo solicitado, datos, acciones permitidas y criterios visuales.",
|
|
175
175
|
workflow: [
|
|
176
|
-
"
|
|
177
|
-
"
|
|
178
|
-
"
|
|
179
|
-
"
|
|
176
|
+
"Diseña una jerarquía pequeña con IDs únicos y un root explícito.",
|
|
177
|
+
"Crea la superficie antes de enviar componentes.",
|
|
178
|
+
"Envía componentes válidos y después el data model enlazado.",
|
|
179
|
+
"Comprueba acknowledgements, IDs y paths; libera la superficie al cancelar.",
|
|
180
180
|
],
|
|
181
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
181
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No interpretas acciones del usuario ni conversas; los eventos vuelven al principal."],
|
|
182
182
|
quality: "La superficie usa el catálogo v0.9, no tiene referencias rotas y sus bindings apuntan a paths válidos.",
|
|
183
183
|
routingExamples: ["crear formulario A2UI", "dashboard interactivo", "wizard de varios pasos"],
|
|
184
184
|
tools: ["a2ui_*"],
|
|
@@ -193,15 +193,15 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
193
193
|
role: "Tu dominio son los jobs técnicos programados de Hive, su recurrencia, ventanas temporales y zonas horarias.",
|
|
194
194
|
receives: "Una automatización que Hive debe ejecutar después, su horario o recurrencia, timezone, canal y comportamiento esperado.",
|
|
195
195
|
workflow: [
|
|
196
|
-
"
|
|
197
|
-
"
|
|
198
|
-
"
|
|
199
|
-
"
|
|
196
|
+
"Normaliza fecha, recurrencia y timezone sin cambiar la intención.",
|
|
197
|
+
"Crea o modifica únicamente el job solicitado.",
|
|
198
|
+
"Consulta el job persistido y su próxima ejecución.",
|
|
199
|
+
"Entrega ID, estado, timezone y next_run_at.",
|
|
200
200
|
],
|
|
201
201
|
prohibitions: [
|
|
202
202
|
...COMMON_PROHIBITIONS,
|
|
203
|
-
"No
|
|
204
|
-
"No
|
|
203
|
+
"No inventas una hora cuando la ambigüedad cambia materialmente el resultado.",
|
|
204
|
+
"No creas, consultas ni modificas eventos, citas, reuniones, asistentes o disponibilidad de un calendario externo.",
|
|
205
205
|
],
|
|
206
206
|
quality: "La definición persistida representa la intención temporal y su próxima ejecución es comprobable.",
|
|
207
207
|
routingExamples: ["ejecutar una tarea cada hora", "programar un reporte semanal", "pausar un cron job"],
|
|
@@ -222,12 +222,12 @@ const CATALOG_PERSONAS: CatalogPersona[] = [
|
|
|
222
222
|
role: "Tu dominio es requests REST, contratos HTTP y validación de respuestas.",
|
|
223
223
|
receives: "Endpoint autorizado, método, headers permitidos, payload, status esperado y esquema relevante.",
|
|
224
224
|
workflow: [
|
|
225
|
-
"
|
|
226
|
-
"
|
|
227
|
-
"
|
|
228
|
-
"
|
|
225
|
+
"Valida método, host, payload y alcance antes del request.",
|
|
226
|
+
"Ejecuta una sola operación idempotente o explícitamente autorizada.",
|
|
227
|
+
"Comprueba status, headers y forma de la respuesta.",
|
|
228
|
+
"Entrega evidencia saneada sin secretos.",
|
|
229
229
|
],
|
|
230
|
-
prohibitions: [...COMMON_PROHIBITIONS, "No
|
|
230
|
+
prohibitions: [...COMMON_PROHIBITIONS, "No repites mutaciones automáticamente ni cambias método, host o payload para forzar éxito."],
|
|
231
231
|
quality: "El status y contrato observados coinciden con los criterios y la evidencia no contiene credenciales.",
|
|
232
232
|
routingExamples: ["hacer un GET a una API", "enviar un POST autorizado", "validar respuesta REST"],
|
|
233
233
|
tools: ["api_request"],
|
|
@@ -25,12 +25,15 @@ import { maybeCompact, clearOldToolResults } from "./compaction"
|
|
|
25
25
|
import { emitCanvas } from "../canvas/emitter"
|
|
26
26
|
import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
|
|
27
27
|
import { compileContext } from "./context-compiler"
|
|
28
|
+
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
28
29
|
import { formatToolResult } from "../utils/toon"
|
|
29
30
|
import { redactBinaryStrings } from "../utils/redact-binary"
|
|
30
31
|
import { resolveUserId, resolveAgentId } from "../storage/onboarding"
|
|
31
32
|
import type { ContentPart } from "../multimodal/types"
|
|
32
33
|
import { loadConfig } from "../config/loader"
|
|
33
34
|
import { executeToolBatch } from "../tool-runtime"
|
|
35
|
+
import { jevWantsParallel, planJevIteration } from "./jev-planner"
|
|
36
|
+
import { emitJevDecision } from "./jev-decisions"
|
|
34
37
|
import { createStuckLoopDetector, getInterventionMessage, type StuckLoopState } from "./stuck-loop"
|
|
35
38
|
import {
|
|
36
39
|
createRun as createAgentRun,
|
|
@@ -51,6 +54,10 @@ import { getNarration } from "../events/tool-narration"
|
|
|
51
54
|
|
|
52
55
|
const log = logger.child("agent-loop")
|
|
53
56
|
|
|
57
|
+
const JEV_ACTION_LABELS: Record<string, string> = {
|
|
58
|
+
continue: "Continuar", delegate: "Delegar", discover: "Descubrir", finish: "Cerrar",
|
|
59
|
+
}
|
|
60
|
+
|
|
54
61
|
// Per-operation budget for a single LLM call — NOT an aggregate deadline for the
|
|
55
62
|
// whole turn. Each call gets its own fresh window; a slow-but-healthy multi-step
|
|
56
63
|
// turn (many quick operations) is never killed just for taking a while overall.
|
|
@@ -352,7 +359,9 @@ export async function* runAgent(
|
|
|
352
359
|
opts.threadId,
|
|
353
360
|
opts.channel && opts.userId
|
|
354
361
|
? { channel: opts.channel, userId: opts.userId }
|
|
355
|
-
: undefined
|
|
362
|
+
: undefined,
|
|
363
|
+
providerCfg.contextWindow,
|
|
364
|
+
opts.signal,
|
|
356
365
|
)
|
|
357
366
|
}
|
|
358
367
|
|
|
@@ -367,7 +376,12 @@ export async function* runAgent(
|
|
|
367
376
|
taskContext: opts.taskContext,
|
|
368
377
|
userId: opts.userId,
|
|
369
378
|
causalStreamId,
|
|
379
|
+
skipJev: !!opts.resume,
|
|
380
|
+
contextWindow: providerCfg.contextWindow,
|
|
370
381
|
})
|
|
382
|
+
if (ctx.jevDecision) {
|
|
383
|
+
emitJevDecision({ ...ctx.jevDecision, agentId: opts.agentId, kind: "context", provider: providerCfg.provider, model: providerCfg.model })
|
|
384
|
+
}
|
|
371
385
|
|
|
372
386
|
// Force extra tools into the loadout (tests/evals)
|
|
373
387
|
if (opts.extraTools?.length) {
|
|
@@ -399,9 +413,11 @@ export async function* runAgent(
|
|
|
399
413
|
if (opts.isolated) {
|
|
400
414
|
messages.push({ role: "user", content: opts.userMessage })
|
|
401
415
|
}
|
|
416
|
+
const jevObjective = typeof opts.userMessage === "string" ? opts.userMessage :
|
|
417
|
+
opts.userMessage.filter((part) => part.type === "text").map((part) => (part as { text: string }).text).join("\n")
|
|
402
418
|
|
|
403
419
|
// ── Resume from checkpoint ─────────────────────────────────────────────────
|
|
404
|
-
let injectedToolNames: string[] =
|
|
420
|
+
let injectedToolNames: string[] = ctx.tools.map(t => t.function.name).filter(name => !MINIMAL_TOOLS.has(name))
|
|
405
421
|
let systemPromptSkillSections: string[] = []
|
|
406
422
|
let resumedFromPending = false
|
|
407
423
|
let iterations = 0
|
|
@@ -422,6 +438,14 @@ export async function* runAgent(
|
|
|
422
438
|
if (restored) {
|
|
423
439
|
messages = restored.messages
|
|
424
440
|
injectedToolNames = restored.injectedToolNames ?? []
|
|
441
|
+
const currentTools = new Set(ctx.tools.map(t => t.function.name))
|
|
442
|
+
for (const name of injectedToolNames) {
|
|
443
|
+
const tool = ctx.allTools.find(t => t.name === name)
|
|
444
|
+
if (tool && !currentTools.has(name)) {
|
|
445
|
+
ctx.tools.push({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } })
|
|
446
|
+
currentTools.add(name)
|
|
447
|
+
}
|
|
448
|
+
}
|
|
425
449
|
systemPromptSkillSections = restored.systemPromptSkillSections ?? []
|
|
426
450
|
iterations = restored.iterations ?? 0
|
|
427
451
|
totalInputTokens = restored.totalInputTokens ?? 0
|
|
@@ -434,7 +458,7 @@ export async function* runAgent(
|
|
|
434
458
|
const pending = JSON.parse(existing.pending_tool_calls_json)
|
|
435
459
|
const interruptedMsgs = pending.map((tc: any) => ({
|
|
436
460
|
role: "tool" as const,
|
|
437
|
-
content: "[interrupted] El proceso se reinició mientras esta herramienta corría. El resultado no está disponible —
|
|
461
|
+
content: "[interrupted] El proceso se reinició mientras esta herramienta corría. El resultado no está disponible — decide si reintentar o continuar sin él.",
|
|
438
462
|
tool_call_id: tc.id,
|
|
439
463
|
}))
|
|
440
464
|
messages.push(...interruptedMsgs)
|
|
@@ -507,12 +531,30 @@ export async function* runAgent(
|
|
|
507
531
|
: null
|
|
508
532
|
let streamedThisCall = false
|
|
509
533
|
let response: Awaited<ReturnType<typeof callLLM>>
|
|
534
|
+
const jevIteration = await planJevIteration({ objective: jevObjective, messages, tools: ctx.tools })
|
|
535
|
+
.catch((err) => { log.warn(`[agent-loop] Jev iteration fallback: ${(err as Error).message}`); return null })
|
|
536
|
+
const callMessages = jevIteration?.messages ?? messages
|
|
537
|
+
const callTools = jevIteration?.tools ?? ctx.tools
|
|
538
|
+
if (jevIteration) {
|
|
539
|
+
log.info(`[agent-loop] Jev action=${jevIteration.action} omitted_results=${jevIteration.omittedResults} tools=${callTools.map(t => t.function.name).join(",")}`)
|
|
540
|
+
// Measured on what the provider actually receives, after the usual truncation.
|
|
541
|
+
const payloadChars = (msgs: LLMMessage[], tools: typeof ctx.tools) =>
|
|
542
|
+
JSON.stringify(clearOldToolResults(msgs)).length + JSON.stringify(tools).length
|
|
543
|
+
emitJevDecision({
|
|
544
|
+
agentId: opts.agentId, kind: "iteration", provider: providerCfg.provider, model: providerCfg.model,
|
|
545
|
+
summary: `${JEV_ACTION_LABELS[jevIteration.action] ?? jevIteration.action} · ${jevIteration.omittedResults} resultado(s) omitido(s) · ${callTools.length}/${ctx.tools.length} herramientas`,
|
|
546
|
+
savedTokens: Math.round((payloadChars(messages, ctx.tools) - payloadChars(callMessages, callTools)) / 4),
|
|
547
|
+
latencyMs: jevIteration.decision.latencyMs, costUsd: jevIteration.decision.costUsd,
|
|
548
|
+
})
|
|
549
|
+
}
|
|
550
|
+
const llmCallStartedAt = performance.now()
|
|
510
551
|
try {
|
|
511
552
|
response = await withTimeout(() => callLLM({
|
|
512
553
|
...providerCfg,
|
|
513
|
-
messages: clearOldToolResults(
|
|
514
|
-
tools:
|
|
554
|
+
messages: clearOldToolResults(callMessages) as LLMMessage[],
|
|
555
|
+
tools: callTools.length > 0 ? callTools : undefined,
|
|
515
556
|
signal: opts.signal,
|
|
557
|
+
sessionId: opts.threadId,
|
|
516
558
|
onToken: opts.onToken && !delegationGroupAtCall
|
|
517
559
|
? (token: string) => {
|
|
518
560
|
streamedThisCall = true
|
|
@@ -527,7 +569,7 @@ export async function* runAgent(
|
|
|
527
569
|
} catch (err) {
|
|
528
570
|
if (err instanceof LLMCallTimeoutError) {
|
|
529
571
|
log.warn(`[agent-loop] ${err.message} at iteration ${iterations}. Breaking.`)
|
|
530
|
-
finalContent = "El modelo tardó demasiado en responder.
|
|
572
|
+
finalContent = "El modelo tardó demasiado en responder. Intenta de nuevo o simplifica la consulta."
|
|
531
573
|
break
|
|
532
574
|
}
|
|
533
575
|
throw err
|
|
@@ -544,6 +586,9 @@ export async function* runAgent(
|
|
|
544
586
|
if (response.usage) {
|
|
545
587
|
totalInputTokens += response.usage.input_tokens
|
|
546
588
|
totalOutputTokens += response.usage.output_tokens
|
|
589
|
+
recordLLMUsage({ provider: providerCfg.provider, model: providerCfg.model,
|
|
590
|
+
inputTokens: response.usage.input_tokens, outputTokens: response.usage.output_tokens,
|
|
591
|
+
latencyMs: Math.round(performance.now() - llmCallStartedAt) })
|
|
547
592
|
}
|
|
548
593
|
|
|
549
594
|
// G9: record this LLM response as a causal "decision", chained off the
|
|
@@ -670,6 +715,16 @@ export async function* runAgent(
|
|
|
670
715
|
}
|
|
671
716
|
}
|
|
672
717
|
|
|
718
|
+
const jevParallel = await jevWantsParallel(response.tool_calls)
|
|
719
|
+
.catch((err) => { log.warn(`[agent-loop] Jev parallel fallback: ${(err as Error).message}`); return null })
|
|
720
|
+
if (jevParallel?.decision) {
|
|
721
|
+
log.info(`[agent-loop] Jev parallel=${jevParallel.parallel} calls=${response.tool_calls.length}`)
|
|
722
|
+
emitJevDecision({
|
|
723
|
+
agentId: opts.agentId, kind: "parallel", provider: providerCfg.provider, model: providerCfg.model,
|
|
724
|
+
summary: `${response.tool_calls.length} herramientas ${jevParallel.parallel ? "en paralelo" : "en secuencia"}`,
|
|
725
|
+
savedTokens: 0, latencyMs: jevParallel.decision.latencyMs, costUsd: jevParallel.decision.costUsd,
|
|
726
|
+
})
|
|
727
|
+
}
|
|
673
728
|
const toolResults = await executeToolBatch({
|
|
674
729
|
toolCalls: response.tool_calls,
|
|
675
730
|
allTools: ctx.allTools,
|
|
@@ -690,6 +745,7 @@ export async function* runAgent(
|
|
|
690
745
|
},
|
|
691
746
|
hiveConfig,
|
|
692
747
|
workerPool: hiveConfig.tools?.workerPool,
|
|
748
|
+
parallelToolCalls: jevParallel?.parallel,
|
|
693
749
|
signal: opts.signal,
|
|
694
750
|
})
|
|
695
751
|
|
|
@@ -1121,14 +1177,19 @@ export async function* runAgent(
|
|
|
1121
1177
|
if (synthesisAttempt > 1) {
|
|
1122
1178
|
log.warn("[agent-loop] Retrying terminal synthesis after an empty or failed response")
|
|
1123
1179
|
}
|
|
1180
|
+
const synthesisStartedAt = performance.now()
|
|
1124
1181
|
const synthesis = await callLLM({
|
|
1125
1182
|
...providerCfg,
|
|
1126
1183
|
messages: clearOldToolResults(messages) as LLMMessage[],
|
|
1127
1184
|
tools: undefined, // no tools — force text response
|
|
1185
|
+
sessionId: opts.threadId,
|
|
1128
1186
|
})
|
|
1129
1187
|
if (synthesis.usage) {
|
|
1130
1188
|
totalInputTokens += synthesis.usage.input_tokens
|
|
1131
1189
|
totalOutputTokens += synthesis.usage.output_tokens
|
|
1190
|
+
recordLLMUsage({ provider: providerCfg.provider, model: providerCfg.model,
|
|
1191
|
+
inputTokens: synthesis.usage.input_tokens, outputTokens: synthesis.usage.output_tokens,
|
|
1192
|
+
latencyMs: Math.round(performance.now() - synthesisStartedAt) })
|
|
1132
1193
|
}
|
|
1133
1194
|
// A provider failure comes back as non-empty `content`, which the
|
|
1134
1195
|
// empty-content check above would happily accept as a valid synthesis and
|
|
@@ -1169,14 +1230,6 @@ export async function* runAgent(
|
|
|
1169
1230
|
changes: { status: "idle", currentTool: null },
|
|
1170
1231
|
})
|
|
1171
1232
|
|
|
1172
|
-
// Record usage
|
|
1173
|
-
recordLLMUsage({
|
|
1174
|
-
provider: providerCfg.provider,
|
|
1175
|
-
model: providerCfg.model,
|
|
1176
|
-
inputTokens: totalInputTokens,
|
|
1177
|
-
outputTokens: totalOutputTokens,
|
|
1178
|
-
})
|
|
1179
|
-
|
|
1180
1233
|
// Extract text for trace summary
|
|
1181
1234
|
const textMessageFinal = opts.rawUserMessage || (typeof opts.userMessage === "string"
|
|
1182
1235
|
? opts.userMessage
|
|
@@ -80,7 +80,8 @@ export async function searchCapabilities(
|
|
|
80
80
|
const k = opts.k ?? 10;
|
|
81
81
|
const types = opts.types?.length ? opts.types : undefined;
|
|
82
82
|
const trimmed = query.trim();
|
|
83
|
-
|
|
83
|
+
// hive-db >= 0.4 rejects k <= 0 instead of returning no hits.
|
|
84
|
+
if (!trimmed || k <= 0) return [];
|
|
84
85
|
|
|
85
86
|
const startTime = performance.now();
|
|
86
87
|
const db = await getHiveDb();
|
|
@@ -39,6 +39,10 @@ const KEEP_LAST_N_MESSAGES = 5 // always keep most recent N messages
|
|
|
39
39
|
const TOOL_RESULT_MAX_CHARS = 200 // max chars for old tool results after clearing
|
|
40
40
|
const MAX_TRANSCRIPT_MSGS = 30 // cap messages sent to summarizer (avoids OOM on small models)
|
|
41
41
|
const MAX_MSG_CHARS = 300 // chars per message in transcript
|
|
42
|
+
// Compaction runs before the turn and blocks it. A local model on CPU took
|
|
43
|
+
// minutes here; past this bound the turn goes on uncompacted — the context
|
|
44
|
+
// compiler already trims history to the window, so nothing overflows.
|
|
45
|
+
const COMPACTION_TIMEOUT_MS = 60_000
|
|
42
46
|
|
|
43
47
|
/**
|
|
44
48
|
* Check if compaction is needed and run it if so.
|
|
@@ -46,14 +50,18 @@ const MAX_MSG_CHARS = 300 // chars per message in transcript
|
|
|
46
50
|
*/
|
|
47
51
|
export async function maybeCompact(
|
|
48
52
|
threadId: string,
|
|
49
|
-
notify?: { channel: string; userId: string }
|
|
53
|
+
notify?: { channel: string; userId: string },
|
|
54
|
+
/** The window the provider really reads (resolveProviderConfig); overrides the model row. */
|
|
55
|
+
contextWindow?: number,
|
|
56
|
+
/** The turn's abort signal: cancelling the turn also stops its compaction. */
|
|
57
|
+
signal?: AbortSignal,
|
|
50
58
|
): Promise<void> {
|
|
51
59
|
try {
|
|
52
60
|
const totalTokens = await getTotalTokens(threadId)
|
|
53
61
|
|
|
54
62
|
// Use model's context window if available, otherwise use default
|
|
55
|
-
let effectiveThreshold = COMPACT_TOKEN_THRESHOLD
|
|
56
|
-
try {
|
|
63
|
+
let effectiveThreshold = contextWindow ? Math.floor(contextWindow * 0.25) : COMPACT_TOKEN_THRESHOLD
|
|
64
|
+
if (!contextWindow) try {
|
|
57
65
|
const agentsCol = await col<AgentDoc>("agents")
|
|
58
66
|
const coordinators = await agentsCol.findBy("role", "coordinator", { limit: 1 })
|
|
59
67
|
const modelId = fromIndexable(coordinators[0]?.doc.model_id ?? null)
|
|
@@ -78,7 +86,8 @@ export async function maybeCompact(
|
|
|
78
86
|
if (summary && summary.last_message_id > totalMessages - KEEP_LAST_N_MESSAGES) return
|
|
79
87
|
|
|
80
88
|
log.info(`[compaction] Compacting thread=${threadId} tokens=${totalTokens}`)
|
|
81
|
-
|
|
89
|
+
const timeout = AbortSignal.timeout(COMPACTION_TIMEOUT_MS)
|
|
90
|
+
await compactThread(threadId, notify, signal ? AbortSignal.any([signal, timeout]) : timeout)
|
|
82
91
|
} catch (err) {
|
|
83
92
|
log.warn("[compaction] Error during compaction check:", err)
|
|
84
93
|
}
|
|
@@ -118,9 +127,10 @@ export function renderTranscript(rows: StoredMessage[], maxMsgChars = MAX_MSG_CH
|
|
|
118
127
|
/**
|
|
119
128
|
* Compress a thread's history into a summary.
|
|
120
129
|
*/
|
|
121
|
-
async function compactThread(
|
|
130
|
+
export async function compactThread(
|
|
122
131
|
threadId: string,
|
|
123
|
-
notify?: { channel: string; userId: string }
|
|
132
|
+
notify?: { channel: string; userId: string },
|
|
133
|
+
signal?: AbortSignal,
|
|
124
134
|
): Promise<void> {
|
|
125
135
|
const allMessages = await getHistory(threadId)
|
|
126
136
|
if (allMessages.length <= KEEP_LAST_N_MESSAGES) return
|
|
@@ -150,6 +160,7 @@ async function compactThread(
|
|
|
150
160
|
|
|
151
161
|
const summaryResponse = await callLLM({
|
|
152
162
|
...providerCfg,
|
|
163
|
+
signal,
|
|
153
164
|
messages: [
|
|
154
165
|
{
|
|
155
166
|
role: "system",
|
|
@@ -191,7 +202,8 @@ async function compactThread(
|
|
|
191
202
|
await sendToUserChannel(
|
|
192
203
|
notify.channel,
|
|
193
204
|
notify.userId,
|
|
194
|
-
`🗜️ Resumí ${toSummarize.length} mensajes anteriores para mantener el contexto limpio
|
|
205
|
+
`🗜️ Resumí ${toSummarize.length} mensajes anteriores para mantener el contexto limpio.`,
|
|
206
|
+
{ threadId }
|
|
195
207
|
)
|
|
196
208
|
} catch {
|
|
197
209
|
// Non-critical — don't break the flow if notification fails
|