@johpaz/hive-agents 0.0.47 → 1.0.1
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 +128 -897
- package/dist/hive.js +222237 -206295
- package/dist/tool-worker.js +226 -927
- package/dist/ui/assets/A2UIPage-D4nzp5NV.js +8 -0
- package/dist/ui/assets/AgentCreateForm-M2RhjeA1.js +1 -0
- package/dist/ui/assets/AgentDetailPage-DkFRtj8g.js +1 -0
- package/dist/ui/assets/AgentNewPage-CfBU7puz.js +1 -0
- package/dist/ui/assets/AgentsPage-Ctzq2LWx.js +10 -0
- package/dist/ui/assets/ApiClientPage-DKbGO1QW.js +3 -0
- package/dist/ui/assets/ChannelsPage-H6rgr8DQ.js +8 -0
- package/dist/ui/assets/DashboardPage-BIjYGf4m.js +6 -0
- package/dist/ui/assets/{LoginPage-BTxJdFVG.js → LoginPage-DazoxtBJ.js} +1 -1
- package/dist/ui/assets/{LogsPage-DVV2eHbh.js → LogsPage-DMZ6KtQ3.js} +1 -1
- package/dist/ui/assets/MeetingPage-CSLFvHL7.js +1 -0
- package/dist/ui/assets/ModelSelector-BCfvugHB.js +1 -0
- package/dist/ui/assets/{NotFound-BIUDlIXU.js → NotFound-Bpr12V51.js} +1 -1
- package/dist/ui/assets/Office3DPage-BE6Epe0d.js +4614 -0
- package/dist/ui/assets/Office3DPage-C3SIzd2H.css +1 -0
- package/dist/ui/assets/ProvidersPage-D0cApfM1.js +1 -0
- package/dist/ui/assets/{RecoverPage-7YDQysBL.js → RecoverPage-BVUPHG9z.js} +1 -1
- package/dist/ui/assets/SettingsPage-DCZ4nql4.js +9 -0
- package/dist/ui/assets/SetupPage-In19p30M.js +1 -0
- package/dist/ui/assets/WebChatPage-ByVBSzxL.js +29 -0
- package/dist/ui/assets/{activity-c3pNngT_.js → activity-BIIli7ET.js} +1 -1
- package/dist/ui/assets/agentCapabilities-D1PD9yFH.js +1 -0
- package/dist/ui/assets/alert-CQlRq6sv.js +1 -0
- package/dist/ui/assets/arrow-left-BfcnX8Er.js +1 -0
- package/dist/ui/assets/arrow-right-Q-dzAn8k.js +1 -0
- package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +1 -0
- package/dist/ui/assets/badge-DKGZbVZJ.js +1 -0
- package/dist/ui/assets/{calendar-B-KZ9RQO.js → calendar-S9-_Q6QR.js} +1 -1
- package/dist/ui/assets/{card-CNf6BS2e.js → card-D3Nw3kh3.js} +1 -1
- package/dist/ui/assets/check-CryV78SQ.js +1 -0
- package/dist/ui/assets/chevron-down-QCtMs-Af.js +1 -0
- package/dist/ui/assets/chevron-left-dTGbyl5G.js +1 -0
- package/dist/ui/assets/chevron-right-D0GjXbnO.js +1 -0
- package/dist/ui/assets/chevron-up-Cg0jO8uT.js +1 -0
- package/dist/ui/assets/{circle-alert-KuAm2FWh.js → circle-alert-DTVW4R94.js} +1 -1
- package/dist/ui/assets/circle-check-BAolxswA.js +1 -0
- package/dist/ui/assets/{circle-x-DjLkFDO8.js → circle-x-CJXbXzRh.js} +1 -1
- package/dist/ui/assets/{copy-Bu5d7C-0.js → copy-X_TPpA-A.js} +1 -1
- package/dist/ui/assets/{dialog-Jk4bieO4.js → dialog-uUBz_NIB.js} +1 -1
- package/dist/ui/assets/dist-CD_qfA30.js +1 -0
- package/dist/ui/assets/{download-Cjbk4Rek.js → download-C-fXu08w.js} +1 -1
- package/dist/ui/assets/earth-CTsVjCmp.js +1 -0
- package/dist/ui/assets/ellipsis-vertical-5zBh5yzc.js +1 -0
- package/dist/ui/assets/{external-link-6sTlRDUR.js → external-link-CvpRhwC_.js} +1 -1
- package/dist/ui/assets/{eye-Df8o0tkC.js → eye-CM-HQEWU.js} +1 -1
- package/dist/ui/assets/{file-text-lnxnjBp0.js → file-text-lwkvYGtA.js} +1 -1
- package/dist/ui/assets/{gateway-url-DwzPmoc8.js → gateway-url-BlnabM5e.js} +1 -1
- package/dist/ui/assets/gauge-CB-cas-h.js +1 -0
- package/dist/ui/assets/{history-CAF_R34_.js → history-eSHspWRr.js} +1 -1
- package/dist/ui/assets/index-D489S18g.css +2 -0
- package/dist/ui/assets/index-ZjAc-KQS.js +116 -0
- package/dist/ui/assets/{info-WjromB4Y.js → info-DTgFQ_jA.js} +1 -1
- package/dist/ui/assets/key-CeM9JJkq.js +1 -0
- package/dist/ui/assets/label-k0jYxoWW.js +1 -0
- package/dist/ui/assets/loader-circle-Dtfz4FWw.js +1 -0
- package/dist/ui/assets/lock-open-B089GUAJ.js +1 -0
- package/dist/ui/assets/mail--gNFIe4M.js +1 -0
- package/dist/ui/assets/{pause-VqeUmp2Z.js → pause-DjT1nwQM.js} +1 -1
- package/dist/ui/assets/pencil-6PRgdjiU.js +1 -0
- package/dist/ui/assets/play-tOrP0xUJ.js +1 -0
- package/dist/ui/assets/plus-Cnom3j47.js +1 -0
- package/dist/ui/assets/progress-DrI2UDu-.js +1 -0
- package/dist/ui/assets/radio-D-joO9J0.js +1 -0
- package/dist/ui/assets/{refresh-cw-CCzDCAuz.js → refresh-cw-BRrzoHQW.js} +1 -1
- package/dist/ui/assets/scroll-area-CfHn94Vb.js +1 -0
- package/dist/ui/assets/search-D277MUP0.js +1 -0
- package/dist/ui/assets/select-BOR8MsSL.js +1 -0
- package/dist/ui/assets/{send-BPk9XbIq.js → send-DIlj81PT.js} +1 -1
- package/dist/ui/assets/{settings-BGfrZ_zM.js → settings-CkBjgAEm.js} +1 -1
- package/dist/ui/assets/{shield-CxhcUT39.js → shield-U0hIjGzm.js} +1 -1
- package/dist/ui/assets/slider-CmE_z1Ii.js +1 -0
- package/dist/ui/assets/{sparkles-BhwlS1pc.js → sparkles-VXHGDbNh.js} +1 -1
- package/dist/ui/assets/{square-DMNWw4Hi.js → square-OHeetvN3.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-C6YPcJl_.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-DQxm7DUM.js} +1 -1
- package/dist/ui/assets/{triangle-alert-pVIJGjga.js → triangle-alert-Dj8ZhmWj.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-BnC4jLE-.js → useHiveAgentsModelLoad-COLvs-Ho.js} +1 -1
- package/dist/ui/assets/useOfficeModel-Cy7cAyEn.js +1 -0
- package/dist/ui/assets/useProviders-q6iROeWE.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-Bm735CXN.js +1 -0
- package/dist/ui/assets/wifi-DklBfOZ6.js +1 -0
- package/dist/ui/assets/{zap-B4RaNNO5.js → zap-BEZNJ0i0.js} +1 -1
- package/dist/ui/index.html +16 -13
- package/dist/ui/logoblack.png +0 -0
- package/dist/ui/logocolor-dark.png +0 -0
- package/dist/ui/logocolorbg.png +0 -0
- package/dist/ui/logodoradobg.png +0 -0
- package/package.json +18 -15
- 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 +156 -1
- package/packages/cli/src/commands/gateway.ts +2 -9
- package/packages/cli/src/commands/onboard.ts +126 -59
- package/packages/cli/src/index.ts +9 -11
- package/packages/cli/src/ui-bundle.generated.ts +9 -92
- package/packages/core/src/agent/acceptance-checks.ts +172 -0
- package/packages/core/src/agent/agent-catalog.ts +348 -0
- package/packages/core/src/agent/agent-loop.ts +204 -28
- package/packages/core/src/agent/capability-search.ts +5 -5
- package/packages/core/src/agent/catalog-selector.ts +103 -0
- package/packages/core/src/agent/compaction.ts +52 -42
- package/packages/core/src/agent/context-compiler.ts +185 -63
- 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 +241 -0
- package/packages/core/src/agent/goal-runner.ts +111 -32
- package/packages/core/src/agent/index.ts +17 -0
- package/packages/core/src/agent/llm-client.ts +34 -2
- package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
- package/packages/core/src/agent/llm-providers/hiveagents.ts +1 -1
- package/packages/core/src/agent/llm-providers/interface.ts +16 -5
- package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
- package/packages/core/src/agent/minimal-loadout.ts +47 -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 +6 -1
- package/packages/core/src/agent/providers/index.ts +9 -4
- 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 +61 -36
- 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 +121 -69
- package/packages/core/src/canvas/index.ts +0 -2
- package/packages/core/src/channels/base.ts +3 -1
- package/packages/core/src/channels/manager.ts +117 -25
- package/packages/core/src/channels/webchat.ts +4 -8
- package/packages/core/src/channels/whatsapp.ts +6 -1
- package/packages/core/src/config/loader.ts +13 -23
- package/packages/core/src/events/agent-bus.ts +0 -31
- package/packages/core/src/events/channel-narration.ts +150 -0
- package/packages/core/src/events/narration.ts +82 -0
- package/packages/core/src/events/tool-narration.ts +62 -0
- package/packages/core/src/gateway/channel-notify.ts +43 -10
- package/packages/core/src/gateway/delegation-groups.ts +258 -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 +4 -57
- package/packages/core/src/gateway/helpers/redact.ts +1 -1
- package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
- package/packages/core/src/gateway/initializer.ts +15 -13
- package/packages/core/src/gateway/job-executors.ts +197 -104
- 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 +11 -25
- 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/channels.ts +15 -1
- 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/models.ts +69 -12
- package/packages/core/src/gateway/routes/providers.ts +111 -28
- package/packages/core/src/gateway/routes/setup.ts +92 -35
- package/packages/core/src/gateway/routes/skills.ts +2 -2
- package/packages/core/src/gateway/routes/system.ts +31 -10
- package/packages/core/src/gateway/routes/users.ts +24 -1
- package/packages/core/src/gateway/routes/voice.ts +3 -0
- package/packages/core/src/gateway/server.ts +207 -141
- 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 +63 -13
- 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 +34 -10
- package/packages/core/src/storage/collections.ts +167 -27
- package/packages/core/src/storage/crypto.ts +147 -58
- package/packages/core/src/storage/hivedb.ts +9 -0
- package/packages/core/src/storage/model-id.ts +53 -0
- package/packages/core/src/storage/onboarding.ts +160 -34
- package/packages/core/src/storage/reconcile.ts +2 -5
- package/packages/core/src/storage/seed.ts +436 -158
- package/packages/core/src/storage/usage.ts +61 -132
- 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/index.ts +566 -85
- 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 +19 -46
- 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-backend.ts +129 -0
- package/packages/core/src/tools/web/browser-screenshot.ts +26 -5
- package/packages/core/src/tools/web/browser-service.ts +75 -35
- package/packages/core/src/tools/web/index.ts +3 -0
- package/packages/core/src/tools/web/webview-backend.ts +412 -0
- package/packages/core/src/utils/logger.ts +58 -30
- package/packages/core/src/utils/toon.ts +0 -20
- package/packages/core/src/voice/index.ts +108 -17
- 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/agent_spawner/SKILL.md +24 -18
- package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +48 -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 +640 -1226
- 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
|
@@ -10,7 +10,7 @@ import { getHiveDb } from "../storage/hivedb"
|
|
|
10
10
|
import { logger } from "../utils/logger"
|
|
11
11
|
import type { LLMMessage, ContentPart } from "./llm-client"
|
|
12
12
|
import { estimateTokens } from "../utils/toon"
|
|
13
|
-
import type { ConversationDoc, SummaryDoc } from "../storage/collections"
|
|
13
|
+
import type { ConversationDoc, SummaryDoc, MessageSource } from "../storage/collections"
|
|
14
14
|
|
|
15
15
|
const log = logger.child("conv-store")
|
|
16
16
|
|
|
@@ -21,7 +21,9 @@ export interface StoredMessage {
|
|
|
21
21
|
id: number
|
|
22
22
|
thread_id: string
|
|
23
23
|
channel: string
|
|
24
|
-
role: "user" | "assistant" | "tool"
|
|
24
|
+
role: "user" | "assistant" | "tool"
|
|
25
|
+
/** Provenance of this turn. Never null — legacy rows are normalized to "legacy_internal" on read. */
|
|
26
|
+
source: MessageSource
|
|
25
27
|
content: string
|
|
26
28
|
tool_calls_json: string | null
|
|
27
29
|
tool_call_id: string | null
|
|
@@ -31,17 +33,48 @@ export interface StoredMessage {
|
|
|
31
33
|
created_at: number
|
|
32
34
|
}
|
|
33
35
|
|
|
36
|
+
// ─── Internal events (delegation fan-in, etc.) ────────────────────────────────
|
|
37
|
+
//
|
|
38
|
+
// These are system-authored turns (async delegation outcomes) that must reach
|
|
39
|
+
// the model as input but must never be persisted with role:"system" — doing so
|
|
40
|
+
// causes every LLM provider to hoist them permanently into the system
|
|
41
|
+
// instruction on every subsequent turn (see gemini.ts/anthropic.ts, which
|
|
42
|
+
// concatenate ALL role:"system" messages into systemInstruction/system). They
|
|
43
|
+
// are persisted as role:"user" + a source tag instead, and wrapped with a
|
|
44
|
+
// framing marker only at serialization time (toAPIMessages), so stored content
|
|
45
|
+
// stays clean and the wording can evolve without a migration.
|
|
46
|
+
|
|
47
|
+
export const INTERNAL_SOURCES: ReadonlySet<string> =
|
|
48
|
+
new Set(["task_complete", "delegation_summary", "legacy_internal"])
|
|
49
|
+
|
|
50
|
+
export function isInternalSource(source: string | null | undefined): boolean {
|
|
51
|
+
return !!source && INTERNAL_SOURCES.has(source)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function formatInternalEvent(source: string, content: string): string {
|
|
55
|
+
return `<hive:internal_event source="${source}">\n` +
|
|
56
|
+
`Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id) ni JSON crudo. Respondé al usuario de forma natural y breve.\n\n` +
|
|
57
|
+
`${content}\n` +
|
|
58
|
+
`</hive:internal_event>`
|
|
59
|
+
}
|
|
60
|
+
|
|
34
61
|
function storageId(threadId: string, seq: number): string {
|
|
35
62
|
return `${threadId}:${String(seq).padStart(15, "0")}`
|
|
36
63
|
}
|
|
37
64
|
|
|
38
65
|
function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
|
|
39
66
|
const seq = parseInt(id.slice(id.lastIndexOf(":") + 1), 10)
|
|
67
|
+
// Legacy rows (written before `source` existed) used role:"system" as the
|
|
68
|
+
// sole marker for internal events. Normalize them here so every downstream
|
|
69
|
+
// reader (getRecentMessages, compaction, context-compiler) sees a single
|
|
70
|
+
// consistent shape and never has to special-case role:"system" again.
|
|
71
|
+
const legacyInternal = doc.role === "system"
|
|
40
72
|
return {
|
|
41
73
|
id: seq,
|
|
42
74
|
thread_id: doc.thread_id,
|
|
43
75
|
channel: doc.channel,
|
|
44
|
-
role: doc.role,
|
|
76
|
+
role: legacyInternal ? "user" : (doc.role as StoredMessage["role"]),
|
|
77
|
+
source: doc.source ?? (legacyInternal ? "legacy_internal" : "message"),
|
|
45
78
|
content: doc.content,
|
|
46
79
|
tool_calls_json: doc.tool_calls_json,
|
|
47
80
|
tool_call_id: doc.tool_call_id,
|
|
@@ -54,6 +87,16 @@ function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
|
|
|
54
87
|
|
|
55
88
|
// ─── Message operations ───────────────────────────────────────────────────────
|
|
56
89
|
|
|
90
|
+
const recentMessageTimestamps: number[] = []
|
|
91
|
+
|
|
92
|
+
export function getRecentMessageCount(windowMs = 5 * 60_000): number {
|
|
93
|
+
const cutoff = Date.now() - windowMs
|
|
94
|
+
while (recentMessageTimestamps.length && recentMessageTimestamps[0] < cutoff) {
|
|
95
|
+
recentMessageTimestamps.shift()
|
|
96
|
+
}
|
|
97
|
+
return recentMessageTimestamps.length
|
|
98
|
+
}
|
|
99
|
+
|
|
57
100
|
export async function addMessage(
|
|
58
101
|
threadId: string,
|
|
59
102
|
role: StoredMessage["role"],
|
|
@@ -63,6 +106,7 @@ export async function addMessage(
|
|
|
63
106
|
tool_calls?: LLMMessage["tool_calls"]
|
|
64
107
|
tool_call_id?: string
|
|
65
108
|
reasoning_content?: string
|
|
109
|
+
source?: MessageSource
|
|
66
110
|
}
|
|
67
111
|
): Promise<number> {
|
|
68
112
|
// Handle multimodal content by extracting text for the content column
|
|
@@ -90,6 +134,7 @@ export async function addMessage(
|
|
|
90
134
|
tool_calls_json,
|
|
91
135
|
tool_call_id: opts?.tool_call_id ?? null,
|
|
92
136
|
reasoning_content: opts?.reasoning_content ?? null,
|
|
137
|
+
source: opts?.source ?? "message",
|
|
93
138
|
// Estimate tokens: content + tool_calls JSON
|
|
94
139
|
token_count: Math.max(1, estimateTokens(textContent) + estimateTokens(tool_calls_json ?? "")),
|
|
95
140
|
created_at: now,
|
|
@@ -99,6 +144,7 @@ export async function addMessage(
|
|
|
99
144
|
// Fire-and-forget — never block message persistence on the activity chart rollup.
|
|
100
145
|
const hour = new Date(now).toISOString().slice(0, 13)
|
|
101
146
|
bumpRollup("activityRollups", hour, { messageCount: 1 }).catch(() => {})
|
|
147
|
+
recentMessageTimestamps.push(now)
|
|
102
148
|
|
|
103
149
|
return seq
|
|
104
150
|
}
|
|
@@ -188,6 +234,13 @@ export function toAPIMessages(rows: StoredMessage[]): LLMMessage[] {
|
|
|
188
234
|
if (r.content_multimodal) {
|
|
189
235
|
try { content = JSON.parse(r.content_multimodal) } catch { /* ignore */ }
|
|
190
236
|
}
|
|
237
|
+
// Internal events (delegation fan-in) are wrapped at serialization time —
|
|
238
|
+
// never at authoring time — so stored content stays clean and legacy rows
|
|
239
|
+
// (normalized to source:"legacy_internal" in toStoredMessage) get wrapped
|
|
240
|
+
// for free. Internal events are never multimodal in practice.
|
|
241
|
+
if (isInternalSource(r.source) && typeof content === "string") {
|
|
242
|
+
content = formatInternalEvent(r.source, content)
|
|
243
|
+
}
|
|
191
244
|
const msg: LLMMessage = { role: r.role, content }
|
|
192
245
|
// Note: tool_calls and tool_call_id are NOT reconstructed from DB.
|
|
193
246
|
// Tool results are kept in-memory during iteration but not persisted,
|
|
@@ -6,23 +6,26 @@
|
|
|
6
6
|
* - Repeated patterns → increment helpful_count
|
|
7
7
|
* - Contradicted rules → increment harmful_count or deactivate
|
|
8
8
|
* - Deactivate rules where harmful_count > helpful_count
|
|
9
|
-
* - Archive unused workers
|
|
10
9
|
*
|
|
11
10
|
* Never rewrites the whole playbook — only incremental edits.
|
|
12
11
|
*
|
|
13
12
|
* "Last processed reflection" is tracked via a `cursors` collection doc
|
|
14
13
|
* (id="curator:lastReflection") instead of SQL's MAX(source_reflection_id).
|
|
15
|
-
* Stale-worker detection uses the denormalized `agents.lastTraceAt` field
|
|
16
|
-
* (set by tracer.ts) instead of a correlated MAX(t.created_at) subquery.
|
|
17
14
|
*/
|
|
18
15
|
|
|
19
16
|
import { logger } from "../utils/logger"
|
|
20
17
|
import { col, nextId, toIndexable, fromIndexable } from "../storage/hive"
|
|
21
|
-
import type {
|
|
18
|
+
import type {
|
|
19
|
+
ReflectionDoc,
|
|
20
|
+
PlaybookDoc,
|
|
21
|
+
AgentDoc,
|
|
22
|
+
CursorDoc,
|
|
23
|
+
AgentProposalDoc,
|
|
24
|
+
TraceDoc,
|
|
25
|
+
} from "../storage/collections"
|
|
22
26
|
|
|
23
27
|
const log = logger.child("curator")
|
|
24
28
|
|
|
25
|
-
const DAYS_BEFORE_ARCHIVE = 14 // archive workers not used in N days
|
|
26
29
|
const MAX_HARMFUL_BEFORE_PRUNE = 3
|
|
27
30
|
const CURSOR_ID = "curator:lastReflection"
|
|
28
31
|
|
|
@@ -32,8 +35,6 @@ export async function runCurator(): Promise<void> {
|
|
|
32
35
|
const cursorsCol = await col<CursorDoc>("cursors")
|
|
33
36
|
const playbookCol = await col<PlaybookDoc>("playbook")
|
|
34
37
|
const reflectionsCol = await col<ReflectionDoc>("reflections")
|
|
35
|
-
const agentsCol = await col<AgentDoc>("agents")
|
|
36
|
-
|
|
37
38
|
// Process unprocessed reflections (those newer than last run)
|
|
38
39
|
const cursorEntry = await cursorsCol.get(CURSOR_ID)
|
|
39
40
|
const lastProcessed = cursorEntry?.doc.value ?? null
|
|
@@ -63,31 +64,7 @@ export async function runCurator(): Promise<void> {
|
|
|
63
64
|
}
|
|
64
65
|
}
|
|
65
66
|
|
|
66
|
-
|
|
67
|
-
// (set by tracer.ts) instead of a correlated MAX(created_at) subquery.
|
|
68
|
-
const cutoff = Date.now() - (DAYS_BEFORE_ARCHIVE * 86400 * 1000)
|
|
69
|
-
const allAgents = await agentsCol.scan({})
|
|
70
|
-
const staleWorkers = allAgents.filter(e =>
|
|
71
|
-
e.doc.role === "worker" &&
|
|
72
|
-
e.doc.status !== "archived" &&
|
|
73
|
-
e.doc.enabled &&
|
|
74
|
-
(e.doc.lastTraceAt ?? 0) < cutoff
|
|
75
|
-
)
|
|
76
|
-
|
|
77
|
-
for (const worker of staleWorkers) {
|
|
78
|
-
await agentsCol.put(worker.id, { ...worker.doc, status: "archived", updated_at: Date.now() }, { expectedVersion: worker.version })
|
|
79
|
-
|
|
80
|
-
// Add playbook note about archival
|
|
81
|
-
const currentPlaybook = await playbookCol.scan({})
|
|
82
|
-
await addOrUpdateRule(playbookCol, currentPlaybook, {
|
|
83
|
-
rule: `Worker '${worker.doc.name}' was archived due to inactivity (>${DAYS_BEFORE_ARCHIVE} days unused).`,
|
|
84
|
-
category: "agent_creation",
|
|
85
|
-
applicable_to: null,
|
|
86
|
-
sourceReflectionId: null,
|
|
87
|
-
})
|
|
88
|
-
|
|
89
|
-
log.info(`[curator] Archived inactive worker: ${worker.doc.name} (${worker.id})`)
|
|
90
|
-
}
|
|
67
|
+
await curateAgentStructure()
|
|
91
68
|
|
|
92
69
|
log.info("[curator] Playbook updated")
|
|
93
70
|
} catch (err) {
|
|
@@ -95,6 +72,115 @@ export async function runCurator(): Promise<void> {
|
|
|
95
72
|
}
|
|
96
73
|
}
|
|
97
74
|
|
|
75
|
+
async function curateAgentStructure(): Promise<void> {
|
|
76
|
+
const agentsCol = await col<AgentDoc>("agents")
|
|
77
|
+
const proposalsCol = await col<AgentProposalDoc>("agentProposals")
|
|
78
|
+
const tracesCol = await col<TraceDoc>("traces")
|
|
79
|
+
const now = Date.now()
|
|
80
|
+
|
|
81
|
+
// A catalog agent is a capability, not a disposable worker: disabling
|
|
82
|
+
// `workspace_file_operator` takes filesystem work away from the whole hive
|
|
83
|
+
// and nothing replaces it, so a bad streak can never switch one off by
|
|
84
|
+
// itself. It raises a proposal for a human to decide instead — and the ACE
|
|
85
|
+
// counters keep accumulating either way, so routing still sees the signal.
|
|
86
|
+
for (const entry of await agentsCol.findBy("source", "catalog")) {
|
|
87
|
+
if (!entry.doc.enabled) continue
|
|
88
|
+
const helpful = entry.doc.helpful_count ?? 0
|
|
89
|
+
const harmful = entry.doc.harmful_count ?? 0
|
|
90
|
+
if (harmful > helpful && harmful >= MAX_HARMFUL_BEFORE_PRUNE) {
|
|
91
|
+
await ensureAgentProposal(proposalsCol, {
|
|
92
|
+
type: "disable_agent",
|
|
93
|
+
agentId: entry.id,
|
|
94
|
+
change: { active: false, reason: "harmful_count exceeded helpful_count" },
|
|
95
|
+
evidence: [],
|
|
96
|
+
confidence: 1,
|
|
97
|
+
})
|
|
98
|
+
log.warn(`[curator] Catalog agent '${entry.doc.name}' (${entry.id}) is failing verification (helpful=${helpful}, harmful=${harmful}) — proposed for review, left enabled`)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const traces = (await tracesCol.scan({})).map((entry) => entry.doc)
|
|
103
|
+
const agents = new Map((await agentsCol.scan({})).map((entry) => [entry.id, entry.doc]))
|
|
104
|
+
|
|
105
|
+
// Recurrent successful free workers are candidates for a learned template.
|
|
106
|
+
const freeSuccess = new Map<string, TraceDoc[]>()
|
|
107
|
+
for (const trace of traces) {
|
|
108
|
+
const agent = agents.get(trace.agent_id)
|
|
109
|
+
if (!trace.success || trace.tool_used || trace.catalog_agent_id || agent?.role !== "worker" || agent.source === "catalog") continue
|
|
110
|
+
const bucket = freeSuccess.get(trace.agent_id) ?? []
|
|
111
|
+
bucket.push(trace)
|
|
112
|
+
freeSuccess.set(trace.agent_id, bucket)
|
|
113
|
+
}
|
|
114
|
+
for (const [agentId, evidence] of freeSuccess) {
|
|
115
|
+
if (evidence.length < 5) continue
|
|
116
|
+
const agent = agents.get(agentId)!
|
|
117
|
+
await ensureAgentProposal(proposalsCol, {
|
|
118
|
+
type: "create_agent",
|
|
119
|
+
agentId: `candidate:${agentId}`,
|
|
120
|
+
change: {
|
|
121
|
+
suggested_name: agent.name,
|
|
122
|
+
suggested_description: agent.description,
|
|
123
|
+
observed_tasks: evidence.slice(-5).map((trace) => trace.input_summary),
|
|
124
|
+
},
|
|
125
|
+
evidence: evidence.slice(-5).map((trace) => trace.id),
|
|
126
|
+
confidence: Math.min(0.95, 0.5 + evidence.length * 0.05),
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Repeated failures identify a loadout mismatch. This remains a proposal;
|
|
131
|
+
// permissions are never changed automatically.
|
|
132
|
+
const failures = new Map<string, TraceDoc[]>()
|
|
133
|
+
for (const trace of traces) {
|
|
134
|
+
if (trace.success || !trace.catalog_agent_id || !trace.tool_used) continue
|
|
135
|
+
const key = `${trace.catalog_agent_id}\0${trace.tool_used}`
|
|
136
|
+
const bucket = failures.get(key) ?? []
|
|
137
|
+
bucket.push(trace)
|
|
138
|
+
failures.set(key, bucket)
|
|
139
|
+
}
|
|
140
|
+
for (const [key, evidence] of failures) {
|
|
141
|
+
if (evidence.length < 3) continue
|
|
142
|
+
const [agentId, tool] = key.split("\0")
|
|
143
|
+
await ensureAgentProposal(proposalsCol, {
|
|
144
|
+
type: "move_tool",
|
|
145
|
+
agentId,
|
|
146
|
+
change: { tool, reason: "repeated failures; review ownership or remove from loadout" },
|
|
147
|
+
evidence: evidence.slice(-10).map((trace) => trace.id),
|
|
148
|
+
confidence: Math.min(0.95, 0.55 + evidence.length * 0.05),
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const { syncCatalogAgentsToIndex } = await import("./catalog-selector")
|
|
153
|
+
await syncCatalogAgentsToIndex()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function ensureAgentProposal(
|
|
157
|
+
proposalsCol: Awaited<ReturnType<typeof col<AgentProposalDoc>>>,
|
|
158
|
+
input: {
|
|
159
|
+
type: AgentProposalDoc["type"]
|
|
160
|
+
agentId: string
|
|
161
|
+
change: unknown
|
|
162
|
+
evidence: string[]
|
|
163
|
+
confidence: number
|
|
164
|
+
},
|
|
165
|
+
): Promise<void> {
|
|
166
|
+
const existing = (await proposalsCol.findBy("agent_id", input.agentId))
|
|
167
|
+
.find((entry) => entry.doc.type === input.type && entry.doc.status === "proposed")
|
|
168
|
+
if (existing) return
|
|
169
|
+
const id = await nextId("agentProposals")
|
|
170
|
+
const now = Date.now()
|
|
171
|
+
await proposalsCol.put(id, {
|
|
172
|
+
id,
|
|
173
|
+
type: input.type,
|
|
174
|
+
agent_id: input.agentId,
|
|
175
|
+
proposed_change_json: JSON.stringify(input.change),
|
|
176
|
+
evidence_trace_ids_json: JSON.stringify(input.evidence),
|
|
177
|
+
confidence: input.confidence,
|
|
178
|
+
status: "proposed",
|
|
179
|
+
created_at: now,
|
|
180
|
+
updated_at: now,
|
|
181
|
+
}, { expectedVersion: 0 })
|
|
182
|
+
}
|
|
183
|
+
|
|
98
184
|
// ─── Process a single reflection ─────────────────────────────────────────────
|
|
99
185
|
|
|
100
186
|
async function processReflection(
|
|
@@ -103,6 +189,15 @@ async function processReflection(
|
|
|
103
189
|
reflection: ReflectionDoc
|
|
104
190
|
): Promise<void> {
|
|
105
191
|
const category = mapInsightTypeToCategory(reflection.insight_type)
|
|
192
|
+
const applicable: string[] = reflection.affected_tools ? JSON.parse(reflection.affected_tools) : []
|
|
193
|
+
if (reflection.affected_agents) {
|
|
194
|
+
const agentsCol = await col<AgentDoc>("agents")
|
|
195
|
+
for (const agentId of JSON.parse(reflection.affected_agents) as string[]) {
|
|
196
|
+
const agent = await agentsCol.get(agentId)
|
|
197
|
+
if (agent?.doc.source === "catalog") applicable.push(`agent:${agent.doc.id}`)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const applicableTo = applicable.length ? JSON.stringify([...new Set(applicable)]) : null
|
|
106
201
|
|
|
107
202
|
// Check if a similar rule already exists (fuzzy check by first 60 chars)
|
|
108
203
|
const prefix = reflection.description.substring(0, 60)
|
|
@@ -121,7 +216,7 @@ async function processReflection(
|
|
|
121
216
|
id,
|
|
122
217
|
rule: reflection.description,
|
|
123
218
|
category,
|
|
124
|
-
applicable_to:
|
|
219
|
+
applicable_to: applicableTo,
|
|
125
220
|
helpful_count: 1,
|
|
126
221
|
harmful_count: 0,
|
|
127
222
|
active: true,
|
|
@@ -129,7 +224,7 @@ async function processReflection(
|
|
|
129
224
|
created_at: now,
|
|
130
225
|
updated_at: now,
|
|
131
226
|
}, { expectedVersion: 0 })
|
|
132
|
-
allPlaybook.push({ id, version: 1, doc: { id, rule: reflection.description, category, applicable_to:
|
|
227
|
+
allPlaybook.push({ id, version: 1, doc: { id, rule: reflection.description, category, applicable_to: applicableTo, helpful_count: 1, harmful_count: 0, active: true, source_reflection_id: toIndexable(reflection.id), created_at: now, updated_at: now } })
|
|
133
228
|
}
|
|
134
229
|
|
|
135
230
|
function mapInsightTypeToCategory(
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { col, toIndexable, fromIndexable, updateDoc } from "../storage/hive";
|
|
2
|
+
import type {
|
|
3
|
+
AgentDoc,
|
|
4
|
+
McpServerDoc,
|
|
5
|
+
ModelDoc,
|
|
6
|
+
ProviderDoc,
|
|
7
|
+
SkillDoc,
|
|
8
|
+
AgentModelOverride,
|
|
9
|
+
} from "../storage/collections";
|
|
10
|
+
import { createAllTools } from "../tools";
|
|
11
|
+
import { loadConfig } from "../config/loader";
|
|
12
|
+
import type { MCPClientManager } from "@johpaz/hive-agents-mcp";
|
|
13
|
+
import { logger } from "../utils/logger";
|
|
14
|
+
|
|
15
|
+
const log = logger.child("delegation-runtime");
|
|
16
|
+
const MCP_IDLE_TTL_MS = 2 * 60_000;
|
|
17
|
+
|
|
18
|
+
export interface PrepareDelegationOptions {
|
|
19
|
+
workspace: string | null;
|
|
20
|
+
/** Fallback provider/model when the target row has none of its own (catalog agents are seeded without one — inherits the parent/coordinator's). */
|
|
21
|
+
parentProviderId?: string | null;
|
|
22
|
+
parentModelId?: string | null;
|
|
23
|
+
/** Model to avoid only during capability-based DB fallback resolution. Explicit agent/parent configuration always wins. */
|
|
24
|
+
executorModelId?: string | null;
|
|
25
|
+
mcpManager?: MCPClientManager | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface PreparedDelegation {
|
|
29
|
+
agent: AgentDoc;
|
|
30
|
+
toolNames: string[];
|
|
31
|
+
skillIds: string[];
|
|
32
|
+
mcpServerIds: string[];
|
|
33
|
+
providerId: string;
|
|
34
|
+
modelId: string;
|
|
35
|
+
release(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface McpLease {
|
|
39
|
+
refs: number;
|
|
40
|
+
serverName: string;
|
|
41
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const mcpLeases = new Map<string, McpLease>();
|
|
45
|
+
|
|
46
|
+
function matchesPattern(name: string, pattern: string): boolean {
|
|
47
|
+
if (!pattern.includes("*")) return name === pattern;
|
|
48
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
49
|
+
return new RegExp(`^${escaped}$`).test(name);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function expandToolAllowlist(patterns: string[], availableNames?: string[]): string[] {
|
|
53
|
+
const names = availableNames ?? createAllTools(loadConfig()).map((tool) => tool.name);
|
|
54
|
+
const selected = names.filter((name) => patterns.some((pattern) => matchesPattern(name, pattern)));
|
|
55
|
+
return [...new Set(selected)].sort();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function parseCapabilities(model: ModelDoc): string[] {
|
|
59
|
+
try {
|
|
60
|
+
return model.capabilities ? JSON.parse(model.capabilities) : [];
|
|
61
|
+
} catch {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolves the effective provider/model for a delegation. Persisted database
|
|
68
|
+
* configuration is authoritative: the agent's complete provider/model pair
|
|
69
|
+
* wins, otherwise the parent's complete pair is inherited. Capability metadata
|
|
70
|
+
* is consulted only when neither row supplies a complete pair, and candidates
|
|
71
|
+
* are selected exclusively from active database rows.
|
|
72
|
+
*/
|
|
73
|
+
export async function resolveAgentModel(
|
|
74
|
+
modelOverride: AgentModelOverride | null,
|
|
75
|
+
rowProviderId: string | null,
|
|
76
|
+
rowModelId: string | null,
|
|
77
|
+
parentProviderId: string | null,
|
|
78
|
+
parentModelId: string | null,
|
|
79
|
+
executorModelId?: string | null,
|
|
80
|
+
): Promise<{ providerId: string; modelId: string }> {
|
|
81
|
+
if (rowProviderId && rowModelId) {
|
|
82
|
+
return { providerId: rowProviderId, modelId: rowModelId };
|
|
83
|
+
}
|
|
84
|
+
if (parentProviderId && parentModelId) {
|
|
85
|
+
return { providerId: parentProviderId, modelId: parentModelId };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const fallback = {
|
|
89
|
+
providerId: rowProviderId ?? parentProviderId ?? "",
|
|
90
|
+
modelId: rowModelId ?? parentModelId ?? "",
|
|
91
|
+
};
|
|
92
|
+
if (!modelOverride) return fallback;
|
|
93
|
+
|
|
94
|
+
const models = (await (await col<ModelDoc>("models")).scan({})).map((entry) => entry.doc);
|
|
95
|
+
const providers = new Map(
|
|
96
|
+
(await (await col<ProviderDoc>("providers")).scan({}))
|
|
97
|
+
.map((entry) => entry.doc)
|
|
98
|
+
.filter((provider) => provider.enabled && provider.active)
|
|
99
|
+
.map((provider) => [provider.id, provider]),
|
|
100
|
+
);
|
|
101
|
+
const compatible = (model: ModelDoc) => {
|
|
102
|
+
if (!model.enabled || !providers.has(model.provider_id)) return false;
|
|
103
|
+
const caps = parseCapabilities(model);
|
|
104
|
+
if (!modelOverride.required_capabilities.every((cap) => caps.includes(cap))) return false;
|
|
105
|
+
if (modelOverride.prefer_different_family && executorModelId) {
|
|
106
|
+
const currentFamily = executorModelId.split(/[/:]/)[0];
|
|
107
|
+
const candidateFamily = model.id.split(/[/:]/)[0];
|
|
108
|
+
if (currentFamily === candidateFamily) return false;
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const candidate = models.find(compatible);
|
|
114
|
+
return candidate ? { providerId: candidate.provider_id, modelId: candidate.id } : fallback;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function validateSkillIds(skillIds: string[]): Promise<string[]> {
|
|
118
|
+
const skills = await col<SkillDoc>("skills");
|
|
119
|
+
const valid: string[] = [];
|
|
120
|
+
for (const id of skillIds) {
|
|
121
|
+
const entry = await skills.get(id);
|
|
122
|
+
if (!entry?.doc.active) throw new Error(`Agent references missing or inactive skill: ${id}`);
|
|
123
|
+
valid.push(id);
|
|
124
|
+
}
|
|
125
|
+
return valid;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function acquireMcpLease(
|
|
129
|
+
serverId: string,
|
|
130
|
+
manager: MCPClientManager,
|
|
131
|
+
): Promise<{ serverId: string; serverName: string }> {
|
|
132
|
+
const entry = await (await col<McpServerDoc>("mcpServers")).get(serverId);
|
|
133
|
+
if (!entry?.doc.enabled) throw new Error(`MCP server is missing or disabled: ${serverId}`);
|
|
134
|
+
// Gateway initialization registers DB-backed MCP servers under their stable
|
|
135
|
+
// document id. The display name is only used in UI/tool labels.
|
|
136
|
+
const serverName = entry.doc.id;
|
|
137
|
+
const existing = mcpLeases.get(serverId);
|
|
138
|
+
if (existing) {
|
|
139
|
+
if (existing.timer) clearTimeout(existing.timer);
|
|
140
|
+
existing.timer = undefined;
|
|
141
|
+
existing.refs++;
|
|
142
|
+
return { serverId, serverName: existing.serverName };
|
|
143
|
+
}
|
|
144
|
+
await manager.connectServer(serverName);
|
|
145
|
+
mcpLeases.set(serverId, { refs: 1, serverName });
|
|
146
|
+
return { serverId, serverName };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function releaseMcpLease(serverId: string, manager: MCPClientManager): Promise<void> {
|
|
150
|
+
const lease = mcpLeases.get(serverId);
|
|
151
|
+
if (!lease) return;
|
|
152
|
+
lease.refs = Math.max(0, lease.refs - 1);
|
|
153
|
+
if (lease.refs > 0) return;
|
|
154
|
+
lease.timer = setTimeout(() => {
|
|
155
|
+
const current = mcpLeases.get(serverId);
|
|
156
|
+
if (!current || current.refs > 0) return;
|
|
157
|
+
void manager.disconnectServer(current.serverName)
|
|
158
|
+
.catch((err) => log.warn(`[delegation-runtime] MCP disconnect failed: ${(err as Error).message}`))
|
|
159
|
+
.finally(() => mcpLeases.delete(serverId));
|
|
160
|
+
}, MCP_IDLE_TTL_MS);
|
|
161
|
+
lease.timer.unref?.();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Prepares a delegation target for execution: expands its tool allowlist
|
|
166
|
+
* (when it has one — catalog agents do, plain agent_create workers use their
|
|
167
|
+
* stored tools_json as-is), validates skills, resolves the effective
|
|
168
|
+
* provider/model, and acquires any requested MCP leases.
|
|
169
|
+
*
|
|
170
|
+
* This never creates a new AgentDoc — the row already exists (seeded from
|
|
171
|
+
* the catalog, or created via agent_create).
|
|
172
|
+
* It does persist the resolved workspace/model back onto that row (same as
|
|
173
|
+
* the old materialization did) so agent-loop.ts picks them up when it loads
|
|
174
|
+
* the agent — which reintroduces a narrow, accepted race for the rare case
|
|
175
|
+
* of two concurrent delegations to the *same* catalog agent with different
|
|
176
|
+
* workspaces (catalog agents are global rows, not one-per-workspace anymore).
|
|
177
|
+
* `updateDoc`'s OCC retry keeps this safe (last-write-wins), never corrupt.
|
|
178
|
+
*/
|
|
179
|
+
export async function prepareDelegation(agentId: string, opts: PrepareDelegationOptions): Promise<PreparedDelegation> {
|
|
180
|
+
const agents = await col<AgentDoc>("agents");
|
|
181
|
+
const entry = await agents.get(agentId);
|
|
182
|
+
if (!entry?.doc.enabled) throw new Error(`Agent not found or disabled: ${agentId}`);
|
|
183
|
+
const agentDoc = entry.doc;
|
|
184
|
+
|
|
185
|
+
const toolNames = agentDoc.tool_allowlist_json
|
|
186
|
+
? expandToolAllowlist(JSON.parse(agentDoc.tool_allowlist_json))
|
|
187
|
+
: (agentDoc.tools_json ? JSON.parse(agentDoc.tools_json) : []);
|
|
188
|
+
|
|
189
|
+
const skillIds = agentDoc.skills_json ? await validateSkillIds(JSON.parse(agentDoc.skills_json)) : [];
|
|
190
|
+
|
|
191
|
+
const requestedMcp: string[] = agentDoc.mcp_server_ids_json ? JSON.parse(agentDoc.mcp_server_ids_json) : [];
|
|
192
|
+
if (requestedMcp.length > 0 && !opts.mcpManager) throw new Error("MCP servers requested but MCP manager is unavailable");
|
|
193
|
+
|
|
194
|
+
const acquired: string[] = [];
|
|
195
|
+
try {
|
|
196
|
+
for (const serverId of requestedMcp) {
|
|
197
|
+
await acquireMcpLease(serverId, opts.mcpManager!);
|
|
198
|
+
acquired.push(serverId);
|
|
199
|
+
}
|
|
200
|
+
} catch (err) {
|
|
201
|
+
await Promise.all(acquired.map((id) => releaseMcpLease(id, opts.mcpManager!)));
|
|
202
|
+
throw err;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const modelOverride: AgentModelOverride | null = agentDoc.model_override_json
|
|
206
|
+
? JSON.parse(agentDoc.model_override_json)
|
|
207
|
+
: null;
|
|
208
|
+
const resolved = await resolveAgentModel(
|
|
209
|
+
modelOverride,
|
|
210
|
+
fromIndexable(agentDoc.provider_id),
|
|
211
|
+
fromIndexable(agentDoc.model_id),
|
|
212
|
+
opts.parentProviderId ?? null,
|
|
213
|
+
opts.parentModelId ?? null,
|
|
214
|
+
opts.executorModelId ?? opts.parentModelId ?? null,
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
await updateDoc<AgentDoc>("agents", agentId, {
|
|
218
|
+
workspace: opts.workspace,
|
|
219
|
+
provider_id: toIndexable(resolved.providerId || null),
|
|
220
|
+
model_id: toIndexable(resolved.modelId || null),
|
|
221
|
+
active_mcp_json: JSON.stringify(requestedMcp),
|
|
222
|
+
updated_at: Date.now(),
|
|
223
|
+
}).catch((err) => log.warn(`[prepareDelegation] Failed to persist delegation context for ${agentId}: ${(err as Error).message}`));
|
|
224
|
+
|
|
225
|
+
let released = false;
|
|
226
|
+
return {
|
|
227
|
+
agent: agentDoc,
|
|
228
|
+
toolNames,
|
|
229
|
+
skillIds,
|
|
230
|
+
mcpServerIds: requestedMcp,
|
|
231
|
+
providerId: resolved.providerId,
|
|
232
|
+
modelId: resolved.modelId,
|
|
233
|
+
release: async () => {
|
|
234
|
+
if (released) return;
|
|
235
|
+
released = true;
|
|
236
|
+
if (opts.mcpManager) {
|
|
237
|
+
await Promise.all(requestedMcp.map((id) => releaseMcpLease(id, opts.mcpManager!)));
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|