@johpaz/hive-agents 0.0.45 → 1.0.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/LICENSE +21 -0
- package/README.md +119 -852
- package/dist/hive.js +59290 -58797
- package/dist/tool-worker.js +220 -925
- package/dist/ui/assets/A2UIPage-D4nUFe5q.js +8 -0
- package/dist/ui/assets/AgentCreateForm-g1mQnIoJ.js +1 -0
- package/dist/ui/assets/AgentDetailPage-C3XkU4Ll.js +1 -0
- package/dist/ui/assets/AgentNewPage-CEkLeA79.js +1 -0
- package/dist/ui/assets/AgentsPage-CNA778Eo.js +10 -0
- package/dist/ui/assets/ApiClientPage-t5DpKhmA.js +3 -0
- package/dist/ui/assets/ChannelsPage-yY6t0YTU.js +8 -0
- package/dist/ui/assets/DashboardPage-BSeNSYg5.js +6 -0
- package/dist/ui/assets/{LoginPage-BTxJdFVG.js → LoginPage-eT5zDRDa.js} +1 -1
- package/dist/ui/assets/{LogsPage-DVV2eHbh.js → LogsPage-Gczzzsdh.js} +1 -1
- package/dist/ui/assets/MeetingPage-Bu4aMMNR.js +1 -0
- package/dist/ui/assets/ModelSelector-nNOrW3te.js +1 -0
- package/dist/ui/assets/{NotFound-BIUDlIXU.js → NotFound-Bpr12V51.js} +1 -1
- package/dist/ui/assets/Office3DPage-B_iXEbyv.js +4614 -0
- package/dist/ui/assets/Office3DPage-C3SIzd2H.css +1 -0
- package/dist/ui/assets/ProvidersPage-BupHs5yO.js +1 -0
- package/dist/ui/assets/{RecoverPage-7YDQysBL.js → RecoverPage-DMqSasKk.js} +1 -1
- package/dist/ui/assets/SettingsPage-B6FTSkOn.js +9 -0
- package/dist/ui/assets/SetupPage-DhcRbGgg.js +1 -0
- package/dist/ui/assets/WebChatPage-CWXjW4Hn.js +29 -0
- package/dist/ui/assets/{activity-c3pNngT_.js → activity-CQuPevhB.js} +1 -1
- package/dist/ui/assets/agentCapabilities-CDC6y91E.js +1 -0
- package/dist/ui/assets/alert-CQlRq6sv.js +1 -0
- package/dist/ui/assets/arrow-left-0EBE7nsF.js +1 -0
- package/dist/ui/assets/arrow-right-5QIaph-z.js +1 -0
- package/dist/ui/assets/arrow-up-right-DQQCY007.js +1 -0
- package/dist/ui/assets/badge-DKGZbVZJ.js +1 -0
- package/dist/ui/assets/{calendar-B-KZ9RQO.js → calendar-Be23hQGc.js} +1 -1
- package/dist/ui/assets/{card-CNf6BS2e.js → card-D3Nw3kh3.js} +1 -1
- package/dist/ui/assets/check-Dp6tzwax.js +1 -0
- package/dist/ui/assets/chevron-down-33N886NY.js +1 -0
- package/dist/ui/assets/chevron-left-C6itJXh3.js +1 -0
- package/dist/ui/assets/chevron-right-CFodBS-b.js +1 -0
- package/dist/ui/assets/chevron-up-BvSmyBEs.js +1 -0
- package/dist/ui/assets/{circle-alert-KuAm2FWh.js → circle-alert-BDVHxmAz.js} +1 -1
- package/dist/ui/assets/circle-check-BJWNbLuF.js +1 -0
- package/dist/ui/assets/{circle-x-DjLkFDO8.js → circle-x-Cb2Yer4s.js} +1 -1
- package/dist/ui/assets/{copy-Bu5d7C-0.js → copy-33tZrzc9.js} +1 -1
- package/dist/ui/assets/{dialog-Jk4bieO4.js → dialog-KOZKWbib.js} +1 -1
- package/dist/ui/assets/dist-CD_qfA30.js +1 -0
- package/dist/ui/assets/{download-Cjbk4Rek.js → download-CiQqqXyz.js} +1 -1
- package/dist/ui/assets/earth-DCvN7ynm.js +1 -0
- package/dist/ui/assets/ellipsis-vertical-BybFZDk2.js +1 -0
- package/dist/ui/assets/{external-link-6sTlRDUR.js → external-link-0iNNBvZm.js} +1 -1
- package/dist/ui/assets/{eye-Df8o0tkC.js → eye-C8sKSSkg.js} +1 -1
- package/dist/ui/assets/{file-text-lnxnjBp0.js → file-text-DO8jqiJK.js} +1 -1
- package/dist/ui/assets/{gateway-url-DwzPmoc8.js → gateway-url-BlnabM5e.js} +1 -1
- package/dist/ui/assets/gauge-BRGwuN8G.js +1 -0
- package/dist/ui/assets/{history-CAF_R34_.js → history-BtTD1kDo.js} +1 -1
- package/dist/ui/assets/index-Bejlp-R1.js +116 -0
- package/dist/ui/assets/index-XoTT41Hr.css +2 -0
- package/dist/ui/assets/{info-WjromB4Y.js → info-mpk1tsNC.js} +1 -1
- package/dist/ui/assets/key-CoQ0qtXt.js +1 -0
- package/dist/ui/assets/label-k0jYxoWW.js +1 -0
- package/dist/ui/assets/loader-circle-BhqRN2nO.js +1 -0
- package/dist/ui/assets/lock-open-Cd2aqwOd.js +1 -0
- package/dist/ui/assets/mail-BG0RYSkL.js +1 -0
- package/dist/ui/assets/{pause-VqeUmp2Z.js → pause-Cme88_9s.js} +1 -1
- package/dist/ui/assets/pencil-f1nJ1xhs.js +1 -0
- package/dist/ui/assets/play-CfYDHD6h.js +1 -0
- package/dist/ui/assets/plus-C5BxJeOX.js +1 -0
- package/dist/ui/assets/progress-DrI2UDu-.js +1 -0
- package/dist/ui/assets/radio-B5SpKJ-J.js +1 -0
- package/dist/ui/assets/{refresh-cw-CCzDCAuz.js → refresh-cw-CroGQY62.js} +1 -1
- package/dist/ui/assets/scroll-area-CfHn94Vb.js +1 -0
- package/dist/ui/assets/search-rfBcmohK.js +1 -0
- package/dist/ui/assets/select-BhbW0stK.js +1 -0
- package/dist/ui/assets/{send-BPk9XbIq.js → send-D6whYpw-.js} +1 -1
- package/dist/ui/assets/{settings-BGfrZ_zM.js → settings-BX6q3MGB.js} +1 -1
- package/dist/ui/assets/{shield-CxhcUT39.js → shield-BnGyu1xf.js} +1 -1
- package/dist/ui/assets/slider-CmE_z1Ii.js +1 -0
- package/dist/ui/assets/{sparkles-BhwlS1pc.js → sparkles-BcaOs_Jk.js} +1 -1
- package/dist/ui/assets/{square-DMNWw4Hi.js → square-ju5H8nrT.js} +1 -1
- package/dist/ui/assets/switch-DXcELPsM.js +1 -0
- package/dist/ui/assets/tabs-CxiybXcw.js +1 -0
- package/dist/ui/assets/terminal-Bjfu-TkS.js +1 -0
- package/dist/ui/assets/{textarea-B6Z1Zc6W.js → textarea-rp6vsOZl.js} +1 -1
- package/dist/ui/assets/{trash-2-xD2o4SgX.js → trash-2-DjQXac_0.js} +1 -1
- package/dist/ui/assets/{triangle-alert-pVIJGjga.js → triangle-alert-B04mgMcg.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-BnC4jLE-.js → useHiveAgentsModelLoad-DT5-4CCj.js} +1 -1
- package/dist/ui/assets/useOfficeModel-Cy7cAyEn.js +1 -0
- package/dist/ui/assets/useProviders-DSX7eVsz.js +1 -0
- package/dist/ui/assets/utils-Dyb7SC2_.js +1 -0
- package/dist/ui/assets/vendor-charts-K3xcRl0X.js +60 -0
- package/dist/ui/assets/{vendor-query-DsWPbQdG.js → vendor-query-Dj8xYhQD.js} +1 -1
- package/dist/ui/assets/vendor-radix-D0s_k6Gp.js +63 -0
- package/dist/ui/assets/vendor-react-CPJEWbIG.js +1 -0
- package/dist/ui/assets/{vendor-router-gqiZ7xhx.js → vendor-router-zpB-76nT.js} +1 -1
- package/dist/ui/assets/volume-x-qnVxkRSM.js +1 -0
- package/dist/ui/assets/wifi-BA1m2dGO.js +1 -0
- package/dist/ui/assets/{zap-B4RaNNO5.js → zap-DT7cM7YS.js} +1 -1
- package/dist/ui/index.html +10 -9
- package/package.json +8 -9
- package/packages/cli/src/adapters/config.ts +1 -80
- package/packages/cli/src/adapters/factory.ts +0 -45
- package/packages/cli/src/adapters/index.ts +0 -8
- package/packages/cli/src/commands/doctor.ts +45 -1
- package/packages/cli/src/commands/gateway.ts +2 -9
- package/packages/cli/src/index.ts +9 -11
- package/packages/core/src/agent/acceptance-verifier.ts +300 -0
- package/packages/core/src/agent/agent-catalog.ts +384 -0
- package/packages/core/src/agent/agent-loop.ts +185 -28
- package/packages/core/src/agent/capability-search.ts +5 -5
- package/packages/core/src/agent/catalog-selector.ts +104 -0
- package/packages/core/src/agent/compaction.ts +36 -41
- package/packages/core/src/agent/context-compiler.ts +182 -62
- package/packages/core/src/agent/conversation-store.ts +56 -3
- package/packages/core/src/agent/curator.ts +129 -34
- package/packages/core/src/agent/delegation-runtime.ts +248 -0
- package/packages/core/src/agent/index.ts +17 -0
- package/packages/core/src/agent/llm-providers/hiveagents.ts +1 -1
- package/packages/core/src/agent/llm-providers/interface.ts +3 -3
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/minimal-loadout.ts +46 -0
- package/packages/core/src/agent/playbook-selector.ts +1 -1
- package/packages/core/src/agent/prompt-builder.ts +4 -0
- package/packages/core/src/agent/proof-packet.ts +15 -1
- package/packages/core/src/agent/providers/index.ts +8 -3
- package/packages/core/src/agent/routing-intent.ts +22 -0
- package/packages/core/src/agent/run-store.ts +24 -3
- package/packages/core/src/agent/service.ts +2 -2
- package/packages/core/src/agent/skill-selector.ts +12 -31
- package/packages/core/src/agent/tool-selector.ts +36 -35
- package/packages/core/src/agent/tracer.ts +5 -1
- package/packages/core/src/artifacts/store.ts +162 -0
- package/packages/core/src/canvas/canvas-manager.ts +5 -234
- package/packages/core/src/canvas/emitter.ts +165 -69
- package/packages/core/src/canvas/index.ts +0 -2
- package/packages/core/src/channels/base.ts +3 -1
- package/packages/core/src/channels/webchat.ts +4 -8
- package/packages/core/src/config/loader.ts +0 -22
- package/packages/core/src/events/agent-bus.ts +0 -31
- package/packages/core/src/events/narration.ts +82 -0
- package/packages/core/src/gateway/channel-notify.ts +34 -5
- package/packages/core/src/gateway/delegation-groups.ts +245 -0
- package/packages/core/src/gateway/delegation-notify.ts +103 -0
- package/packages/core/src/gateway/durable-queue.ts +33 -2
- package/packages/core/src/gateway/helpers/index.ts +2 -2
- package/packages/core/src/gateway/helpers/narration.ts +12 -7
- package/packages/core/src/gateway/helpers/redact.ts +1 -1
- package/packages/core/src/gateway/initializer.ts +15 -13
- package/packages/core/src/gateway/job-executors.ts +232 -101
- package/packages/core/src/gateway/lane-queue.ts +1 -1
- package/packages/core/src/gateway/notification-inbox.ts +57 -0
- package/packages/core/src/gateway/resolver.ts +1 -23
- package/packages/core/src/gateway/routes/agents.ts +91 -1
- package/packages/core/src/gateway/routes/auth.ts +21 -42
- package/packages/core/src/gateway/routes/chat.ts +6 -6
- package/packages/core/src/gateway/routes/cron-api.ts +0 -4
- package/packages/core/src/gateway/routes/mcp.ts +0 -63
- package/packages/core/src/gateway/routes/meeting.ts +245 -0
- package/packages/core/src/gateway/routes/providers.ts +1 -0
- package/packages/core/src/gateway/routes/setup.ts +29 -24
- package/packages/core/src/gateway/routes/skills.ts +2 -2
- package/packages/core/src/gateway/routes/system.ts +23 -5
- package/packages/core/src/gateway/routes/users.ts +24 -1
- package/packages/core/src/gateway/server.ts +153 -117
- package/packages/core/src/gateway/session.ts +6 -4
- package/packages/core/src/gateway/slash-commands.ts +7 -6
- package/packages/core/src/gateway/webchat-turn.ts +34 -8
- package/packages/core/src/index.ts +3 -0
- package/packages/core/src/mcp/hot-reload.ts +14 -7
- package/packages/core/src/mcp/singleton.ts +0 -3
- package/packages/core/src/mcp/tool-sync.ts +2 -2
- package/packages/core/src/resilience/retry.ts +1 -1
- package/packages/core/src/scheduler/CronScheduler.ts +3 -1
- package/packages/core/src/scheduler/integration.ts +1 -1
- package/packages/core/src/storage/bootstrap.ts +25 -5
- package/packages/core/src/storage/collections.ts +201 -27
- package/packages/core/src/storage/onboarding.ts +147 -32
- package/packages/core/src/storage/reconcile.ts +2 -5
- package/packages/core/src/storage/seed.ts +202 -38
- package/packages/core/src/storage/usage.ts +0 -9
- package/packages/core/src/storage/user-email.ts +11 -0
- package/packages/core/src/tool-runtime/index.ts +69 -23
- package/packages/core/src/tool-runtime/worker-tools.ts +4 -2
- package/packages/core/src/{canvas/a2ui-tools.ts → tools/a2ui/index.ts} +17 -8
- package/packages/core/src/tools/agents/get-available-models.ts +11 -3
- package/packages/core/src/tools/agents/index.ts +404 -86
- package/packages/core/src/tools/core/index.ts +28 -10
- package/packages/core/src/tools/cron/index.ts +1 -6
- package/packages/core/src/tools/index.ts +17 -45
- package/packages/core/src/tools/types.ts +1 -1
- package/packages/core/src/tools/web/artifact-inspect.ts +23 -0
- package/packages/core/src/tools/web/browser-screenshot.ts +26 -5
- package/packages/core/src/tools/web/index.ts +3 -0
- package/packages/core/src/utils/logger.ts +58 -30
- package/packages/core/src/utils/toon.ts +0 -20
- package/packages/mcp/src/manager.ts +8 -7
- package/packages/mcp/src/transports/sse.ts +0 -4
- package/packages/mcp/src/transports/websocket.ts +0 -6
- package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_dashboard/SKILL.md +4 -4
- package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_form/SKILL.md +4 -4
- package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_interactive/SKILL.md +5 -5
- package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +26 -0
- package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +24 -18
- package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +47 -148
- package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +9 -10
- package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +1 -1
- package/packages/skills/src/bundled/cli/software_engineering/SKILL.md +23 -0
- package/packages/skills/src/bundled/cron_manager/SKILL.md +2 -2
- package/packages/skills/src/bundled/cron_reminder/SKILL.md +7 -7
- package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +11 -10
- package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +29 -35
- package/packages/skills/src/bundled/filesystem/workspace_file_operator/SKILL.md +22 -0
- package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +5 -4
- package/packages/skills/src/bundled-data.generated.ts +155 -720
- package/dist/ui/assets/AgentCreateForm-DzaIT-dA.js +0 -1
- package/dist/ui/assets/AgentDetailPage-DgqcJceY.js +0 -1
- package/dist/ui/assets/AgentNewPage-CNSpoOSA.js +0 -1
- package/dist/ui/assets/AgentsPage-BMUJzTD6.js +0 -10
- package/dist/ui/assets/ApiClientPage-Cum_a_3j.js +0 -3
- package/dist/ui/assets/CanvasPage-o6oCP6uq.js +0 -33
- package/dist/ui/assets/ChannelsPage-WrB0zwLq.js +0 -8
- package/dist/ui/assets/DashboardPage-BCd6kNw0.js +0 -6
- package/dist/ui/assets/MeetingPage-BULIAWzq.js +0 -1
- package/dist/ui/assets/ModelSelector-BMYOChYb.js +0 -1
- package/dist/ui/assets/ProvidersPage-BVN5UZrI.js +0 -1
- package/dist/ui/assets/SettingsPage-CYmpFfDn.js +0 -9
- package/dist/ui/assets/SetupPage-Dnmb1Lbv.js +0 -1
- package/dist/ui/assets/WebChatPage-DmmdFhIC.js +0 -16
- package/dist/ui/assets/accordion-CnLzKNHK.js +0 -1
- package/dist/ui/assets/alert-B9J6KHmt.js +0 -1
- package/dist/ui/assets/alert-dialog-KcYQWcJ6.js +0 -1
- package/dist/ui/assets/arrow-left-CBcbX5EZ.js +0 -1
- package/dist/ui/assets/badge-88dRb4M8.js +0 -1
- package/dist/ui/assets/bell-8BqRYmzf.js +0 -1
- package/dist/ui/assets/chevron-down-DIosfU_U.js +0 -1
- package/dist/ui/assets/chevron-left-D4U-5A27.js +0 -1
- package/dist/ui/assets/chevron-right-CR4Skrf3.js +0 -1
- package/dist/ui/assets/chevron-up-CI-W21Fy.js +0 -1
- package/dist/ui/assets/circle-check-6Ard1-2z.js +0 -1
- package/dist/ui/assets/dropdown-menu-DDiaHg5y.js +0 -1
- package/dist/ui/assets/es-4I-joeZz.js +0 -1
- package/dist/ui/assets/folder-open-DJBLDFjv.js +0 -1
- package/dist/ui/assets/format-DsLPBxvt.js +0 -1
- package/dist/ui/assets/gauge-B8Tj43rC.js +0 -1
- package/dist/ui/assets/hexagon-6L79pgVK.js +0 -1
- package/dist/ui/assets/index-BmwTAwOF.css +0 -2
- package/dist/ui/assets/index-Cyw7L0Li.js +0 -116
- package/dist/ui/assets/key-DyKOoQh5.js +0 -1
- package/dist/ui/assets/label-B_15zZlR.js +0 -1
- package/dist/ui/assets/loader-circle-BmBOgYze.js +0 -1
- package/dist/ui/assets/lock-BS6OLXPv.js +0 -1
- package/dist/ui/assets/play-zJpWuhrr.js +0 -1
- package/dist/ui/assets/plus-BZQX26Dr.js +0 -1
- package/dist/ui/assets/progress-D5c-Eilm.js +0 -1
- package/dist/ui/assets/scroll-area-CihOx0cb.js +0 -1
- package/dist/ui/assets/search-DzDptO9s.js +0 -1
- package/dist/ui/assets/select-BQCOjM2j.js +0 -1
- package/dist/ui/assets/slider-bcUiUfx0.js +0 -14
- package/dist/ui/assets/switch-BR30E4ej.js +0 -1
- package/dist/ui/assets/table-B3aGEaVp.js +0 -1
- package/dist/ui/assets/tabs-LQidMKRS.js +0 -1
- package/dist/ui/assets/terminal--7G943As.js +0 -1
- package/dist/ui/assets/useProviders-C1xVKLxB.js +0 -1
- package/dist/ui/assets/utils-3pnRFmFe.js +0 -1
- package/dist/ui/assets/vendor-charts-Bu2lyBKP.js +0 -65
- package/dist/ui/assets/vendor-radix-D6rA7xKY.js +0 -63
- package/dist/ui/assets/vendor-react-BU5iQU4f.js +0 -1
- package/dist/ui/assets/volume-2-BekVQl6P.js +0 -1
- package/packages/core/src/agent/context-guard.ts +0 -91
- package/packages/core/src/agent/hooks.ts +0 -166
- package/packages/core/src/agent/providers.ts +0 -1
- package/packages/core/src/auth/auth.ts +0 -111
- package/packages/core/src/auth/index.ts +0 -1
- package/packages/core/src/canvas/canvas-tools.ts +0 -448
- package/packages/core/src/gateway/router.ts +0 -126
- package/packages/core/src/scheduler/dag/AgentExecutor.ts +0 -53
- package/packages/core/src/scheduler/dag/DAGScheduler.ts +0 -250
- package/packages/core/src/scheduler/dag/EventBridge.ts +0 -122
- package/packages/core/src/scheduler/dag/TaskGraph.ts +0 -192
- package/packages/core/src/scheduler/dag/TaskNode.ts +0 -97
- package/packages/core/src/scheduler/dag/TaskResult.ts +0 -22
- package/packages/core/src/scheduler/dag/errors.ts +0 -37
- package/packages/core/src/scheduler/dag/index.ts +0 -26
- package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +0 -97
- package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +0 -21
- package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +0 -46
- package/packages/core/src/scheduler/index.ts +0 -22
- package/packages/core/src/scheduler/task-driver.ts +0 -216
- package/packages/core/src/tools/canvas/index.ts +0 -420
- package/packages/core/src/tools/meeting/index.ts +0 -336
- package/packages/core/src/tools/projects/index.ts +0 -348
- package/packages/core/src/tools/voice/index.ts +0 -104
- package/packages/core/src/utils/index.ts +0 -5
- package/packages/skills/src/bundled/agents/code_delegator/SKILL.md +0 -156
- package/packages/skills/src/bundled/canvas/canvas_dashboard/SKILL.md +0 -146
- package/packages/skills/src/bundled/canvas/canvas_interact/SKILL.md +0 -148
- package/packages/skills/src/bundled/canvas/canvas_report/SKILL.md +0 -146
- package/packages/skills/src/bundled/meeting/meeting_transcription/SKILL.md +0 -213
- package/packages/skills/src/bundled/voice/voice_assistant/SKILL.md +0 -174
- package/packages/skills/src/bundled/voice/voice_input/SKILL.md +0 -146
- package/packages/skills/src/bundled/voice/voice_output/SKILL.md +0 -151
|
@@ -17,7 +17,7 @@ import { logger } from "../utils/logger"
|
|
|
17
17
|
import { col, fromIndexable } from "../storage/hive"
|
|
18
18
|
import { getHiveDb } from "../storage/hivedb"
|
|
19
19
|
import type { HiveDB, EventInput } from "@johpaz/hive-db"
|
|
20
|
-
import type { AgentDoc } from "../storage/collections"
|
|
20
|
+
import type { AgentDoc, TurnSource } from "../storage/collections"
|
|
21
21
|
import { callLLM, resolveProviderConfig, getDefaultLLM, type LLMMessage } from "./llm-client"
|
|
22
22
|
import { addMessage } from "./conversation-store"
|
|
23
23
|
import { saveTrace, recordLLMUsage } from "./tracer"
|
|
@@ -46,6 +46,7 @@ import {
|
|
|
46
46
|
stopLeaseRenewal,
|
|
47
47
|
type RunCheckpointState,
|
|
48
48
|
} from "./run-store"
|
|
49
|
+
import { publishNarration } from "../events/narration"
|
|
49
50
|
|
|
50
51
|
const log = logger.child("agent-loop")
|
|
51
52
|
|
|
@@ -61,6 +62,38 @@ export class LLMCallTimeoutError extends Error {
|
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
64
|
|
|
65
|
+
export class AgentSynthesisError extends Error {
|
|
66
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
67
|
+
super(message, options)
|
|
68
|
+
this.name = "AgentSynthesisError"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Produce a terminal response with one bounded retry. Empty model output is a
|
|
74
|
+
* failure: callers must never turn an unknown outcome into a success message.
|
|
75
|
+
*/
|
|
76
|
+
export async function synthesizeFinalResponse(
|
|
77
|
+
operation: () => Promise<string | null | undefined>,
|
|
78
|
+
): Promise<string> {
|
|
79
|
+
let lastError: unknown
|
|
80
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
81
|
+
try {
|
|
82
|
+
const content = (await operation())?.trim()
|
|
83
|
+
if (content) return content
|
|
84
|
+
lastError = new Error("The model returned an empty synthesis")
|
|
85
|
+
} catch (err) {
|
|
86
|
+
lastError = err
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const detail = lastError instanceof Error ? lastError.message : String(lastError)
|
|
91
|
+
throw new AgentSynthesisError(
|
|
92
|
+
`No se pudo generar la respuesta final del agente después de 2 intentos: ${detail}`,
|
|
93
|
+
{ cause: lastError },
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
|
|
64
97
|
/** Bounds a single async operation to its own timeout window, independent of any caller. */
|
|
65
98
|
export async function withTimeout<T>(op: () => Promise<T>, timeoutMs: number): Promise<T> {
|
|
66
99
|
let timer: ReturnType<typeof setTimeout>
|
|
@@ -132,6 +165,12 @@ export interface AgentLoopOptions {
|
|
|
132
165
|
extraTools?: any[]
|
|
133
166
|
/** Run ID for an existing AgentRun — enables resume from checkpoint */
|
|
134
167
|
runId?: string
|
|
168
|
+
/** Stable originating chat-turn id used to group delegated work. */
|
|
169
|
+
turnId?: string
|
|
170
|
+
/** Durable task id when executing a delegated worker. */
|
|
171
|
+
taskId?: string
|
|
172
|
+
/** External routing/session id for progress delivery. */
|
|
173
|
+
sessionId?: string
|
|
135
174
|
/** Whether to resume from a previously saved checkpoint */
|
|
136
175
|
resume?: boolean
|
|
137
176
|
/** Run budget — overrides agent.max_iterations when set */
|
|
@@ -149,6 +188,16 @@ export interface AgentLoopOptions {
|
|
|
149
188
|
durable?: boolean
|
|
150
189
|
/** Kind of run for the AgentRun record */
|
|
151
190
|
runKind?: "chat" | "worker" | "goal" | "cron" | "project"
|
|
191
|
+
/**
|
|
192
|
+
* Provenance to persist the trigger message with (default "message"). The
|
|
193
|
+
* trigger message is always persisted with role:"user" — including
|
|
194
|
+
* system-originated turns (async-delegation fan-in/fan-out notices from
|
|
195
|
+
* delegation-groups.ts and delegation-notify.ts), since AgentLoop.stream()
|
|
196
|
+
* extracts the last role:"user" message as the turn's trigger content.
|
|
197
|
+
* `historySource` records where it actually came from so history/compaction/
|
|
198
|
+
* LLM serialization can recognize and frame it without a second role.
|
|
199
|
+
*/
|
|
200
|
+
historySource?: TurnSource
|
|
152
201
|
}
|
|
153
202
|
|
|
154
203
|
export type { StepEvent as AgentStepEvent }
|
|
@@ -243,8 +292,14 @@ export async function* runAgent(
|
|
|
243
292
|
|
|
244
293
|
// Store the user message in conversation history
|
|
245
294
|
if (!opts.isolated) {
|
|
246
|
-
// If userMessage is multimodal, addMessage extracts text for history storage
|
|
247
|
-
|
|
295
|
+
// If userMessage is multimodal, addMessage extracts text for history storage.
|
|
296
|
+
// historySource records provenance; system-originated turns (delegation
|
|
297
|
+
// fan-in) persist as role:"user" like everything else and stay off the
|
|
298
|
+
// visible transcript purely because their source is internal.
|
|
299
|
+
await addMessage(opts.threadId, "user", opts.userMessage, {
|
|
300
|
+
channel: opts.channel,
|
|
301
|
+
source: opts.historySource ?? "message",
|
|
302
|
+
})
|
|
248
303
|
// Run compaction if conversation history is getting large
|
|
249
304
|
await maybeCompact(
|
|
250
305
|
opts.threadId,
|
|
@@ -280,7 +335,12 @@ export async function* runAgent(
|
|
|
280
335
|
}
|
|
281
336
|
}
|
|
282
337
|
|
|
283
|
-
|
|
338
|
+
// Compose rather than discard: an override must still carry the
|
|
339
|
+
// conversation summary context-compiler folded in, or a compacted thread
|
|
340
|
+
// silently loses it whenever a caller supplies systemPromptOverride.
|
|
341
|
+
const systemPrompt = opts.systemPromptOverride
|
|
342
|
+
? opts.systemPromptOverride + ctx.conversationSummarySection
|
|
343
|
+
: ctx.systemPrompt
|
|
284
344
|
|
|
285
345
|
// Build initial messages array for the model
|
|
286
346
|
let messages: LLMMessage[] = [
|
|
@@ -391,6 +451,9 @@ export async function* runAgent(
|
|
|
391
451
|
|
|
392
452
|
iterations++
|
|
393
453
|
|
|
454
|
+
const delegationGroupAtCall = opts.turnId && !opts.isolated
|
|
455
|
+
? await import("../gateway/delegation-groups").then((mod) => mod.getDelegationGroup(opts.turnId!))
|
|
456
|
+
: null
|
|
394
457
|
let streamedThisCall = false
|
|
395
458
|
let response: Awaited<ReturnType<typeof callLLM>>
|
|
396
459
|
try {
|
|
@@ -399,7 +462,7 @@ export async function* runAgent(
|
|
|
399
462
|
messages: clearOldToolResults(messages) as LLMMessage[],
|
|
400
463
|
tools: ctx.tools.length > 0 ? ctx.tools : undefined,
|
|
401
464
|
signal: opts.signal,
|
|
402
|
-
onToken: opts.onToken
|
|
465
|
+
onToken: opts.onToken && !delegationGroupAtCall
|
|
403
466
|
? (token: string) => {
|
|
404
467
|
streamedThisCall = true
|
|
405
468
|
opts.onToken?.(token)
|
|
@@ -419,6 +482,13 @@ export async function* runAgent(
|
|
|
419
482
|
throw err
|
|
420
483
|
}
|
|
421
484
|
|
|
485
|
+
if (
|
|
486
|
+
delegationGroupAtCall &&
|
|
487
|
+
(!response.tool_calls?.length || response.stop_reason !== "tool_calls")
|
|
488
|
+
) {
|
|
489
|
+
response.content = ""
|
|
490
|
+
}
|
|
491
|
+
|
|
422
492
|
// Accumulate usage
|
|
423
493
|
if (response.usage) {
|
|
424
494
|
totalInputTokens += response.usage.input_tokens
|
|
@@ -495,6 +565,21 @@ export async function* runAgent(
|
|
|
495
565
|
message: `Calling tool: \`${toolName}\``,
|
|
496
566
|
})
|
|
497
567
|
}
|
|
568
|
+
if (opts.turnId) {
|
|
569
|
+
await publishNarration({
|
|
570
|
+
turnId: opts.turnId,
|
|
571
|
+
threadId: opts.threadId,
|
|
572
|
+
channel: opts.channel,
|
|
573
|
+
userId: opts.userId,
|
|
574
|
+
sessionId: opts.sessionId,
|
|
575
|
+
agentId: opts.agentId,
|
|
576
|
+
agentName,
|
|
577
|
+
kind: "tool_call",
|
|
578
|
+
status: "running",
|
|
579
|
+
label: `${agentName} llamó ${toolName}`,
|
|
580
|
+
dedupeKey: `tool_call:${iterations}:${tc.id}:${toolName}`,
|
|
581
|
+
})
|
|
582
|
+
}
|
|
498
583
|
}
|
|
499
584
|
|
|
500
585
|
const hiveConfig = loadConfig()
|
|
@@ -529,6 +614,15 @@ export async function* runAgent(
|
|
|
529
614
|
thread_id: opts.threadId,
|
|
530
615
|
channel: opts.channel,
|
|
531
616
|
workspace: agent.workspace ?? null,
|
|
617
|
+
// Tools read this to know who's calling them (task_delegate's parent
|
|
618
|
+
// lookup, agent_create's parent_id, bus_publish's sender) — was
|
|
619
|
+
// missing entirely before, so config.configurable.agent_id was always
|
|
620
|
+
// undefined inside every tool execute().
|
|
621
|
+
agent_id: opts.agentId,
|
|
622
|
+
run_id: runId ?? opts.runId,
|
|
623
|
+
turn_id: opts.turnId,
|
|
624
|
+
task_id: opts.taskId,
|
|
625
|
+
session_id: opts.sessionId,
|
|
532
626
|
},
|
|
533
627
|
hiveConfig,
|
|
534
628
|
workerPool: hiveConfig.tools?.workerPool,
|
|
@@ -574,6 +668,7 @@ export async function* runAgent(
|
|
|
574
668
|
errorMessage: toolResultLLM.startsWith("[Tool Error]") ? toolResultLLM : null,
|
|
575
669
|
durationMs: toolMs,
|
|
576
670
|
causalStreamId,
|
|
671
|
+
catalogAgentId: agent.source === "catalog" ? agent.id : undefined,
|
|
577
672
|
})
|
|
578
673
|
|
|
579
674
|
// G9: record the tool call, caused by the decision that requested it.
|
|
@@ -596,11 +691,29 @@ export async function* runAgent(
|
|
|
596
691
|
}
|
|
597
692
|
|
|
598
693
|
// Emit tool chunk (TOON encoded for LLM)
|
|
599
|
-
yield { tools: { messages: [{ content: toolResultLLM, tool_call_id: tc.id }] } }
|
|
694
|
+
yield { tools: { messages: [{ content: toolResultLLM, tool_call_id: tc.id, name: toolName }] } }
|
|
600
695
|
|
|
601
696
|
if (opts.onStep) {
|
|
602
697
|
await opts.onStep({ type: "tool_result", message: toolResultLLM })
|
|
603
698
|
}
|
|
699
|
+
if (opts.turnId) {
|
|
700
|
+
await publishNarration({
|
|
701
|
+
turnId: opts.turnId,
|
|
702
|
+
threadId: opts.threadId,
|
|
703
|
+
channel: opts.channel,
|
|
704
|
+
userId: opts.userId,
|
|
705
|
+
sessionId: opts.sessionId,
|
|
706
|
+
agentId: opts.agentId,
|
|
707
|
+
agentName,
|
|
708
|
+
kind: "tool_result",
|
|
709
|
+
status: batchResult.ok ? "done" : "error",
|
|
710
|
+
label: batchResult.ok
|
|
711
|
+
? `${agentName} recibió el resultado de ${toolName}`
|
|
712
|
+
: `${agentName} recibió un error de ${toolName}`,
|
|
713
|
+
detail: batchResult.ok ? null : batchResult.error?.message ?? null,
|
|
714
|
+
dedupeKey: `tool_result:${iterations}:${tc.id}:${toolName}`,
|
|
715
|
+
})
|
|
716
|
+
}
|
|
604
717
|
|
|
605
718
|
// Add tool result to messages for next model call (in-memory only, NOT persisted to DB)
|
|
606
719
|
messages.push({
|
|
@@ -704,8 +817,11 @@ export async function* runAgent(
|
|
|
704
817
|
.map(s => `## Skill: ${s.name}\n${s.body}`)
|
|
705
818
|
.join("\n\n")
|
|
706
819
|
|
|
707
|
-
// Add skill instructions to system prompt
|
|
708
|
-
|
|
820
|
+
// Add skill instructions to system prompt. messages[0] is
|
|
821
|
+
// always the system prompt by construction — there is
|
|
822
|
+
// exactly one system message in the array (see its
|
|
823
|
+
// construction above), so index instead of scanning.
|
|
824
|
+
const systemMsg = messages[0]?.role === "system" ? messages[0] : undefined
|
|
709
825
|
if (systemMsg && typeof systemMsg.content === "string") {
|
|
710
826
|
// Check if we already added this skill
|
|
711
827
|
const existingSkillNames = new Set(
|
|
@@ -902,12 +1018,24 @@ export async function* runAgent(
|
|
|
902
1018
|
// The agent spent all iterations on tool calls and never produced a final message.
|
|
903
1019
|
// Make one extra call without tools so it summarizes what it did.
|
|
904
1020
|
if (!finalContent) {
|
|
1021
|
+
const pendingDelegation = opts.turnId && !opts.isolated
|
|
1022
|
+
? await import("../gateway/delegation-groups").then((mod) => mod.getDelegationGroup(opts.turnId!))
|
|
1023
|
+
: null
|
|
1024
|
+
if (pendingDelegation) {
|
|
1025
|
+
log.info(`[agent-loop] Suppressing terminal synthesis while delegation group ${opts.turnId} is pending`)
|
|
1026
|
+
finalContent = ""
|
|
1027
|
+
} else {
|
|
905
1028
|
log.info(`[agent-loop] Max iterations hit with no text response — requesting synthesis (isolated=${!!opts.isolated})`)
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
1029
|
+
messages.push({
|
|
1030
|
+
role: "user",
|
|
1031
|
+
content: "Basándote en lo que hiciste hasta ahora, responde al usuario con un resumen claro y estrictamente factual de lo completado, lo pendiente o los errores. No declares éxito sin evidencia. Sé conciso.",
|
|
1032
|
+
})
|
|
1033
|
+
let synthesisAttempt = 0
|
|
1034
|
+
finalContent = await synthesizeFinalResponse(async () => {
|
|
1035
|
+
synthesisAttempt++
|
|
1036
|
+
if (synthesisAttempt > 1) {
|
|
1037
|
+
log.warn("[agent-loop] Retrying terminal synthesis after an empty or failed response")
|
|
1038
|
+
}
|
|
911
1039
|
const synthesis = await callLLM({
|
|
912
1040
|
...providerCfg,
|
|
913
1041
|
messages: clearOldToolResults(messages) as LLMMessage[],
|
|
@@ -917,18 +1045,12 @@ export async function* runAgent(
|
|
|
917
1045
|
totalInputTokens += synthesis.usage.input_tokens
|
|
918
1046
|
totalOutputTokens += synthesis.usage.output_tokens
|
|
919
1047
|
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
log.warn(`[agent-loop] Synthesis call failed: ${(err as Error).message}`)
|
|
927
|
-
finalContent = "He completado las tareas solicitadas."
|
|
928
|
-
if (!opts.isolated) {
|
|
929
|
-
await addMessage(opts.threadId, "assistant", finalContent)
|
|
930
|
-
}
|
|
931
|
-
yield { agent: { messages: [{ content: finalContent }] } }
|
|
1048
|
+
return synthesis.content
|
|
1049
|
+
})
|
|
1050
|
+
if (!opts.isolated) {
|
|
1051
|
+
await addMessage(opts.threadId, "assistant", finalContent)
|
|
1052
|
+
}
|
|
1053
|
+
yield { agent: { messages: [{ content: finalContent }] } }
|
|
932
1054
|
}
|
|
933
1055
|
} else if (!finalEmitted) {
|
|
934
1056
|
// Internal break (stall, loop detected, stuck, timeout, abort) set finalContent
|
|
@@ -979,6 +1101,7 @@ export async function* runAgent(
|
|
|
979
1101
|
durationMs,
|
|
980
1102
|
tokensUsed: totalInputTokens + totalOutputTokens,
|
|
981
1103
|
causalStreamId,
|
|
1104
|
+
catalogAgentId: agent.source === "catalog" ? agent.id : undefined,
|
|
982
1105
|
})
|
|
983
1106
|
|
|
984
1107
|
log.info(
|
|
@@ -1047,7 +1170,7 @@ export async function* runAgent(
|
|
|
1047
1170
|
* Passing `runId` + `durable` links the run to an existing AgentRun so the
|
|
1048
1171
|
* worker checkpoints per round-trip and can resume mid-task after a crash.
|
|
1049
1172
|
*/
|
|
1050
|
-
export
|
|
1173
|
+
export interface IsolatedAgentOptions {
|
|
1051
1174
|
agentId: string
|
|
1052
1175
|
taskDescription: string | ContentPart[]
|
|
1053
1176
|
threadId: string
|
|
@@ -1056,8 +1179,18 @@ export async function runAgentIsolated(opts: {
|
|
|
1056
1179
|
resume?: boolean
|
|
1057
1180
|
durable?: boolean
|
|
1058
1181
|
signal?: AbortSignal
|
|
1059
|
-
|
|
1182
|
+
turnId?: string
|
|
1183
|
+
taskId?: string
|
|
1184
|
+
userId?: string
|
|
1185
|
+
channel?: string
|
|
1186
|
+
sessionId?: string
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
export async function runAgentIsolatedDetailed(
|
|
1190
|
+
opts: IsolatedAgentOptions,
|
|
1191
|
+
): Promise<{ content: string; toolEvidence: string[] }> {
|
|
1060
1192
|
let lastContent = ""
|
|
1193
|
+
const toolEvidence: string[] = []
|
|
1061
1194
|
for await (const chunk of runAgent({
|
|
1062
1195
|
agentId: opts.agentId,
|
|
1063
1196
|
userMessage: opts.taskDescription,
|
|
@@ -1069,12 +1202,29 @@ export async function runAgentIsolated(opts: {
|
|
|
1069
1202
|
resume: opts.resume,
|
|
1070
1203
|
durable: opts.durable,
|
|
1071
1204
|
signal: opts.signal,
|
|
1205
|
+
turnId: opts.turnId,
|
|
1206
|
+
taskId: opts.taskId,
|
|
1207
|
+
userId: opts.userId,
|
|
1208
|
+
channel: opts.channel,
|
|
1209
|
+
sessionId: opts.sessionId,
|
|
1072
1210
|
})) {
|
|
1073
1211
|
if (chunk.agent?.messages?.[0]?.content) {
|
|
1074
1212
|
lastContent = chunk.agent.messages[0].content
|
|
1075
1213
|
}
|
|
1214
|
+
for (const message of chunk.tools?.messages ?? []) {
|
|
1215
|
+
const raw = typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1216
|
+
const safe = raw
|
|
1217
|
+
.replace(/data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+/gi, "[REDACTED_BINARY]")
|
|
1218
|
+
.replace(/[A-Za-z0-9+/]{1000,}={0,2}/g, "[REDACTED_BINARY]")
|
|
1219
|
+
toolEvidence.push(`${message.name ?? "tool"}: ${safe.slice(0, 4000)}`)
|
|
1220
|
+
if (toolEvidence.length > 8) toolEvidence.shift()
|
|
1221
|
+
}
|
|
1076
1222
|
}
|
|
1077
|
-
return lastContent
|
|
1223
|
+
return { content: lastContent, toolEvidence }
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
export async function runAgentIsolated(opts: IsolatedAgentOptions): Promise<string> {
|
|
1227
|
+
return (await runAgentIsolatedDetailed(opts)).content
|
|
1078
1228
|
}
|
|
1079
1229
|
|
|
1080
1230
|
// ─── Shim: AgentLoop class with stream() compatible with providers/index.ts ──
|
|
@@ -1104,6 +1254,10 @@ export class AgentLoop {
|
|
|
1104
1254
|
run_id?: string
|
|
1105
1255
|
resume?: boolean
|
|
1106
1256
|
durable?: boolean
|
|
1257
|
+
turn_id?: string
|
|
1258
|
+
session_id?: string
|
|
1259
|
+
/** See AgentLoopOptions.historySource. */
|
|
1260
|
+
history_source?: TurnSource
|
|
1107
1261
|
}
|
|
1108
1262
|
signal?: AbortSignal
|
|
1109
1263
|
onToken?: (token: string) => void
|
|
@@ -1159,9 +1313,12 @@ export class AgentLoop {
|
|
|
1159
1313
|
onReasoningToken: config.onReasoningToken,
|
|
1160
1314
|
onStep: config.onStep,
|
|
1161
1315
|
extraTools: config.extraTools,
|
|
1316
|
+
historySource: config.configurable?.history_source,
|
|
1162
1317
|
runId: config.configurable?.run_id,
|
|
1163
1318
|
resume: config.configurable?.resume,
|
|
1164
1319
|
durable: config.configurable?.durable,
|
|
1320
|
+
turnId: config.configurable?.turn_id,
|
|
1321
|
+
sessionId: config.configurable?.session_id,
|
|
1165
1322
|
runKind: "chat",
|
|
1166
1323
|
})
|
|
1167
1324
|
}
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
* Capability Search — shared HiveDB search layer
|
|
3
3
|
*
|
|
4
4
|
* Single entry point for searching Hive's capability catalogs (native tools,
|
|
5
|
-
* skills, playbook rules, MCP tools)
|
|
6
|
-
*
|
|
5
|
+
* skills, playbook rules, MCP tools): one HiveDB index for all four, with the
|
|
6
|
+
* catalog discriminated by the `type` field rather than by separate tables.
|
|
7
7
|
*
|
|
8
8
|
* Document convention (one index, type discrimination via filters):
|
|
9
|
-
* - id: `tool:${name}` | `skill:${id}` | `playbook:${rowid}` | `mcp:${id}`
|
|
9
|
+
* - id: `tool:${name}` | `skill:${id}` | `playbook:${rowid}` | `mcp:${id}` | `agent:${id}`
|
|
10
10
|
* - name: tool/skill name or rule head (BM25 boost 4.0)
|
|
11
11
|
* - tags: category + triggers + keywords (BM25 boost 3.0)
|
|
12
12
|
* - body: description / rule text / content (BM25 boost 2.0)
|
|
@@ -24,7 +24,7 @@ import { logger } from "../utils/logger";
|
|
|
24
24
|
|
|
25
25
|
const log = logger.child("capability-search");
|
|
26
26
|
|
|
27
|
-
export type CapabilityType = "tool" | "skill" | "playbook" | "mcp";
|
|
27
|
+
export type CapabilityType = "tool" | "skill" | "playbook" | "mcp" | "agent";
|
|
28
28
|
|
|
29
29
|
export interface CapabilityHit {
|
|
30
30
|
/** Namespaced id, e.g. "tool:web_search" */
|
|
@@ -47,7 +47,7 @@ export interface CapabilityDoc {
|
|
|
47
47
|
extraFilters?: Array<{ field: string; value: string }>;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
const TYPE_PREFIXES: CapabilityType[] = ["tool", "skill", "playbook", "mcp"];
|
|
50
|
+
const TYPE_PREFIXES: CapabilityType[] = ["tool", "skill", "playbook", "mcp", "agent"];
|
|
51
51
|
|
|
52
52
|
function splitId(id: string): { type: CapabilityType; rawId: string } | null {
|
|
53
53
|
const sep = id.indexOf(":");
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { col } from "../storage/hive";
|
|
2
|
+
import type { AgentDoc } from "../storage/collections";
|
|
3
|
+
import {
|
|
4
|
+
applyRelativeCutoff,
|
|
5
|
+
replaceCapabilityDocs,
|
|
6
|
+
searchCapabilities,
|
|
7
|
+
type CapabilityDoc,
|
|
8
|
+
} from "./capability-search";
|
|
9
|
+
import { logger } from "../utils/logger";
|
|
10
|
+
|
|
11
|
+
const log = logger.child("catalog-selector");
|
|
12
|
+
const RELEVANCE_RATIO = 0.35;
|
|
13
|
+
const ROUTING_STOP_WORDS = new Set([
|
|
14
|
+
"a", "al", "de", "del", "el", "en", "la", "las", "lo", "los",
|
|
15
|
+
"o", "otro", "otra", "un", "una", "y",
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
function routingTokens(value: string): Set<string> {
|
|
19
|
+
const normalized = value
|
|
20
|
+
.normalize("NFD")
|
|
21
|
+
.replace(/\p{Diacritic}/gu, "")
|
|
22
|
+
.toLowerCase()
|
|
23
|
+
.split(/[^\p{Letter}\p{Number}_]+/u)
|
|
24
|
+
.filter(Boolean)
|
|
25
|
+
.map((token) => token.length > 4 && token.endsWith("s") ? token.slice(0, -1) : token)
|
|
26
|
+
.filter((token) => !ROUTING_STOP_WORDS.has(token));
|
|
27
|
+
return new Set(normalized);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function matchesRoutingExclusion(query: string, agent: AgentDoc): boolean {
|
|
31
|
+
if (!agent.routing_exclusions_json) return false;
|
|
32
|
+
const queryTokens = routingTokens(query);
|
|
33
|
+
const exclusions = JSON.parse(agent.routing_exclusions_json) as string[];
|
|
34
|
+
|
|
35
|
+
return exclusions.some((exclusion) => {
|
|
36
|
+
const excludedTokens = routingTokens(exclusion);
|
|
37
|
+
const shared = [...excludedTokens].filter((token) => queryTokens.has(token)).length;
|
|
38
|
+
return shared >= 2 && shared / Math.max(excludedTokens.size, 1) >= 0.35;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function getCatalogAgent(id: string): Promise<AgentDoc | null> {
|
|
43
|
+
const entry = await (await col<AgentDoc>("agents")).get(id);
|
|
44
|
+
return entry?.doc.source === "catalog" && entry.doc.enabled ? entry.doc : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function listCatalogAgents(): Promise<AgentDoc[]> {
|
|
48
|
+
const c = await col<AgentDoc>("agents");
|
|
49
|
+
return (await c.findBy("source", "catalog")).map((entry) => entry.doc).filter((doc) => doc.enabled);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function searchCatalogAgents(query: string, k = 5): Promise<Array<{ agent: AgentDoc; score: number }>> {
|
|
53
|
+
const hits = applyRelativeCutoff(
|
|
54
|
+
await searchCapabilities(query, { types: ["agent"], k }),
|
|
55
|
+
RELEVANCE_RATIO,
|
|
56
|
+
);
|
|
57
|
+
const c = await col<AgentDoc>("agents");
|
|
58
|
+
const results: Array<{ agent: AgentDoc; score: number }> = [];
|
|
59
|
+
for (const hit of hits) {
|
|
60
|
+
const entry = await c.get(hit.rawId);
|
|
61
|
+
if (
|
|
62
|
+
entry?.doc.source === "catalog" &&
|
|
63
|
+
entry.doc.enabled &&
|
|
64
|
+
!matchesRoutingExclusion(query, entry.doc)
|
|
65
|
+
) {
|
|
66
|
+
results.push({ agent: entry.doc, score: hit.score });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return results;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function syncCatalogAgentsToIndex(): Promise<void> {
|
|
73
|
+
const agents = await listCatalogAgents();
|
|
74
|
+
const docs: CapabilityDoc[] = agents.map((agent) => ({
|
|
75
|
+
type: "agent",
|
|
76
|
+
rawId: agent.id,
|
|
77
|
+
name: `${agent.name} ${agent.id}`,
|
|
78
|
+
tags: [
|
|
79
|
+
...(agent.routing_examples_json ? JSON.parse(agent.routing_examples_json) : []),
|
|
80
|
+
...(agent.tool_allowlist_json ? JSON.parse(agent.tool_allowlist_json) : []),
|
|
81
|
+
...(agent.skills_json ? JSON.parse(agent.skills_json) : []),
|
|
82
|
+
].join(" "),
|
|
83
|
+
// The complete system prompt is intentionally excluded: it adds routing
|
|
84
|
+
// noise and may contain operational policy not meant for retrieval.
|
|
85
|
+
body: agent.description ?? "",
|
|
86
|
+
}));
|
|
87
|
+
await replaceCapabilityDocs("agent", docs);
|
|
88
|
+
log.info(`[catalog-selector] Synced ${docs.length} catalog agents to HiveDB index`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function renderAgentRoutingCatalog(agents: AgentDoc[]): string {
|
|
92
|
+
return agents
|
|
93
|
+
.filter((a) => a.id !== "acceptance_verifier")
|
|
94
|
+
.map((a) => {
|
|
95
|
+
const exclusions = a.routing_exclusions_json
|
|
96
|
+
? JSON.parse(a.routing_exclusions_json) as string[]
|
|
97
|
+
: [];
|
|
98
|
+
const exclusionText = exclusions.length > 0
|
|
99
|
+
? ` NO usar para: ${exclusions.join("; ")}.`
|
|
100
|
+
: "";
|
|
101
|
+
return `- ${a.id}: ${a.description ?? ""}${exclusionText}`;
|
|
102
|
+
})
|
|
103
|
+
.join("\n");
|
|
104
|
+
}
|
|
@@ -21,8 +21,9 @@ import {
|
|
|
21
21
|
getHistory,
|
|
22
22
|
getSummary,
|
|
23
23
|
saveSummary,
|
|
24
|
-
toAPIMessages,
|
|
25
24
|
getMessageCount,
|
|
25
|
+
isInternalSource,
|
|
26
|
+
type StoredMessage,
|
|
26
27
|
} from "./conversation-store"
|
|
27
28
|
import { estimateTokens } from "../utils/toon"
|
|
28
29
|
import { callLLM, resolveProviderConfig, getDefaultLLM, type ContentPart } from "./llm-client"
|
|
@@ -80,22 +81,48 @@ export async function maybeCompact(
|
|
|
80
81
|
}
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Find a clean cut point: the "keep" side must begin with a user turn so we
|
|
86
|
+
* never leave orphaned tool messages at the start of the visible window.
|
|
87
|
+
* Internal events (delegation fan-in) are persisted as role:"user", so they
|
|
88
|
+
* are valid boundaries here same as human turns.
|
|
89
|
+
* Returns 0 when no clean boundary exists (caller should skip compaction).
|
|
90
|
+
*/
|
|
91
|
+
export function findCompactionCutIndex(rows: StoredMessage[], keepLastN = KEEP_LAST_N_MESSAGES): number {
|
|
92
|
+
let cutIndex = rows.length - keepLastN
|
|
93
|
+
while (cutIndex > 0 && rows[cutIndex]?.role !== "user") {
|
|
94
|
+
cutIndex--
|
|
95
|
+
}
|
|
96
|
+
return cutIndex
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Render a transcript for the summarizer LLM. Internal events (delegation
|
|
101
|
+
* fan-in notices) are labeled distinctly — they are persisted as
|
|
102
|
+
* role:"user" so the LLM treats them as input, but labeling them [USER] here
|
|
103
|
+
* would make the summarizer attribute system-generated task outcomes to the
|
|
104
|
+
* human, baking that misattribution into the durable summary.
|
|
105
|
+
*/
|
|
106
|
+
export function renderTranscript(rows: StoredMessage[], maxMsgChars = MAX_MSG_CHARS): string {
|
|
107
|
+
return rows
|
|
108
|
+
.map((r) => {
|
|
109
|
+
const label = isInternalSource(r.source) ? "EVENTO INTERNO" : r.role.toUpperCase()
|
|
110
|
+
return `[${label}]: ${r.content.substring(0, maxMsgChars)}`
|
|
111
|
+
})
|
|
112
|
+
.join("\n\n")
|
|
113
|
+
}
|
|
114
|
+
|
|
83
115
|
/**
|
|
84
116
|
* Compress a thread's history into a summary.
|
|
85
117
|
*/
|
|
86
|
-
|
|
118
|
+
async function compactThread(
|
|
87
119
|
threadId: string,
|
|
88
120
|
notify?: { channel: string; userId: string }
|
|
89
121
|
): Promise<void> {
|
|
90
122
|
const allMessages = await getHistory(threadId)
|
|
91
123
|
if (allMessages.length <= KEEP_LAST_N_MESSAGES) return
|
|
92
124
|
|
|
93
|
-
|
|
94
|
-
// we never leave orphaned tool messages at the start of the visible window.
|
|
95
|
-
let cutIndex = allMessages.length - KEEP_LAST_N_MESSAGES
|
|
96
|
-
while (cutIndex > 0 && allMessages[cutIndex]?.role !== "user") {
|
|
97
|
-
cutIndex--
|
|
98
|
-
}
|
|
125
|
+
const cutIndex = findCompactionCutIndex(allMessages)
|
|
99
126
|
if (cutIndex <= 0) {
|
|
100
127
|
log.info(`[compaction] No clean user-turn boundary found — skipping`)
|
|
101
128
|
return
|
|
@@ -111,17 +138,7 @@ export async function compactThread(
|
|
|
111
138
|
|
|
112
139
|
// Cap transcript to avoid overflowing small model contexts
|
|
113
140
|
const capped = toSummarize.slice(-MAX_TRANSCRIPT_MSGS)
|
|
114
|
-
const
|
|
115
|
-
const transcript = apiMessages
|
|
116
|
-
.map((m) => {
|
|
117
|
-
const text = typeof m.content === "string"
|
|
118
|
-
? m.content
|
|
119
|
-
: Array.isArray(m.content)
|
|
120
|
-
? m.content.filter(p => p.type === "text").map(p => (p as any).text).join("\n")
|
|
121
|
-
: ""
|
|
122
|
-
return `[${m.role.toUpperCase()}]: ${text.substring(0, MAX_MSG_CHARS)}`
|
|
123
|
-
})
|
|
124
|
-
.join("\n\n")
|
|
141
|
+
const transcript = renderTranscript(capped)
|
|
125
142
|
|
|
126
143
|
const defaultLLM = await getDefaultLLM()
|
|
127
144
|
if (!defaultLLM) throw new Error("No active LLM providers/models configured in the database")
|
|
@@ -210,25 +227,3 @@ export function clearOldToolResults<T extends { role: string; content: string |
|
|
|
210
227
|
})
|
|
211
228
|
}
|
|
212
229
|
|
|
213
|
-
/**
|
|
214
|
-
* Summarize a tool result to a single line
|
|
215
|
-
* Used for very old tool results (> 10 turns)
|
|
216
|
-
*/
|
|
217
|
-
export function summarizeToolResult(content: string, toolName?: string): string {
|
|
218
|
-
// Try to extract success/failure status
|
|
219
|
-
const isError = content.includes('error') || content.includes('failed') || content.startsWith('[Tool Error]')
|
|
220
|
-
const isSuccess = content.includes('ok') || content.includes('success') || content.includes('true')
|
|
221
|
-
|
|
222
|
-
// Try to extract key result field from JSON/TOON
|
|
223
|
-
let keyInfo = ""
|
|
224
|
-
try {
|
|
225
|
-
// Simple extraction of first key value
|
|
226
|
-
const firstLine = content.split('\n')[0].substring(0, 80)
|
|
227
|
-
keyInfo = firstLine
|
|
228
|
-
} catch {
|
|
229
|
-
keyInfo = content.substring(0, 80)
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
const status = isError ? "failed" : isSuccess ? "success" : "completed"
|
|
233
|
-
return `[${toolName || 'Tool'} ${status}: ${keyInfo}...]`
|
|
234
|
-
}
|