@johpaz/hive-agents 1.0.4 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/hive.js +88127 -103024
- package/dist/tool-worker.js +13243 -17002
- package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
- package/dist/ui/assets/AgentCreateForm-DXkjtXaS.js +1 -0
- package/dist/ui/assets/AgentDetailPage-DUIX_cuQ.js +1 -0
- package/dist/ui/assets/AgentNewPage-SNXz2wik.js +1 -0
- package/dist/ui/assets/AgentsPage-CGsdgx5F.js +10 -0
- package/dist/ui/assets/{ApiClientPage-6a6KFwsQ.js → ApiClientPage-MNMjfSDs.js} +2 -2
- package/dist/ui/assets/ChannelsPage-BEwxWUcE.js +8 -0
- package/dist/ui/assets/DashboardPage-D6cRFKWW.js +6 -0
- package/dist/ui/assets/LoginPage-ByYmIa2p.js +1 -0
- package/dist/ui/assets/LogsPage-Bmk9rohg.js +1 -0
- package/dist/ui/assets/MeetingPage-Dm97Mbiw.js +1 -0
- package/dist/ui/assets/ModelSelector-gubC8j_Q.js +1 -0
- package/dist/ui/assets/NotFound-PUg3gEO0.js +1 -0
- package/dist/ui/assets/{Office3DPage-C3SIzd2H.css → Office3DPage-31AMJ-LN.css} +1 -1
- package/dist/ui/assets/Office3DPage-Bfi-S2kG.js +727 -0
- package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +1 -0
- package/dist/ui/assets/RecoverPage-YY2QU-qh.js +1 -0
- package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
- package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
- package/dist/ui/assets/Vignette-BcPWkNhm.js +4302 -0
- package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -0
- package/dist/ui/assets/VoicePage-uLWdtoD4.css +1 -0
- package/dist/ui/assets/WebChatPage-B61ZDjQ8.js +29 -0
- package/dist/ui/assets/agentCapabilities-PfTEVxG1.js +1 -0
- package/dist/ui/assets/alert-CjiX20jI.js +1 -0
- package/dist/ui/assets/badge-B5AKge1b.js +1 -0
- package/dist/ui/assets/bia-4LFKOyxR.webp +0 -0
- package/dist/ui/assets/bia-BFcUpOu3.glb +0 -0
- package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
- package/dist/ui/assets/conversationsStore-BlwA3yd2.js +1 -0
- package/dist/ui/assets/dialog-B04KpdNt.js +1 -0
- package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
- package/dist/ui/assets/{dist-js-CLxM1g2B.js → dist-js-q7C_AB0j.js} +1 -1
- package/dist/ui/assets/index-ByTufXPh.css +2 -0
- package/dist/ui/assets/index-DKJFLL3a.js +116 -0
- package/dist/ui/assets/label-D_fvqJyD.js +1 -0
- package/dist/ui/assets/lock-3IApZyVy.js +1 -0
- package/dist/ui/assets/{square-psq7k_CB.js → mic-CpDU_2as.js} +1 -1
- package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
- package/dist/ui/assets/rotate-ccw-LoM1AuqK.js +1 -0
- package/dist/ui/assets/scroll-area-CbH8FOo8.js +1 -0
- package/dist/ui/assets/select-v_3QBYrD.js +1 -0
- package/dist/ui/assets/slider-DXS4h1LB.js +1 -0
- package/dist/ui/assets/square-D5zdNkAY.js +1 -0
- package/dist/ui/assets/switch-ndx8VCpm.js +1 -0
- package/dist/ui/assets/tabs-epu-3Tl4.js +1 -0
- package/dist/ui/assets/textarea-BgZJFZTX.js +1 -0
- package/dist/ui/assets/useAudioDevices-B2stUHvr.js +41 -0
- package/dist/ui/assets/useHiveAgentsModelLoad-B4EjHvj4.js +1 -0
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
- package/dist/ui/assets/{useProviders-CiLSc05q.js → useProviders-B1NS24md.js} +1 -1
- package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
- package/dist/ui/assets/volume-2-EaA0JRvD.js +1 -0
- package/dist/ui/assets/volume-x-CROXNMGT.js +1 -0
- package/dist/ui/index.html +6 -6
- package/package.json +10 -6
- package/packages/cli/src/adapters/config.ts +11 -3
- package/packages/cli/src/commands/causal.ts +1 -1
- package/packages/cli/src/commands/doctor.ts +101 -46
- package/packages/cli/src/commands/onboard.ts +4 -2
- package/packages/core/src/agent/agent-catalog.ts +47 -47
- package/packages/core/src/agent/agent-loop.ts +67 -14
- package/packages/core/src/agent/capability-search.ts +2 -1
- package/packages/core/src/agent/compaction.ts +19 -7
- package/packages/core/src/agent/context-compiler.ts +166 -28
- package/packages/core/src/agent/conversation-store.ts +26 -2
- package/packages/core/src/agent/goal-runner.ts +2 -2
- package/packages/core/src/agent/jev-decisions.ts +148 -0
- package/packages/core/src/agent/jev-planner.ts +293 -0
- package/packages/core/src/agent/llm-client.ts +29 -7
- package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
- package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
- package/packages/core/src/agent/prompt-builder.ts +1 -1
- package/packages/core/src/agent/realtime-providers/gemini-live.ts +233 -0
- package/packages/core/src/agent/realtime-providers/index.ts +29 -0
- package/packages/core/src/agent/realtime-providers/interface.ts +108 -0
- package/packages/core/src/agent/skill-selector.ts +5 -3
- package/packages/core/src/agent/thread-id.ts +71 -0
- package/packages/core/src/agent/thread-store.ts +230 -0
- package/packages/core/src/agent/tool-selector.ts +2 -0
- package/packages/core/src/agent/tracer.ts +2 -0
- package/packages/core/src/canvas/canvas-manager.ts +145 -27
- package/packages/core/src/canvas/emitter.ts +24 -0
- package/packages/core/src/channels/telegram.ts +19 -1
- package/packages/core/src/channels/webchat.ts +47 -45
- package/packages/core/src/config/loader.ts +9 -6
- package/packages/core/src/events/tool-narration.ts +1 -0
- package/packages/core/src/gateway/channel-notify.ts +24 -5
- package/packages/core/src/gateway/delegation-groups.ts +5 -5
- package/packages/core/src/gateway/delegation-notify.ts +34 -5
- package/packages/core/src/gateway/durable-queue.ts +22 -0
- package/packages/core/src/gateway/failure-notify.ts +8 -2
- package/packages/core/src/gateway/initializer.ts +17 -10
- package/packages/core/src/gateway/job-executors.ts +3 -3
- package/packages/core/src/gateway/realtime/bridge-tools.ts +470 -0
- package/packages/core/src/gateway/realtime/index.ts +305 -0
- package/packages/core/src/gateway/realtime/prompt.ts +182 -0
- package/packages/core/src/gateway/realtime/protocol.ts +60 -0
- package/packages/core/src/gateway/realtime/voice-session.ts +442 -0
- package/packages/core/src/gateway/resolver.ts +31 -4
- package/packages/core/src/gateway/routes/artifacts.ts +13 -0
- package/packages/core/src/gateway/routes/chat.ts +20 -4
- package/packages/core/src/gateway/routes/conversations.ts +121 -0
- package/packages/core/src/gateway/routes/providers.ts +16 -1
- package/packages/core/src/gateway/routes/setup.ts +25 -14
- package/packages/core/src/gateway/routes/system.ts +4 -2
- package/packages/core/src/gateway/routes/tts-local.ts +2 -1
- package/packages/core/src/gateway/server.ts +171 -13
- package/packages/core/src/gateway/slash-commands.ts +48 -10
- package/packages/core/src/gateway/tts/src/server.ts +2 -1
- package/packages/core/src/gateway/webchat-turn.ts +68 -10
- package/packages/core/src/index.ts +2 -0
- package/packages/core/src/scheduler/CronScheduler.ts +20 -8
- package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
- package/packages/core/src/scheduler/cron/expression.ts +165 -0
- package/packages/core/src/scheduler/cron/index.ts +10 -0
- package/packages/core/src/scheduler/cron/job.ts +340 -0
- package/packages/core/src/scheduler/cron/next-run.ts +121 -0
- package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
- package/packages/core/src/scheduler/integration.ts +16 -5
- package/packages/core/src/scheduler/types.ts +3 -18
- package/packages/core/src/storage/bootstrap.ts +23 -0
- package/packages/core/src/storage/collections.ts +38 -1
- package/packages/core/src/storage/crypto.ts +23 -12
- package/packages/core/src/storage/onboarding.ts +39 -39
- package/packages/core/src/storage/reconcile.ts +6 -1
- package/packages/core/src/storage/seed.ts +82 -8
- package/packages/core/src/storage/usage.ts +53 -1
- package/packages/core/src/tool-runtime/index.ts +19 -1
- package/packages/core/src/tools/a2ui/index.ts +65 -1
- package/packages/core/src/tools/agents/get-available-models.ts +3 -1
- package/packages/core/src/tools/core/index.ts +39 -4
- package/packages/core/src/tools/cron/index.ts +4 -4
- package/packages/core/src/tools/index.ts +2 -1
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
- package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
- package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
- package/packages/core/src/tools/web/browser-backend.ts +141 -44
- package/packages/core/src/tools/web/browser-click.ts +2 -2
- package/packages/core/src/tools/web/browser-extract.ts +2 -2
- package/packages/core/src/tools/web/browser-navigate.ts +2 -2
- package/packages/core/src/tools/web/browser-screenshot.ts +12 -5
- package/packages/core/src/tools/web/browser-script.ts +2 -2
- package/packages/core/src/tools/web/browser-service.ts +63 -384
- package/packages/core/src/tools/web/browser-session.ts +125 -0
- package/packages/core/src/tools/web/browser-type.ts +2 -2
- package/packages/core/src/tools/web/browser-wait.ts +2 -2
- package/packages/core/src/tools/web/computer-use.ts +553 -0
- package/packages/core/src/tools/web/index.ts +5 -1
- package/packages/core/src/tools/web/webview-backend.ts +559 -21
- package/packages/core/src/utils/port.ts +33 -0
- package/packages/core/src/voice/index.ts +2 -1
- package/packages/mcp/src/config.ts +2 -1
- package/packages/mcp/src/manager.ts +9 -0
- package/packages/mcp/src/transports/index.ts +42 -1
- package/packages/mcp/src/transports/sse.ts +11 -5
- package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
- package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
- package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
- package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
- package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
- package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
- package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
- package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
- package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
- package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
- package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
- package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
- package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
- package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
- package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
- package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
- package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
- package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
- package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
- package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
- package/packages/skills/src/bundled-data.generated.ts +837 -783
- package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +0 -8
- package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +0 -1
- package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +0 -1
- package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +0 -1
- package/dist/ui/assets/AgentsPage-YZrDmgNI.js +0 -10
- package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +0 -8
- package/dist/ui/assets/DashboardPage-B9r0sc0F.js +0 -6
- package/dist/ui/assets/LoginPage-BkAAX_tu.js +0 -1
- package/dist/ui/assets/LogsPage-8-H1OJs3.js +0 -1
- package/dist/ui/assets/MeetingPage-14JoQo71.js +0 -1
- package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +0 -1
- package/dist/ui/assets/NotFound-B06kVW7N.js +0 -1
- package/dist/ui/assets/Office3DPage-BMUZWkFS.js +0 -4614
- package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +0 -1
- package/dist/ui/assets/RecoverPage-D1o8yxNz.js +0 -1
- package/dist/ui/assets/SettingsPage-GP8UwQIL.js +0 -9
- package/dist/ui/assets/SetupPage-B_gU1YQU.js +0 -1
- package/dist/ui/assets/WebChatPage-Yahufnth.js +0 -29
- package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +0 -1
- package/dist/ui/assets/alert-DChoEVJw.js +0 -1
- package/dist/ui/assets/badge-uRjRSt86.js +0 -1
- package/dist/ui/assets/card-DwQizslL.js +0 -1
- package/dist/ui/assets/dialog--mljnfAi.js +0 -1
- package/dist/ui/assets/dist-js-B0s_TDau.js +0 -1
- package/dist/ui/assets/index-BHHUQZJd.js +0 -116
- package/dist/ui/assets/index-CEFhf4dF.css +0 -2
- package/dist/ui/assets/label-BceoUB2w.js +0 -1
- package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
- package/dist/ui/assets/scroll-area-DMEaZZUp.js +0 -1
- package/dist/ui/assets/select-BBEBtcLm.js +0 -1
- package/dist/ui/assets/slider-DcmBdvYD.js +0 -1
- package/dist/ui/assets/switch-CgiDezVR.js +0 -1
- package/dist/ui/assets/tabs-gUXIjjZv.js +0 -1
- package/dist/ui/assets/textarea-DedxQYBx.js +0 -1
- package/dist/ui/assets/useHiveAgentsModelLoad-C7bhWPDG.js +0 -1
- package/dist/ui/assets/useOfficeModel-BAFasrg8.js +0 -1
- package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
- package/dist/ui/assets/volume-x-BDlMCDYT.js +0 -1
- /package/dist/ui/assets/{core-Sjunb8Z1.js → core-B_5cyOSV.js} +0 -0
- /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
- /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
- /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
- /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BZj_2-jf.js → gateway-url-BALS_wVh.js} +0 -0
- /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
- /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
- /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
- /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
- /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
- /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
- /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
- /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
- /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
- /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
- /package/dist/ui/assets/{search-ykSx-zZU.js → search-BMwCI-pX.js} +0 -0
- /package/dist/ui/assets/{send-DAhlz2i9.js → send-D6fgWV7m.js} +0 -0
- /package/dist/ui/assets/{settings-DL0REysC.js → settings-qV3kVkeG.js} +0 -0
- /package/dist/ui/assets/{shield-BPZZhjCT.js → shield-CIarwBvx.js} +0 -0
- /package/dist/ui/assets/{sparkles-BViXTAh7.js → sparkles-DVvY6jDT.js} +0 -0
- /package/dist/ui/assets/{terminal-CzxPKG-h.js → terminal-BEcTK780.js} +0 -0
- /package/dist/ui/assets/{trash-2-SgYCWiVk.js → trash-2-D6oziYAK.js} +0 -0
- /package/dist/ui/assets/{utils-SGUggNJc.js → utils-DEmd_M8c.js} +0 -0
- /package/dist/ui/assets/{vendor-router-Dsg8fxNQ.js → vendor-router-DP84b3LQ.js} +0 -0
- /package/dist/ui/assets/{wifi-CyPHteEm.js → wifi-BUJuOcgP.js} +0 -0
- /package/dist/ui/assets/{zap-OVVrfEHr.js → zap-DSoX9NDk.js} +0 -0
|
@@ -43,6 +43,7 @@ import { getHiveDb } from "../storage/hivedb"
|
|
|
43
43
|
import { listCatalogAgents, renderAgentRoutingCatalog } from "./catalog-selector"
|
|
44
44
|
import { expandToolAllowlist } from "./delegation-runtime"
|
|
45
45
|
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
46
|
+
import { describeSwarmCapabilities, planJevContext, renderSpecialistLine } from "./jev-planner"
|
|
46
47
|
|
|
47
48
|
const log = logger.child("context-compiler")
|
|
48
49
|
|
|
@@ -89,6 +90,8 @@ export interface CompiledContext {
|
|
|
89
90
|
tools: LLMToolDef[]
|
|
90
91
|
allTools: ContextTool[]
|
|
91
92
|
skills: SkillDescriptor[] // Skills loaded (minimal + discovered)
|
|
93
|
+
/** Jev's context plan, for the caller to publish once it knows the agent's resolved model. */
|
|
94
|
+
jevDecision?: { summary: string; savedTokens: number; latencyMs: number; costUsd: number; recommendedAgentId: string | null; mcpOff: string[] }
|
|
92
95
|
}
|
|
93
96
|
|
|
94
97
|
// ─── G9 causal context (buildAgentContext) ────────────────────────────────
|
|
@@ -146,6 +149,42 @@ function fromAgentDoc(doc: AgentDoc) {
|
|
|
146
149
|
}
|
|
147
150
|
}
|
|
148
151
|
|
|
152
|
+
// ─── History budget ─────────────────────────────────────────────────────────
|
|
153
|
+
|
|
154
|
+
const messageTokens = (m: LLMMessage) => estimateTokens(typeof m.content === "string" ? m.content : JSON.stringify(m.content))
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Drops the oldest history until it fits `budget` tokens. The history used to
|
|
158
|
+
* go out whole whatever its size, and a provider that truncates (Ollama at
|
|
159
|
+
* num_ctx) cut it blindly instead. The last `minKeep` messages — the current
|
|
160
|
+
* turn and the exchange it refers to — always stay, even over budget: a window
|
|
161
|
+
* too small for them is better served by a truncated prompt than by an answer
|
|
162
|
+
* with no conversation at all. A single oversized newest message is trimmed
|
|
163
|
+
* from the middle, keeping its start and its end.
|
|
164
|
+
*/
|
|
165
|
+
export function fitMessagesToBudget(messages: LLMMessage[], budget: number, minKeep = 4): LLMMessage[] {
|
|
166
|
+
let total = messages.reduce((sum, m) => sum + messageTokens(m), 0)
|
|
167
|
+
if (total <= budget || messages.length === 0) return messages
|
|
168
|
+
const kept = [...messages]
|
|
169
|
+
while (kept.length > Math.max(1, minKeep) && total > budget) total -= messageTokens(kept.shift()!)
|
|
170
|
+
// History must open on a user turn: providers reject or drop a leading model turn.
|
|
171
|
+
while (kept.length > 1 && kept[0].role !== "user") total -= messageTokens(kept.shift()!)
|
|
172
|
+
const last = kept[kept.length - 1]
|
|
173
|
+
if (total > budget && typeof last.content === "string") {
|
|
174
|
+
const maxChars = Math.max(400, Math.floor(Math.max(budget, 100) * 4))
|
|
175
|
+
if (last.content.length > maxChars) {
|
|
176
|
+
const half = Math.floor(maxChars / 2)
|
|
177
|
+
kept[kept.length - 1] = {
|
|
178
|
+
...last,
|
|
179
|
+
content: `${last.content.slice(0, half)}\n[… recortado para caber en la ventana del modelo …]\n${last.content.slice(-half)}`,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (kept.length === messages.length && kept[kept.length - 1] === last) return messages
|
|
184
|
+
log.info(`[context-compiler] History trimmed to fit the window: ${messages.length} → ${kept.length} messages (budget ${budget} tokens)`)
|
|
185
|
+
return kept
|
|
186
|
+
}
|
|
187
|
+
|
|
149
188
|
// ─── Main compiler ─────────────────────────────────────────────────────────
|
|
150
189
|
|
|
151
190
|
/**
|
|
@@ -166,6 +205,13 @@ export async function compileContext(opts: {
|
|
|
166
205
|
mcpManager?: MCPClientManager | null
|
|
167
206
|
/** G9 causal stream id for this invocation (agent-loop.ts's causalStreamId). */
|
|
168
207
|
causalStreamId?: string
|
|
208
|
+
/** A resumed run restores the exact previously selected prompt and loadout. */
|
|
209
|
+
skipJev?: boolean
|
|
210
|
+
/**
|
|
211
|
+
* The window the provider will really read (resolveProviderConfig): the
|
|
212
|
+
* smaller of the model's and, for Ollama, num_ctx. Falls back to the model row.
|
|
213
|
+
*/
|
|
214
|
+
contextWindow?: number
|
|
169
215
|
}): Promise<CompiledContext> {
|
|
170
216
|
const { agentId, threadId, mcpManager, userMessage, isolated, taskContext } = opts
|
|
171
217
|
|
|
@@ -211,8 +257,8 @@ export async function compileContext(opts: {
|
|
|
211
257
|
log.info(`[context-compiler] [STEP-1] ✅ Compiling for ${isWorker ? 'worker' : 'coordinator'} agent=${agent.name}`)
|
|
212
258
|
|
|
213
259
|
// Load model's context window for compaction decisions
|
|
214
|
-
let modelContextWindow = DEFAULT_CONTEXT_WINDOW
|
|
215
|
-
if (agent.model_id) {
|
|
260
|
+
let modelContextWindow = opts.contextWindow ?? DEFAULT_CONTEXT_WINDOW
|
|
261
|
+
if (!opts.contextWindow && agent.model_id) {
|
|
216
262
|
try {
|
|
217
263
|
const modelsCol = await col<ModelDoc>("models")
|
|
218
264
|
// Id completo: el recorte del primer segmento fallaba para todo modelo
|
|
@@ -505,7 +551,45 @@ export async function compileContext(opts: {
|
|
|
505
551
|
// or — on a context-overflow retry that keeps only the LAST system message
|
|
506
552
|
// (openai-compat-base.ts) — silently replaces the real prompt. The summary
|
|
507
553
|
// lives in `systemPrompt` instead (see conversationSummarySection below).
|
|
508
|
-
|
|
554
|
+
let messages: LLMMessage[] = toAPIMessages(recentMessages)
|
|
555
|
+
let selectedSkills = allSkills
|
|
556
|
+
let jevAgentId: string | null = null
|
|
557
|
+
let jevAgentMcpOff: string[] = []
|
|
558
|
+
let omittedMessageIds: number[] = []
|
|
559
|
+
let omittedScratchpadKeys: string[] = []
|
|
560
|
+
const objectiveSource = taskContext ?? userMessage
|
|
561
|
+
const objective = typeof objectiveSource === "string" ? objectiveSource
|
|
562
|
+
: objectiveSource.filter((p: ContentPart) => p.type === "text").map((p: ContentPart) => (p as { text: string }).text).join("\n")
|
|
563
|
+
const playbookRules = (await selectPlaybookRules(objective)).filter((rule) => {
|
|
564
|
+
if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
|
|
565
|
+
return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
|
|
566
|
+
})
|
|
567
|
+
const swarm = opts.skipJev ? undefined : await describeSwarmCapabilities(effectiveMcpManager, { includeSpecialists: !isWorker })
|
|
568
|
+
.catch((err) => { log.warn(`[context-compiler] Swarm capability map failed: ${(err as Error).message}`); return undefined })
|
|
569
|
+
const jevPlan = opts.skipJev ? null : await planJevContext({
|
|
570
|
+
objective, messages, tools: toolsForLLM, allTools, skills: allSkills, scratchpadNotes, playbookRules, isWorker, swarm,
|
|
571
|
+
}).catch((err) => { log.warn(`[context-compiler] Jev planning failed: ${(err as Error).message}`); return null })
|
|
572
|
+
// Characters the classic path would have sent minus what Jev's plan sends,
|
|
573
|
+
// accumulated section by section; the office shows it as estimated savings.
|
|
574
|
+
let jevSavedChars = 0
|
|
575
|
+
const classicToolCount = toolsForLLM.length
|
|
576
|
+
if (jevPlan) {
|
|
577
|
+
jevSavedChars += JSON.stringify(messages).length - JSON.stringify(jevPlan.messages).length
|
|
578
|
+
jevSavedChars += JSON.stringify(toolsForLLM).length
|
|
579
|
+
messages = jevPlan.messages
|
|
580
|
+
toolsForLLM = jevPlan.tools
|
|
581
|
+
selectedSkills = allSkills.filter(s => minimalSkills.some(m => m.id === s.id) || jevPlan.selectedSkillNames.includes(s.name))
|
|
582
|
+
jevAgentId = jevPlan.agentId
|
|
583
|
+
jevAgentMcpOff = jevPlan.agentMcpOff
|
|
584
|
+
omittedMessageIds = recentMessages.filter((_, i) => !jevPlan.selectedMessageIds.includes(i)).map(row => row.id)
|
|
585
|
+
omittedScratchpadKeys = scratchpadNotes.filter(note => !jevPlan.selectedScratchpadKeys.includes(note.key)).map(note => note.key)
|
|
586
|
+
if (!isWorker && (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) && !toolsForLLM.some(t => t.function.name === "conversation_read")) {
|
|
587
|
+
const reader = allTools.find(t => t.name === "conversation_read")
|
|
588
|
+
if (reader) toolsForLLM.push({ type: "function", function: { name: reader.name, description: reader.description, parameters: reader.parameters } })
|
|
589
|
+
}
|
|
590
|
+
jevSavedChars -= JSON.stringify(toolsForLLM).length
|
|
591
|
+
log.info(`[context-compiler] Jev selected messages=${jevPlan.selectedMessageIds.join(",")} tools=${toolsForLLM.map(t => t.function.name).join(",")} skills=${selectedSkills.map(s => s.name).join(",")} agent=${jevAgentId ?? "coordinator"}`)
|
|
592
|
+
}
|
|
509
593
|
|
|
510
594
|
// [STEP-10] STRATEGY 4: ISOLATE — Build context based on agent role
|
|
511
595
|
log.info(`[context-compiler] [STEP-10] Building system prompt...`)
|
|
@@ -534,33 +618,52 @@ export async function compileContext(opts: {
|
|
|
534
618
|
// budget, so a summary appended last would be the first thing silently
|
|
535
619
|
// dropped on an oversized prompt.
|
|
536
620
|
systemPrompt += conversationSummarySection
|
|
621
|
+
if (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) {
|
|
622
|
+
const recoverable = `\n\n# CONTEXTO RECUPERABLE\nMensajes previos omitidos: ${omittedMessageIds.join(", ") || "ninguno"}. Notas omitidas: ${omittedScratchpadKeys.join(", ") || "ninguna"}. Si necesitas un dato de ellos, usa conversation_read con message_ids, note_keys o query antes de asumir que falta información.\n`
|
|
623
|
+
systemPrompt += recoverable
|
|
624
|
+
jevSavedChars -= recoverable.length
|
|
625
|
+
}
|
|
537
626
|
|
|
538
627
|
// Only the live roster goes here — how to delegate, fan-out/fan-in and the
|
|
539
628
|
// execution-truth rules are static doctrine and live in the coordinator's
|
|
540
629
|
// stored prompt (storage/onboarding.ts), not duplicated per turn.
|
|
541
630
|
if (!isWorker) {
|
|
542
|
-
const
|
|
543
|
-
|
|
631
|
+
const catalogAgents = await listCatalogAgents()
|
|
632
|
+
const fullCatalog = `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${renderAgentRoutingCatalog(catalogAgents)}\n`
|
|
633
|
+
if (jevPlan) {
|
|
634
|
+
// Ids, names and MCP state only: without them the coordinator spent
|
|
635
|
+
// iterations on agent_find just to learn who exists and what is
|
|
636
|
+
// connected. Descriptions stay behind agent_find.
|
|
637
|
+
const roster = swarm?.specialists.length
|
|
638
|
+
? swarm.specialists.map(renderSpecialistLine).join("\n")
|
|
639
|
+
: catalogAgents.map(a => `- ${a.id} (${a.name})`).join("\n")
|
|
640
|
+
let rosterSection = roster ? `\n\n# COLMENA DE AGENTES\nWorkers disponibles (usa agent_find solo si necesitas su descripción). Un MCP "apagado" no está disponible; "disponible" se conecta al primer uso:\n${roster}\n` : ""
|
|
641
|
+
if (jevAgentId && jevAgentMcpOff.length > 0) {
|
|
642
|
+
// Turning a server on starts processes and uses credentials: that is
|
|
643
|
+
// the user's call, so the coordinator asks instead of delegating.
|
|
644
|
+
rosterSection += `\n\n# ESPECIALISTA RECOMENDADO — MCP APAGADO\nJev seleccionó ${jevAgentId} para esta tarea, pero depende de ${jevAgentMcpOff.length === 1 ? "el servidor MCP" : "los servidores MCP"} ${jevAgentMcpOff.join(", ")}, que está${jevAgentMcpOff.length === 1 ? "" : "n"} apagado${jevAgentMcpOff.length === 1 ? "" : "s"}. No lo delegues todavía: dile al usuario que para hacerlo hace falta encender ${jevAgentMcpOff.join(", ")} en Ajustes → Entorno → MCP Servers y que continúas en cuanto quede conectado. Si una parte se puede resolver sin ese MCP, ofrécela.\n`
|
|
645
|
+
} else if (jevAgentId) {
|
|
646
|
+
rosterSection += `\n\n# ESPECIALISTA RECOMENDADO\nJev seleccionó ${jevAgentId} para una subtarea acotada. Delega con task_delegate cuando puedas formular objetivo y criterios verificables.\n`
|
|
647
|
+
}
|
|
648
|
+
systemPrompt += rosterSection
|
|
649
|
+
jevSavedChars += fullCatalog.length - rosterSection.length
|
|
650
|
+
} else {
|
|
651
|
+
systemPrompt += fullCatalog
|
|
652
|
+
}
|
|
544
653
|
}
|
|
545
654
|
|
|
546
|
-
const
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
? playbookInput.filter((part) => part.type === "text").map((part) => (part as any).text).join("\n")
|
|
551
|
-
: String(playbookInput)
|
|
552
|
-
const playbookRules = (await selectPlaybookRules(playbookText)).filter((rule) => {
|
|
553
|
-
if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
|
|
554
|
-
return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
|
|
555
|
-
})
|
|
556
|
-
if (playbookRules.length > 0) {
|
|
557
|
-
systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${playbookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
|
|
655
|
+
const selectedPlaybookRules = jevPlan ? playbookRules.filter(rule => jevPlan.selectedPlaybookIds.includes(rule.id)) : playbookRules
|
|
656
|
+
for (const rule of playbookRules) if (!selectedPlaybookRules.includes(rule)) jevSavedChars += rule.rule.length + 3
|
|
657
|
+
if (selectedPlaybookRules.length > 0) {
|
|
658
|
+
systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${selectedPlaybookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
|
|
558
659
|
}
|
|
559
660
|
|
|
560
661
|
// Inject scratchpad (Strategy: WRITE) — usando TOON para ahorro de tokens
|
|
561
|
-
|
|
662
|
+
const selectedScratchpadNotes = jevPlan ? scratchpadNotes.filter(note => jevPlan.selectedScratchpadKeys.includes(note.key)) : scratchpadNotes
|
|
663
|
+
for (const note of scratchpadNotes) if (!selectedScratchpadNotes.includes(note)) jevSavedChars += note.key.length + note.value.length + 4
|
|
664
|
+
if (selectedScratchpadNotes.length > 0) {
|
|
562
665
|
const scratchpadData: Record<string, string> = {}
|
|
563
|
-
for (const n of
|
|
666
|
+
for (const n of selectedScratchpadNotes) {
|
|
564
667
|
scratchpadData[n.key] = n.value
|
|
565
668
|
}
|
|
566
669
|
// TOON comprime el formato clave-valor
|
|
@@ -596,7 +699,7 @@ export async function compileContext(opts: {
|
|
|
596
699
|
.filter((line): line is string => !!line)
|
|
597
700
|
|
|
598
701
|
if (causalLines.length > 0) {
|
|
599
|
-
systemPrompt += `\n\n# CAUSAL CONTEXT (decisiones y tool calls de este turno, previos a la compactación —
|
|
702
|
+
systemPrompt += `\n\n# CAUSAL CONTEXT (decisiones y tool calls de este turno, previos a la compactación — prioriza la conversación actual; úsalo solo para no repetir algo que ya funcionó o ya falló)\n${causalLines.join("\n")}\n`
|
|
600
703
|
log.info(`[context-compiler] [STEP-9d] ✅ Injected ${causalLines.length} causal context item(s)`)
|
|
601
704
|
}
|
|
602
705
|
} catch (err) {
|
|
@@ -616,10 +719,10 @@ export async function compileContext(opts: {
|
|
|
616
719
|
|
|
617
720
|
|
|
618
721
|
// Inject available skills (minimal + discovered)
|
|
619
|
-
if (
|
|
722
|
+
if (selectedSkills.length > 0) {
|
|
620
723
|
// Minimal skills: inject full body (always-loaded instructions)
|
|
621
724
|
const minimalNames = new Set(minimalSkills.map(s => s.name))
|
|
622
|
-
const minimalWithBody =
|
|
725
|
+
const minimalWithBody = selectedSkills.filter(s => minimalNames.has(s.name) && s.body)
|
|
623
726
|
if (minimalWithBody.length > 0) {
|
|
624
727
|
let minimalSection = `\n\n# SKILLS SIEMPRE ACTIVAS\n`
|
|
625
728
|
for (const skill of minimalWithBody) {
|
|
@@ -629,12 +732,23 @@ export async function compileContext(opts: {
|
|
|
629
732
|
}
|
|
630
733
|
|
|
631
734
|
// Discovered skills: list only (body arrives via agent-loop when tools are injected)
|
|
632
|
-
const discoveredOnly =
|
|
735
|
+
const discoveredOnly = selectedSkills.filter(s => !minimalNames.has(s.name))
|
|
736
|
+
if (jevPlan) {
|
|
737
|
+
// Classic lists every discovered skill in one line; Jev inlines the chosen bodies.
|
|
738
|
+
for (const skill of allSkills) {
|
|
739
|
+
if (minimalNames.has(skill.name)) continue
|
|
740
|
+
jevSavedChars += `- **${skill.name}**${skill.description ? ` — ${skill.description}` : ""}\n`.length
|
|
741
|
+
if (discoveredOnly.includes(skill)) jevSavedChars -= skill.body ? `\n## ${skill.name}\n${skill.body}\n`.length : 0
|
|
742
|
+
}
|
|
743
|
+
}
|
|
633
744
|
if (discoveredOnly.length > 0) {
|
|
634
745
|
let discoveredSection = `\n\n# SKILLS DESCUBIERTAS (relevantes para esta tarea)\n`
|
|
635
746
|
for (const skill of discoveredOnly) {
|
|
636
|
-
|
|
637
|
-
|
|
747
|
+
if (jevPlan && skill.body) discoveredSection += `\n## ${skill.name}\n${skill.body}\n`
|
|
748
|
+
else {
|
|
749
|
+
const desc = skill.description ? ` — ${skill.description}` : ""
|
|
750
|
+
discoveredSection += `- **${skill.name}**${desc}\n`
|
|
751
|
+
}
|
|
638
752
|
}
|
|
639
753
|
systemPrompt += discoveredSection
|
|
640
754
|
}
|
|
@@ -648,9 +762,9 @@ export async function compileContext(opts: {
|
|
|
648
762
|
if (isWorker && opts.taskContext && !isCatalogAgent) {
|
|
649
763
|
systemPrompt += `\n\n# HERRAMIENTAS DISPONIBLES\n` +
|
|
650
764
|
`Arrancas con herramientas básicas. Si tu tarea requiere herramientas adicionales (web_search, fs_read, browser_navigate, etc.):\n` +
|
|
651
|
-
`1.
|
|
765
|
+
`1. Usa \`search_knowledge(type="tools", query="<herramienta o tarea>")\` para encontrarlas.\n` +
|
|
652
766
|
`2. Las herramientas que encuentres estarán disponibles para usar inmediatamente.\n` +
|
|
653
|
-
`Si el coordinador te indicó herramientas específicas,
|
|
767
|
+
`Si el coordinador te indicó herramientas específicas, búscalas primero con search_knowledge antes de ejecutar tu tarea.\n` +
|
|
654
768
|
`\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task. Do not deviate.`
|
|
655
769
|
} else if (isWorker && opts.taskContext) {
|
|
656
770
|
systemPrompt += `\n\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task and return the required structured delivery.`
|
|
@@ -669,6 +783,16 @@ export async function compileContext(opts: {
|
|
|
669
783
|
}
|
|
670
784
|
|
|
671
785
|
const estimatedSystemTokens = estimateTokens(systemPrompt)
|
|
786
|
+
const estimatedToolTokensForBudget = toolsForLLM.reduce((sum, t) => sum + estimateTokens(JSON.stringify(t)), 0)
|
|
787
|
+
// History keeps at least a quarter of the window even when instructions and
|
|
788
|
+
// tools alone overflow it: otherwise a small model would lose the whole chat.
|
|
789
|
+
messages = fitMessagesToBudget(
|
|
790
|
+
messages,
|
|
791
|
+
Math.max(
|
|
792
|
+
Math.floor(modelContextWindow * 0.25),
|
|
793
|
+
Math.floor(modelContextWindow * COMPACT_RATIO) - estimatedSystemTokens - estimatedToolTokensForBudget,
|
|
794
|
+
),
|
|
795
|
+
)
|
|
672
796
|
const estimatedMsgTokens = messages.reduce((sum, m) => sum + estimateTokens(typeof m.content === 'string' ? m.content : JSON.stringify(m.content)), 0)
|
|
673
797
|
const estimatedToolTokens = toolsForLLM.reduce((sum, t) => sum + estimateTokens(JSON.stringify(t)), 0)
|
|
674
798
|
const estimatedTotal = estimatedSystemTokens + estimatedMsgTokens + estimatedToolTokens
|
|
@@ -682,13 +806,27 @@ export async function compileContext(opts: {
|
|
|
682
806
|
`total=${estimatedTotal}/${modelContextWindow} (${budgetPct}%)`
|
|
683
807
|
)
|
|
684
808
|
|
|
809
|
+
const jevDecision = jevPlan ? {
|
|
810
|
+
summary: [
|
|
811
|
+
`${jevPlan.selectedMessageIds.length}/${recentMessages.length} mensajes`,
|
|
812
|
+
`${toolsForLLM.length}/${classicToolCount} herramientas`,
|
|
813
|
+
`${selectedSkills.length}/${allSkills.length} skills`,
|
|
814
|
+
].join(" · "),
|
|
815
|
+
savedTokens: Math.round(jevSavedChars / 4),
|
|
816
|
+
latencyMs: jevPlan.decision.latencyMs,
|
|
817
|
+
costUsd: jevPlan.decision.costUsd,
|
|
818
|
+
recommendedAgentId: jevAgentId,
|
|
819
|
+
mcpOff: jevAgentMcpOff,
|
|
820
|
+
} : undefined
|
|
821
|
+
|
|
685
822
|
return {
|
|
686
823
|
systemPrompt,
|
|
687
824
|
conversationSummarySection,
|
|
688
825
|
messages,
|
|
689
826
|
tools: toolsForLLM,
|
|
690
827
|
allTools,
|
|
691
|
-
skills:
|
|
828
|
+
skills: selectedSkills,
|
|
829
|
+
jevDecision,
|
|
692
830
|
}
|
|
693
831
|
}
|
|
694
832
|
|
|
@@ -11,6 +11,7 @@ import { logger } from "../utils/logger"
|
|
|
11
11
|
import type { LLMMessage, ContentPart } from "./llm-client"
|
|
12
12
|
import { estimateTokens } from "../utils/toon"
|
|
13
13
|
import type { ConversationDoc, SummaryDoc, MessageSource } from "../storage/collections"
|
|
14
|
+
import { touchThread } from "./thread-store"
|
|
14
15
|
|
|
15
16
|
const log = logger.child("conv-store")
|
|
16
17
|
|
|
@@ -45,15 +46,28 @@ export interface StoredMessage {
|
|
|
45
46
|
// stays clean and the wording can evolve without a migration.
|
|
46
47
|
|
|
47
48
|
export const INTERNAL_SOURCES: ReadonlySet<string> =
|
|
48
|
-
new Set(["task_complete", "delegation_summary", "legacy_internal"])
|
|
49
|
+
new Set(["task_complete", "delegation_summary", "legacy_internal", "realtime_chat"])
|
|
49
50
|
|
|
50
51
|
export function isInternalSource(source: string | null | undefined): boolean {
|
|
51
52
|
return !!source && INTERNAL_SOURCES.has(source)
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
export function formatInternalEvent(source: string, content: string): string {
|
|
56
|
+
// La charla hablada sí salió del usuario, pero la sesión de voz ya la
|
|
57
|
+
// respondió: es contexto, no trabajo por hacer. Sin esta distinción el
|
|
58
|
+
// coordinador leía cada frase suelta de una llamada como un pedido nuevo y
|
|
59
|
+
// delegaba una tarea por cada una.
|
|
60
|
+
if (source === "realtime_chat") {
|
|
61
|
+
return `<hive:voice_context>\n` +
|
|
62
|
+
`Fragmento de una conversación hablada que la voz de Hive YA respondió en el momento. ` +
|
|
63
|
+
`Es contexto de lo que vinieron hablando, NO un pedido pendiente: no ejecutes ni delegues nada por esto. ` +
|
|
64
|
+
`El trabajo real llega siempre como un mensaje aparte y explícito.\n\n` +
|
|
65
|
+
`${content}\n` +
|
|
66
|
+
`</hive:voice_context>`
|
|
67
|
+
}
|
|
68
|
+
|
|
55
69
|
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.
|
|
70
|
+
`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. Responde al usuario de forma natural y breve.\n\n` +
|
|
57
71
|
`${content}\n` +
|
|
58
72
|
`</hive:internal_event>`
|
|
59
73
|
}
|
|
@@ -146,6 +160,16 @@ export async function addMessage(
|
|
|
146
160
|
bumpRollup("activityRollups", hour, { messageCount: 1 }).catch(() => {})
|
|
147
161
|
recentMessageTimestamps.push(now)
|
|
148
162
|
|
|
163
|
+
// Igual de opcional: el registro de conversaciones es el catálogo que alimenta la
|
|
164
|
+
// lista de la web (título, orden, contador). Se actualiza acá y no en cada llamador
|
|
165
|
+
// para que todo camino que escriba un mensaje —canales, webchat, API, voz— lo
|
|
166
|
+
// mantenga al día sin repetir la llamada.
|
|
167
|
+
touchThread(threadId, {
|
|
168
|
+
role,
|
|
169
|
+
text: textContent,
|
|
170
|
+
internal: isInternalSource(opts?.source),
|
|
171
|
+
}).catch(() => {})
|
|
172
|
+
|
|
149
173
|
return seq
|
|
150
174
|
}
|
|
151
175
|
|
|
@@ -166,7 +166,7 @@ async function judgeCriteriaWithLLM(
|
|
|
166
166
|
...clearOldToolResults(messages),
|
|
167
167
|
{
|
|
168
168
|
role: "user",
|
|
169
|
-
content: `
|
|
169
|
+
content: `Evalúa si cada uno de los siguientes criterios de aceptación se cumplió, basándote en la conversación anterior.\n\nCriterios:\n${criteria.map((c) => `- ${c.id}: ${c.description}`).join("\n")}\n\nResponde en JSON estricto, un resultado por criterio:\n{"results":[{"id":"...","met":true/false,"reason":"explicación breve"}]}`,
|
|
170
170
|
},
|
|
171
171
|
];
|
|
172
172
|
|
|
@@ -253,7 +253,7 @@ export async function verifyGoal(
|
|
|
253
253
|
...clearOldToolResults(messages),
|
|
254
254
|
{
|
|
255
255
|
role: "user",
|
|
256
|
-
content: `
|
|
256
|
+
content: `Evalúa si el siguiente objetivo ha sido cumplido basándote en la conversación anterior.\n\nObjetivo: "${goal}"\n\nResponde en JSON:\n{"met": true/false, "reason": "explicación breve"}`,
|
|
257
257
|
},
|
|
258
258
|
];
|
|
259
259
|
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/** Optional decision plane. Jev is never used through the chat completions API. */
|
|
2
|
+
import { col } from "../storage/hive"
|
|
3
|
+
import type { ProviderDoc } from "../storage/collections"
|
|
4
|
+
import { loadProviderApiKey } from "../storage/crypto"
|
|
5
|
+
import { recordJevDecision, recordUsage } from "../storage/usage"
|
|
6
|
+
import { catalogModelKey } from "../storage/model-id"
|
|
7
|
+
import { logger } from "../utils/logger"
|
|
8
|
+
import { emitCanvas, type CanvasJevDecision } from "../canvas/emitter"
|
|
9
|
+
|
|
10
|
+
const log = logger.child("jev-decisions")
|
|
11
|
+
export const JEV_MODEL = "typesafe/jev-1.13"
|
|
12
|
+
const ENDPOINT = "https://openrouter.ai/api/alpha/decisions"
|
|
13
|
+
const TIMEOUT_MS = 3000
|
|
14
|
+
const COOLDOWN_MS = 60_000
|
|
15
|
+
let failures = 0
|
|
16
|
+
let cooldownUntil = 0
|
|
17
|
+
let lastError: string | null = null
|
|
18
|
+
let lastSuccessAt: number | null = null
|
|
19
|
+
let decisionSequence = 0
|
|
20
|
+
/** Since gateway boot; the office shows them as the oracle's running contribution. */
|
|
21
|
+
const totals = { decisions: 0, savedTokens: 0, costUsd: 0 }
|
|
22
|
+
|
|
23
|
+
export type JevQuestion =
|
|
24
|
+
| { type: "choice"; instructions: string; criteria: Record<string, string> }
|
|
25
|
+
| { type: "noul"; instructions: string; criteria?: { true: string; false: string } }
|
|
26
|
+
|
|
27
|
+
export type JevAnswer =
|
|
28
|
+
| { type: "choice"; choice: string; confidence: number; probabilities: Record<string, number> }
|
|
29
|
+
| { type: "noul"; noul: number }
|
|
30
|
+
|
|
31
|
+
export interface JevResult {
|
|
32
|
+
answers: Record<string, JevAnswer>
|
|
33
|
+
inputTokens: number
|
|
34
|
+
costUsd: number
|
|
35
|
+
latencyMs: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function getJevKey(): Promise<string | null> {
|
|
39
|
+
const provider = await (await col<ProviderDoc>("providers")).get("openrouter")
|
|
40
|
+
if (!provider?.doc.enabled || !provider.doc.active) return null
|
|
41
|
+
return (await loadProviderApiKey("openrouter")) || process.env.OPENROUTER_API_KEY || null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface JevStatus {
|
|
45
|
+
state: "off" | "ready" | "fallback"
|
|
46
|
+
lastError: string | null
|
|
47
|
+
lastSuccessAt: number | null
|
|
48
|
+
totals: { decisions: number; savedTokens: number; costUsd: number }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function getJevStatus(): Promise<JevStatus> {
|
|
52
|
+
const key = await getJevKey().catch(() => null)
|
|
53
|
+
return {
|
|
54
|
+
state: !key ? "off" : Date.now() < cooldownUntil || lastError ? "fallback" : "ready",
|
|
55
|
+
lastError: key ? lastError : null,
|
|
56
|
+
lastSuccessAt: key ? lastSuccessAt : null,
|
|
57
|
+
totals: { ...totals },
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function broadcastStatus(): void {
|
|
62
|
+
getJevStatus().then(status => emitCanvas("canvas:jev_status", status)).catch(() => { /* best effort */ })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Publishes a served decision to the office and persists it for the dashboard.
|
|
67
|
+
* Callers estimate savings; Jev itself only answers questions. `provider`/`model`
|
|
68
|
+
* are the advised agent's main model, used to price the avoided tokens.
|
|
69
|
+
*/
|
|
70
|
+
export function emitJevDecision({ provider, model, ...decision }: Omit<CanvasJevDecision, "eventId" | "totals"> & { provider: string; model: string }): void {
|
|
71
|
+
recordJevDecision({ agentId: decision.agentId, provider, model, savedTokens: decision.savedTokens, costUsd: decision.costUsd })
|
|
72
|
+
totals.decisions++
|
|
73
|
+
totals.savedTokens += decision.savedTokens
|
|
74
|
+
totals.costUsd += decision.costUsd
|
|
75
|
+
emitCanvas("canvas:jev_decision", {
|
|
76
|
+
...decision,
|
|
77
|
+
eventId: `jev:${Date.now().toString(36)}:${++decisionSequence}`,
|
|
78
|
+
summary: decision.summary.slice(0, 160),
|
|
79
|
+
totals: { ...totals },
|
|
80
|
+
} satisfies CanvasJevDecision)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function resetJevStatus(): void {
|
|
84
|
+
failures = 0
|
|
85
|
+
cooldownUntil = 0
|
|
86
|
+
lastError = null
|
|
87
|
+
lastSuccessAt = null
|
|
88
|
+
broadcastStatus()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function askJev(
|
|
92
|
+
state: unknown,
|
|
93
|
+
questions: Record<string, JevQuestion>,
|
|
94
|
+
options: { fetcher?: typeof fetch; signal?: AbortSignal } = {},
|
|
95
|
+
): Promise<JevResult | null> {
|
|
96
|
+
const key = await getJevKey().catch(() => null)
|
|
97
|
+
if (!key || Date.now() < cooldownUntil || Object.keys(questions).length === 0) return null
|
|
98
|
+
const started = performance.now()
|
|
99
|
+
try {
|
|
100
|
+
const response = await (options.fetcher ?? fetch)(ENDPOINT, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
103
|
+
body: JSON.stringify({ model: JEV_MODEL, state, questions }),
|
|
104
|
+
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS),
|
|
105
|
+
})
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
if (response.status === 401 || response.status === 403) cooldownUntil = Date.now() + COOLDOWN_MS
|
|
108
|
+
throw new Error(`OpenRouter HTTP ${response.status}`)
|
|
109
|
+
}
|
|
110
|
+
const data = await response.json() as {
|
|
111
|
+
answers?: Record<string, JevAnswer>
|
|
112
|
+
usage?: { input_tokens?: number; output_tokens?: number; cost?: number }
|
|
113
|
+
}
|
|
114
|
+
const answers: Record<string, JevAnswer> = {}
|
|
115
|
+
for (const [name, question] of Object.entries(questions)) {
|
|
116
|
+
const answer = data.answers?.[name]
|
|
117
|
+
if (question.type === "choice") {
|
|
118
|
+
if (answer?.type !== "choice" || !Object.hasOwn(question.criteria, answer.choice) ||
|
|
119
|
+
!Number.isFinite(answer.confidence) || answer.confidence < 0 || answer.confidence > 1) {
|
|
120
|
+
throw new Error(`Invalid choice answer: ${name}`)
|
|
121
|
+
}
|
|
122
|
+
} else if (answer?.type !== "noul" || !Number.isFinite(answer.noul) || answer.noul < 0 || answer.noul > 1) {
|
|
123
|
+
throw new Error(`Invalid noul answer: ${name}`)
|
|
124
|
+
}
|
|
125
|
+
answers[name] = answer
|
|
126
|
+
}
|
|
127
|
+
const recovered = lastError !== null
|
|
128
|
+
failures = 0
|
|
129
|
+
lastError = null
|
|
130
|
+
lastSuccessAt = Date.now()
|
|
131
|
+
if (recovered) broadcastStatus()
|
|
132
|
+
const inputTokens = data.usage?.input_tokens ?? 0
|
|
133
|
+
const costUsd = data.usage?.cost ?? inputTokens * 0.042 / 1_000_000
|
|
134
|
+
log.info(`Decision served: questions=${Object.keys(questions).join(",")} latency_ms=${Math.round(performance.now() - started)} input_tokens=${inputTokens} cost_usd=${costUsd}`)
|
|
135
|
+
if (inputTokens > 0) {
|
|
136
|
+
recordUsage({ provider: "openrouter", model: catalogModelKey("openrouter", JEV_MODEL), inputTokens, outputTokens: data.usage?.output_tokens ?? 0, latencyMs: Math.round(performance.now() - started) })
|
|
137
|
+
}
|
|
138
|
+
return { answers, inputTokens, costUsd, latencyMs: Math.round(performance.now() - started) }
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (options.signal?.aborted) return null
|
|
141
|
+
failures++
|
|
142
|
+
lastError = error instanceof Error ? error.message : "Jev unavailable"
|
|
143
|
+
if (failures >= 3) cooldownUntil = Date.now() + COOLDOWN_MS
|
|
144
|
+
log.warn(`Decision fallback: ${lastError}`)
|
|
145
|
+
broadcastStatus()
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
}
|