@johpaz/hive-agents 1.0.5 → 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 +85466 -101014
- package/dist/tool-worker.js +13241 -17001
- package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
- package/dist/ui/assets/{AgentCreateForm-Bcp3HN8D.js → AgentCreateForm-DXkjtXaS.js} +1 -1
- 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-DHfIlSAg.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-BaX6cAPa.js → LoginPage-ByYmIa2p.js} +1 -1
- 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-C_Id9WM-.js → RecoverPage-YY2QU-qh.js} +1 -1
- package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
- package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
- package/dist/ui/assets/{Vignette-Cyi27LQH.js → Vignette-BcPWkNhm.js} +17 -17
- package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -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/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-Bg0g3vPS.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/pencil-L3Li7_pz.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/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-CHmtvNp4.js → useHiveAgentsModelLoad-B4EjHvj4.js} +1 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
- package/dist/ui/assets/{useProviders-C7FA6z4M.js → useProviders-B1NS24md.js} +1 -1
- package/dist/ui/assets/vendor-react-kUOwxn0g.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 +2 -2
- package/packages/core/src/agent/agent-catalog.ts +31 -31
- 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 +165 -27
- package/packages/core/src/agent/conversation-store.ts +12 -1
- 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 +27 -5
- 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/realtime-providers/gemini-live.ts +5 -2
- package/packages/core/src/agent/skill-selector.ts +4 -2
- 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 +1 -0
- package/packages/core/src/agent/tracer.ts +2 -0
- package/packages/core/src/canvas/canvas-manager.ts +17 -1
- 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 +3 -2
- package/packages/core/src/gateway/channel-notify.ts +24 -5
- package/packages/core/src/gateway/delegation-groups.ts +3 -3
- 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/job-executors.ts +3 -3
- package/packages/core/src/gateway/realtime/bridge-tools.ts +106 -28
- package/packages/core/src/gateway/realtime/index.ts +63 -7
- package/packages/core/src/gateway/realtime/prompt.ts +45 -0
- package/packages/core/src/gateway/realtime/voice-session.ts +1 -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 +15 -0
- package/packages/core/src/gateway/routes/setup.ts +22 -11
- 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 +85 -12
- package/packages/core/src/gateway/slash-commands.ts +46 -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 +29 -1
- package/packages/core/src/storage/crypto.ts +23 -12
- package/packages/core/src/storage/reconcile.ts +6 -1
- package/packages/core/src/storage/seed.ts +63 -7
- 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 +1 -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/webview-backend.ts +140 -20
- 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-DTW79pyL.js +0 -8
- package/dist/ui/assets/AgentDetailPage-10XptMde.js +0 -1
- package/dist/ui/assets/AgentNewPage-CUt49rVS.js +0 -1
- package/dist/ui/assets/AgentsPage-1_e1a9xa.js +0 -10
- package/dist/ui/assets/ChannelsPage-BnCQAGZL.js +0 -8
- package/dist/ui/assets/DashboardPage-BsCCKHgg.js +0 -6
- package/dist/ui/assets/LogsPage-DiFBQt7o.js +0 -1
- package/dist/ui/assets/MeetingPage-Bpv5zVXf.js +0 -1
- package/dist/ui/assets/ModelSelector-DfExlPzx.js +0 -1
- package/dist/ui/assets/NotFound-C8HBdF73.js +0 -1
- package/dist/ui/assets/Office3DPage-ChsGMapf.js +0 -319
- package/dist/ui/assets/ProvidersPage-B39pfWHf.js +0 -1
- package/dist/ui/assets/SettingsPage-BgFqasyg.js +0 -9
- package/dist/ui/assets/SetupPage-YeJFfgbt.js +0 -1
- package/dist/ui/assets/VoicePage-Cp63Abj4.js +0 -307
- package/dist/ui/assets/WebChatPage-DxFLWgtM.js +0 -29
- package/dist/ui/assets/agentCapabilities-DOeepCty.js +0 -1
- package/dist/ui/assets/alert-Cj4DpKv6.js +0 -1
- package/dist/ui/assets/badge-DKpeVCpY.js +0 -1
- package/dist/ui/assets/card-Cag15G4h.js +0 -1
- package/dist/ui/assets/dialog-7E3EoEt3.js +0 -1
- package/dist/ui/assets/dist-js-DwLn9F4C.js +0 -1
- package/dist/ui/assets/index-Bi8qEmrK.js +0 -116
- package/dist/ui/assets/index-D2UhaSb0.css +0 -2
- package/dist/ui/assets/label-C6atPuIh.js +0 -1
- package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
- package/dist/ui/assets/scroll-area-CSoG2z53.js +0 -1
- package/dist/ui/assets/select-DlCT21_r.js +0 -1
- package/dist/ui/assets/slider-Bb_PHFJT.js +0 -1
- package/dist/ui/assets/switch-CUsGuBNi.js +0 -1
- package/dist/ui/assets/tabs-Ckfc7DGG.js +0 -1
- package/dist/ui/assets/textarea-BH6pI9Ax.js +0 -1
- package/dist/ui/assets/useAudioDevices-Dpr_hn6i.js +0 -41
- package/dist/ui/assets/useOfficeModel-Cc5VkReZ.js +0 -1
- package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
- /package/dist/ui/assets/{core-Dz04EE_8.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-BzQV75Ig.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/{mic-Rq4BxU1R.js → mic-CpDU_2as.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/{rotate-ccw-Dx92orJM.js → rotate-ccw-LoM1AuqK.js} +0 -0
- /package/dist/ui/assets/{search-DB4w9YHW.js → search-BMwCI-pX.js} +0 -0
- /package/dist/ui/assets/{send-xi8HzUdc.js → send-D6fgWV7m.js} +0 -0
- /package/dist/ui/assets/{settings-pV0cF8Kf.js → settings-qV3kVkeG.js} +0 -0
- /package/dist/ui/assets/{shield-nLNsomh_.js → shield-CIarwBvx.js} +0 -0
- /package/dist/ui/assets/{sparkles-CerRDYxk.js → sparkles-DVvY6jDT.js} +0 -0
- /package/dist/ui/assets/{square-CcWzRWyG.js → square-D5zdNkAY.js} +0 -0
- /package/dist/ui/assets/{terminal-C2SUZUAD.js → terminal-BEcTK780.js} +0 -0
- /package/dist/ui/assets/{trash-2-BZsMCfso.js → trash-2-D6oziYAK.js} +0 -0
- /package/dist/ui/assets/{utils-lc8H6VGT.js → utils-DEmd_M8c.js} +0 -0
- /package/dist/ui/assets/{vendor-router-DCsSv_I7.js → vendor-router-DP84b3LQ.js} +0 -0
- /package/dist/ui/assets/{volume-2-CBMYsuF3.js → volume-2-EaA0JRvD.js} +0 -0
- /package/dist/ui/assets/{volume-x-vNFf2e4-.js → volume-x-CROXNMGT.js} +0 -0
- /package/dist/ui/assets/{wifi-DNv53AfN.js → wifi-BUJuOcgP.js} +0 -0
- /package/dist/ui/assets/{zap-Yed86Sh8.js → zap-DSoX9NDk.js} +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import type { LLMMessage, LLMToolDef } from "./llm-client"
|
|
2
|
+
import type { SkillDescriptor } from "./skill-selector"
|
|
3
|
+
import type { ContextTool } from "./context-compiler"
|
|
4
|
+
import type { PlaybookRule } from "./playbook-selector"
|
|
5
|
+
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
6
|
+
import { searchCapabilities } from "./capability-search"
|
|
7
|
+
import { mcpToolFullName } from "./tool-selector"
|
|
8
|
+
import { askJev, getJevKey, type JevAnswer, type JevQuestion } from "./jev-decisions"
|
|
9
|
+
import { col } from "../storage/hive"
|
|
10
|
+
import type { AgentDoc, McpServerDoc, McpToolDoc } from "../storage/collections"
|
|
11
|
+
|
|
12
|
+
export interface JevDecisionMetrics {
|
|
13
|
+
latencyMs: number
|
|
14
|
+
costUsd: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** "activo": connected now; "disponible": enabled, connects on first use; "apagado": disabled. */
|
|
18
|
+
export type JevMcpState = "activo" | "disponible" | "apagado"
|
|
19
|
+
|
|
20
|
+
export interface JevMcpServer {
|
|
21
|
+
id: string
|
|
22
|
+
name: string
|
|
23
|
+
state: JevMcpState
|
|
24
|
+
tools: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface JevSpecialist {
|
|
28
|
+
id: string
|
|
29
|
+
name: string
|
|
30
|
+
description: string
|
|
31
|
+
tools: string[]
|
|
32
|
+
mcp: Array<{ name: string; state: JevMcpState }>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What the swarm can do right now: every enabled worker (catalog and
|
|
37
|
+
* agent_create alike) with its tools, and every MCP server with its state.
|
|
38
|
+
* Jev routes and selects over this, so it never recommends a specialist whose
|
|
39
|
+
* MCP is off or proposes a tool that is not connected.
|
|
40
|
+
*/
|
|
41
|
+
export async function describeSwarmCapabilities(
|
|
42
|
+
mcpManager: { getServerTools(key: string): unknown[] | undefined } | null,
|
|
43
|
+
opts: { includeSpecialists: boolean },
|
|
44
|
+
): Promise<{ mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }> {
|
|
45
|
+
const servers = (await (await col<McpServerDoc>("mcpServers")).scan({})).map(e => e.doc)
|
|
46
|
+
const mcpServers: JevMcpServer[] = servers.map(server => {
|
|
47
|
+
const tools = mcpManager?.getServerTools(server.id)?.length || mcpManager?.getServerTools(server.name)?.length || 0
|
|
48
|
+
return { id: server.id, name: server.name, tools, state: !server.enabled ? "apagado" : tools > 0 ? "activo" : "disponible" }
|
|
49
|
+
})
|
|
50
|
+
if (!opts.includeSpecialists) return { mcpServers, specialists: [] }
|
|
51
|
+
|
|
52
|
+
const byId = new Map(mcpServers.map(s => [s.id, s]))
|
|
53
|
+
const parse = (json: string | null | undefined): string[] => {
|
|
54
|
+
try { return json ? (JSON.parse(json) as unknown[]).map(String) : [] } catch { return [] }
|
|
55
|
+
}
|
|
56
|
+
const specialists = (await (await col<AgentDoc>("agents")).scan({}))
|
|
57
|
+
.map(e => e.doc)
|
|
58
|
+
.filter(a => a.role === "worker" && a.enabled && a.status !== "archived")
|
|
59
|
+
.map(a => ({
|
|
60
|
+
id: a.id,
|
|
61
|
+
name: a.name,
|
|
62
|
+
description: (a.description ?? a.name).slice(0, 200),
|
|
63
|
+
tools: parse(a.tool_allowlist_json).slice(0, 12),
|
|
64
|
+
mcp: parse(a.mcp_server_ids_json).map(id => byId.get(id)).filter((s): s is JevMcpServer => !!s)
|
|
65
|
+
.map(s => ({ name: s.name, state: s.state })),
|
|
66
|
+
}))
|
|
67
|
+
return { mcpServers, specialists }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One roster line: what the coordinator needs to pick a specialist without calling agent_find. */
|
|
71
|
+
export function renderSpecialistLine(s: JevSpecialist): string {
|
|
72
|
+
const mcp = s.mcp.length ? ` · MCP: ${s.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : ""
|
|
73
|
+
return `- ${s.id} (${s.name})${mcp}`
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface JevContextPlan {
|
|
77
|
+
messages: LLMMessage[]
|
|
78
|
+
tools: LLMToolDef[]
|
|
79
|
+
skills: SkillDescriptor[]
|
|
80
|
+
agentId: string | null
|
|
81
|
+
/**
|
|
82
|
+
* MCP servers the recommended specialist depends on that are off. Non-empty
|
|
83
|
+
* means "this is the right specialist, but the user must turn these on
|
|
84
|
+
* first" — delegating now would hand it a task it cannot do.
|
|
85
|
+
*/
|
|
86
|
+
agentMcpOff: string[]
|
|
87
|
+
selectedMessageIds: number[]
|
|
88
|
+
selectedToolNames: string[]
|
|
89
|
+
selectedSkillNames: string[]
|
|
90
|
+
selectedScratchpadKeys: string[]
|
|
91
|
+
selectedPlaybookIds: string[]
|
|
92
|
+
decision: JevDecisionMetrics
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const excerpt = (value: unknown, max = 450): string =>
|
|
96
|
+
(typeof value === "string" ? value : JSON.stringify(value) ?? "").slice(0, max)
|
|
97
|
+
const probability = (answer: JevAnswer | undefined): number | null => answer?.type === "noul" ? answer.noul : null
|
|
98
|
+
const MANDATORY_TAIL = 4
|
|
99
|
+
/** Below this many characters of prunable tool output, a decision costs more latency than it saves. */
|
|
100
|
+
const MIN_PRUNABLE_CHARS = 4000
|
|
101
|
+
|
|
102
|
+
/** Decisions select only from already authorized, discoverable candidates. */
|
|
103
|
+
export async function planJevContext(input: {
|
|
104
|
+
objective: string
|
|
105
|
+
messages: LLMMessage[]
|
|
106
|
+
tools: LLMToolDef[]
|
|
107
|
+
allTools: ContextTool[]
|
|
108
|
+
skills: SkillDescriptor[]
|
|
109
|
+
scratchpadNotes?: Array<{ key: string; value: string }>
|
|
110
|
+
playbookRules?: PlaybookRule[]
|
|
111
|
+
isWorker: boolean
|
|
112
|
+
/** From describeSwarmCapabilities; absent means "unknown", not "none". */
|
|
113
|
+
swarm?: { mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }
|
|
114
|
+
}): Promise<JevContextPlan | null> {
|
|
115
|
+
if (!await getJevKey().catch(() => null)) return null
|
|
116
|
+
const { objective, messages, tools, allTools, skills, isWorker } = input
|
|
117
|
+
const mandatoryMessages = new Set<number>()
|
|
118
|
+
// The last two exchanges carry the thread's immediate referents ("hazlo otra
|
|
119
|
+
// vez", "el anterior"); dropping them sent the model into conversation_read loops.
|
|
120
|
+
for (let i = Math.max(0, messages.length - MANDATORY_TAIL); i < messages.length; i++) mandatoryMessages.add(i)
|
|
121
|
+
messages.forEach((message, i) => {
|
|
122
|
+
if (Array.isArray(message.content) || (typeof message.content === "string" && message.content.startsWith("<hive:internal_event"))) mandatoryMessages.add(i)
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
const candidateMessageIds = messages.map((_, i) => i).filter(i => !mandatoryMessages.has(i))
|
|
126
|
+
let candidateTools: ContextTool[] = tools.filter(t => !MINIMAL_TOOLS.has(t.function.name))
|
|
127
|
+
.map(t => allTools.find(a => a.name === t.function.name))
|
|
128
|
+
.filter((t): t is ContextTool => !!t)
|
|
129
|
+
try {
|
|
130
|
+
const hits = await searchCapabilities(objective, { types: ["tool", "mcp"], k: 12 })
|
|
131
|
+
// allTools only holds MCP tools of servers that are enabled, connected and
|
|
132
|
+
// allowed for this agent — resolving through it is what keeps a dormant or
|
|
133
|
+
// foreign server's tools out of the plan.
|
|
134
|
+
const available = new Map(allTools.map(t => [t.name, t]))
|
|
135
|
+
const mcpTools = await col<McpToolDoc>("mcpTools")
|
|
136
|
+
const names = await Promise.all(hits.map(async h => {
|
|
137
|
+
if (h.type !== "mcp") return h.rawId
|
|
138
|
+
const tool = (await mcpTools.get(h.rawId))?.doc
|
|
139
|
+
return tool ? mcpToolFullName(tool.server_name, tool.tool_name) : null
|
|
140
|
+
}))
|
|
141
|
+
const discovered = names.map(n => n ? available.get(n) : undefined).filter((t): t is ContextTool => !!t && !MINIMAL_TOOLS.has(t.name))
|
|
142
|
+
candidateTools = [...new Map([...candidateTools, ...discovered].map(t => [t.name, t])).values()].slice(0, 24)
|
|
143
|
+
} catch { /* index unavailable: retain the current loadout */ }
|
|
144
|
+
|
|
145
|
+
const optionalSkills = skills.filter(s => s.active && s.body).slice(0, 8)
|
|
146
|
+
const scratchpadNotes = (input.scratchpadNotes ?? []).slice(-16)
|
|
147
|
+
const playbookRules = (input.playbookRules ?? []).slice(0, 8)
|
|
148
|
+
// Specialists with an MCP off stay eligible: Jev still names the right one,
|
|
149
|
+
// and the coordinator asks the user to turn the server on instead of
|
|
150
|
+
// delegating a task the specialist cannot do yet.
|
|
151
|
+
const agents = isWorker ? [] : (input.swarm?.specialists ?? []).slice(0, 16)
|
|
152
|
+
const questions: Record<string, JevQuestion> = {}
|
|
153
|
+
for (const i of candidateMessageIds) questions[`history_${i}`] = { type: "noul", instructions: `Is earlier conversation item ${i} necessary to complete the current objective?` }
|
|
154
|
+
for (const tool of candidateTools) questions[`tool_${tool.name}`] = { type: "noul", instructions: `Will tool ${tool.name} likely be needed for the current objective?` }
|
|
155
|
+
for (const skill of optionalSkills) questions[`skill_${skill.id}`] = { type: "noul", instructions: `Are instructions from skill ${skill.name} needed for the current objective?` }
|
|
156
|
+
for (const note of scratchpadNotes) questions[`note_${note.key}`] = { type: "noul", instructions: `Is scratchpad note ${note.key} needed for the current objective?` }
|
|
157
|
+
for (const rule of playbookRules) questions[`rule_${rule.id}`] = { type: "noul", instructions: `Does playbook rule ${rule.id} apply to the current objective?` }
|
|
158
|
+
if (agents.length) questions.agent = {
|
|
159
|
+
type: "choice", instructions: "Which existing specialist should handle a bounded part of this objective, or should the coordinator handle it?",
|
|
160
|
+
criteria: {
|
|
161
|
+
coordinator: "No bounded specialist task is needed",
|
|
162
|
+
...Object.fromEntries(agents.map(a => [a.id, [
|
|
163
|
+
a.description,
|
|
164
|
+
a.tools.length ? `tools: ${a.tools.join(", ")}` : "",
|
|
165
|
+
a.mcp.length ? `MCP: ${a.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : "",
|
|
166
|
+
].filter(Boolean).join(" · ").slice(0, 400)])),
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
const decision = await askJev({
|
|
170
|
+
objective: objective.slice(0, 3500),
|
|
171
|
+
history: candidateMessageIds.map(i => ({ id: i, role: messages[i].role, content: excerpt(messages[i].content) })),
|
|
172
|
+
tools: candidateTools.map(t => ({ name: t.name, description: t.description.slice(0, 240) })),
|
|
173
|
+
skills: optionalSkills.map(s => ({ id: s.id, name: s.name, description: s.description.slice(0, 240) })),
|
|
174
|
+
notes: scratchpadNotes.map(n => ({ key: n.key, value: n.value.slice(0, 350) })),
|
|
175
|
+
rules: playbookRules.map(r => ({ id: r.id, rule: r.rule.slice(0, 350) })),
|
|
176
|
+
mcp_servers: (input.swarm?.mcpServers ?? []).map(s => ({ name: s.name, state: s.state, tools: s.tools })),
|
|
177
|
+
}, questions)
|
|
178
|
+
if (!decision) return null
|
|
179
|
+
|
|
180
|
+
const selected = new Set(messages.map((_, i) => i).filter(i => mandatoryMessages.has(i) ||
|
|
181
|
+
!candidateMessageIds.includes(i) || (probability(decision.answers[`history_${i}`]) ?? 1) >= 0.35))
|
|
182
|
+
// A reply travels with the user turn it answered: Gemini silently drops a
|
|
183
|
+
// model turn that has no preceding user turn.
|
|
184
|
+
for (const i of [...selected]) {
|
|
185
|
+
if (messages[i].role !== "assistant") continue
|
|
186
|
+
for (let j = i - 1; j >= 0; j--) if (messages[j].role === "user") { selected.add(j); break }
|
|
187
|
+
}
|
|
188
|
+
const selectedMessageIds = [...selected].sort((a, b) => a - b)
|
|
189
|
+
const selectedToolNames = candidateTools.filter(t => (probability(decision.answers[`tool_${t.name}`]) ?? 1) >= 0.35).map(t => t.name)
|
|
190
|
+
const selectedSkills = optionalSkills.filter(s => (probability(decision.answers[`skill_${s.id}`]) ?? 1) >= 0.35)
|
|
191
|
+
const toolMap = new Map(allTools.map(t => [t.name, t]))
|
|
192
|
+
const selectedNames = new Set(selectedToolNames)
|
|
193
|
+
const candidateNames = new Set(candidateTools.map(t => t.name))
|
|
194
|
+
const combinedTools = tools.filter(t => !candidateNames.has(t.function.name) || selectedNames.has(t.function.name))
|
|
195
|
+
for (const name of selectedToolNames) {
|
|
196
|
+
const tool = toolMap.get(name)
|
|
197
|
+
if (tool && !combinedTools.some(t => t.function.name === name)) combinedTools.push({
|
|
198
|
+
type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters },
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
const agentAnswer = decision.answers.agent
|
|
202
|
+
const agentId = agentAnswer?.type === "choice" && agentAnswer.confidence >= 0.7 && agentAnswer.choice !== "coordinator"
|
|
203
|
+
? agentAnswer.choice : null
|
|
204
|
+
const agentMcpOff = agents.find(a => a.id === agentId)?.mcp.filter(m => m.state === "apagado").map(m => m.name) ?? []
|
|
205
|
+
return {
|
|
206
|
+
messages: selectedMessageIds.map(i => messages[i]), tools: combinedTools,
|
|
207
|
+
skills: selectedSkills, agentId, agentMcpOff, selectedMessageIds, selectedToolNames,
|
|
208
|
+
selectedSkillNames: selectedSkills.map(s => s.name),
|
|
209
|
+
selectedScratchpadKeys: scratchpadNotes.filter(n => (probability(decision.answers[`note_${n.key}`]) ?? 1) >= 0.35).map(n => n.key),
|
|
210
|
+
selectedPlaybookIds: playbookRules.filter(r => (probability(decision.answers[`rule_${r.id}`]) ?? 1) >= 0.35).map(r => r.id),
|
|
211
|
+
decision: { latencyMs: decision.latencyMs, costUsd: decision.costUsd },
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Only independent reads, or separate delegated tasks, may execute concurrently.
|
|
217
|
+
* null leaves the batch to the runtime default; `decision` is present only when Jev was asked.
|
|
218
|
+
*/
|
|
219
|
+
export async function jevWantsParallel(calls: Array<{ function: { name: string; arguments: unknown } }>): Promise<{ parallel: boolean; decision?: JevDecisionMetrics } | null> {
|
|
220
|
+
if (calls.length < 2) return null
|
|
221
|
+
if (!await getJevKey().catch(() => null)) return null
|
|
222
|
+
const names = calls.map(c => c.function.name)
|
|
223
|
+
const readOnly = names.every(n => /^(fs_read|fs_list|fs_glob|fs_exists|web_search|web_fetch|memory_read|memory_search|artifact_read|artifact_inspect|task_status|agent_find)$/.test(n))
|
|
224
|
+
const delegated = names.every(n => n === "task_delegate")
|
|
225
|
+
if (!readOnly && !delegated) return { parallel: false }
|
|
226
|
+
if (delegated) {
|
|
227
|
+
const ids = calls.map(call => {
|
|
228
|
+
try {
|
|
229
|
+
const args = typeof call.function.arguments === "string" ? JSON.parse(call.function.arguments) : call.function.arguments
|
|
230
|
+
return String(args?.worker_id ?? "")
|
|
231
|
+
} catch { return "" }
|
|
232
|
+
})
|
|
233
|
+
if (ids.some(id => !id) || new Set(ids).size !== ids.length) return { parallel: false }
|
|
234
|
+
const agentsCol = await col<AgentDoc>("agents")
|
|
235
|
+
const agents = await Promise.all(ids.map(id => agentsCol.get(id)))
|
|
236
|
+
const workspaces = agents.map(row => row?.doc.workspace)
|
|
237
|
+
if (workspaces.some(path => !path) || new Set(workspaces).size !== workspaces.length) return { parallel: false }
|
|
238
|
+
}
|
|
239
|
+
const result = await askJev({ calls: calls.map(c => ({ tool: c.function.name, arguments: excerpt(c.function.arguments, 700) })) }, {
|
|
240
|
+
independent: { type: "noul", instructions: "Can every listed operation run concurrently without needing the result of another listed operation?" },
|
|
241
|
+
})
|
|
242
|
+
const answer = result?.answers.independent
|
|
243
|
+
return result && answer?.type === "noul"
|
|
244
|
+
? { parallel: answer.noul >= 0.8, decision: { latencyMs: result.latencyMs, costUsd: result.costUsd } }
|
|
245
|
+
: null
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export async function planJevIteration(input: {
|
|
249
|
+
objective: string
|
|
250
|
+
messages: LLMMessage[]
|
|
251
|
+
tools: LLMToolDef[]
|
|
252
|
+
}): Promise<{ messages: LLMMessage[]; tools: LLMToolDef[]; action: string; omittedResults: number; decision: JevDecisionMetrics } | null> {
|
|
253
|
+
const toolIndices = input.messages.map((m, i) => m.role === "tool" ? i : -1).filter(i => i >= 0)
|
|
254
|
+
if (!toolIndices.length) return null
|
|
255
|
+
const older = toolIndices.slice(0, -1).slice(-8)
|
|
256
|
+
const prunableChars = older.reduce((sum, i) => sum + excerpt(input.messages[i].content, Infinity).length, 0)
|
|
257
|
+
if (prunableChars < MIN_PRUNABLE_CHARS) return null
|
|
258
|
+
const questions: Record<string, JevQuestion> = {
|
|
259
|
+
action: {
|
|
260
|
+
type: "choice",
|
|
261
|
+
instructions: "What capability should the text model use next to complete the current objective?",
|
|
262
|
+
criteria: {
|
|
263
|
+
continue: "Continue reasoning with currently available tools",
|
|
264
|
+
delegate: "Formulate a bounded task for an existing specialist",
|
|
265
|
+
discover: "Discover another tool or skill before continuing",
|
|
266
|
+
finish: "The evidence is sufficient to compose the final answer without more tools",
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
for (const i of older) questions[`result_${i}`] = {
|
|
271
|
+
type: "noul", instructions: `Is result ${i} still needed to complete the current objective?`,
|
|
272
|
+
}
|
|
273
|
+
const result = await askJev({
|
|
274
|
+
objective: input.objective.slice(0, 2800),
|
|
275
|
+
results: toolIndices.slice(-9).map(i => ({ id: i, tool: input.messages[i].name, content: excerpt(input.messages[i].content, 650) })),
|
|
276
|
+
}, questions)
|
|
277
|
+
if (!result) return null
|
|
278
|
+
const omitted = new Set(older.filter(i => (probability(result.answers[`result_${i}`]) ?? 1) < 0.35))
|
|
279
|
+
const projected = input.messages.map((m, i) => omitted.has(i)
|
|
280
|
+
? { ...m, content: "[Previous tool result omitted from this call]" } : m)
|
|
281
|
+
const answer = result.answers.action
|
|
282
|
+
const latestResult = input.messages[toolIndices[toolIndices.length - 1]]
|
|
283
|
+
const resultFailed = typeof latestResult.content === "string" && (latestResult.content.startsWith("[Tool Error]") || latestResult.content.includes('"error":true'))
|
|
284
|
+
const proposedAction = answer?.type === "choice" && answer.confidence >= (answer.choice === "finish" ? 0.85 : 0.7) ? answer.choice : "continue"
|
|
285
|
+
const action = proposedAction === "finish" && resultFailed ? "continue" : proposedAction
|
|
286
|
+
let tools = input.tools
|
|
287
|
+
if (action === "finish") tools = []
|
|
288
|
+
else if (action === "delegate") tools = tools.filter(t => ["task_delegate", "agent_find", "search_knowledge"].includes(t.function.name))
|
|
289
|
+
else if (action === "discover") tools = tools.filter(t => t.function.name === "search_knowledge")
|
|
290
|
+
const decision = { latencyMs: result.latencyMs, costUsd: result.costUsd }
|
|
291
|
+
if (action !== "finish" && tools.length === 0) return { messages: projected, tools: input.tools, action: "continue", omittedResults: omitted.size, decision }
|
|
292
|
+
return { messages: projected, tools, action, omittedResults: omitted.size, decision }
|
|
293
|
+
}
|
|
@@ -16,7 +16,7 @@ import { loadConfig } from "../config/loader"
|
|
|
16
16
|
import { withRetry, isRetryableError, type RetryPolicy } from "../resilience/retry"
|
|
17
17
|
import { GeminiProvider } from "./llm-providers/gemini"
|
|
18
18
|
import { AnthropicProvider } from "./llm-providers/anthropic"
|
|
19
|
-
import { OllamaProvider } from "./llm-providers/ollama"
|
|
19
|
+
import { OllamaProvider, ollamaDefaultNumCtx } from "./llm-providers/ollama"
|
|
20
20
|
import { OpenAIProvider } from "./llm-providers/openai"
|
|
21
21
|
import { GroqProvider } from "./llm-providers/groq"
|
|
22
22
|
import { MistralProvider } from "./llm-providers/mistral"
|
|
@@ -97,6 +97,13 @@ export interface LLMCallOptions {
|
|
|
97
97
|
signal?: AbortSignal
|
|
98
98
|
/** Enable extended thinking for supported models (Anthropic Claude 3.7+). */
|
|
99
99
|
thinking?: { enabled: boolean; budget_tokens?: number }
|
|
100
|
+
/**
|
|
101
|
+
* Stable id of the conversation this call belongs to (the agent loop's
|
|
102
|
+
* threadId). Providers that route or cache per session derive their own
|
|
103
|
+
* header from it — OpenCode Go's `x-opencode-session` — and never send it
|
|
104
|
+
* verbatim, since it carries user, channel and peer ids.
|
|
105
|
+
*/
|
|
106
|
+
sessionId?: string
|
|
100
107
|
}
|
|
101
108
|
|
|
102
109
|
export interface LLMResponse {
|
|
@@ -214,6 +221,14 @@ export function describeProviderFailure(
|
|
|
214
221
|
provider: string,
|
|
215
222
|
cleanModel: string,
|
|
216
223
|
): string {
|
|
224
|
+
// NVIDIA usa 404 también para modelos que siguen en su catálogo público pero
|
|
225
|
+
// no están habilitados para esa key ("Function '…': Not found for account
|
|
226
|
+
// '…'"). Decir que "se retiró" mandaba a buscar un modelo que sí existe.
|
|
227
|
+
if (status === 404 && /not found for account/i.test((err as Error)?.message ?? "")) {
|
|
228
|
+
return `Tu cuenta de ${provider} no tiene habilitado el modelo "${cleanModel}" (HTTP 404): `
|
|
229
|
+
+ `figura en su catálogo, pero no está disponible para esta API key. `
|
|
230
|
+
+ `Elige otro modelo en Ajustes → Proveedores.`
|
|
231
|
+
}
|
|
217
232
|
if (status === 404 || status === 410) {
|
|
218
233
|
return `El modelo "${cleanModel}" ya no existe en ${provider} (HTTP ${status}). `
|
|
219
234
|
+ `El proveedor lo retiró de su catálogo; reintentar no sirve. `
|
|
@@ -221,8 +236,8 @@ export function describeProviderFailure(
|
|
|
221
236
|
}
|
|
222
237
|
if (status === 429) {
|
|
223
238
|
return `${provider} está limitando las peticiones (HTTP 429) y los reintentos tampoco pasaron. `
|
|
224
|
-
+ `Es el límite de uso de tu cuenta, no un problema del modelo:
|
|
225
|
-
+ `revisa tu cuota con el proveedor, o
|
|
239
|
+
+ `Es el límite de uso de tu cuenta, no un problema del modelo: espera unos minutos, `
|
|
240
|
+
+ `revisa tu cuota con el proveedor, o cambia de modelo en Ajustes → Proveedores.`
|
|
226
241
|
}
|
|
227
242
|
if (status === 401 || status === 403) {
|
|
228
243
|
return `${provider} rechazó la API key (HTTP ${status}). `
|
|
@@ -289,13 +304,20 @@ export async function resolveProviderConfig(
|
|
|
289
304
|
apiKey = process.env[`${providerId.toUpperCase()}_API_KEY`] || ""
|
|
290
305
|
}
|
|
291
306
|
|
|
307
|
+
// The window the model will actually see. Ollama truncates at num_ctx
|
|
308
|
+
// without an error, so budgeting with the model's nominal window made the
|
|
309
|
+
// compiler build ~22k-token prompts that arrived cut to 4k.
|
|
310
|
+
const modelWindow = modelEntry?.doc.context_window || undefined
|
|
311
|
+
const numCtx = providerRow?.num_ctx ?? (providerId === "ollama" ? ollamaDefaultNumCtx(modelWindow) : undefined)
|
|
312
|
+
const contextWindow = modelWindow && numCtx ? Math.min(modelWindow, numCtx) : modelWindow ?? numCtx
|
|
313
|
+
|
|
292
314
|
return {
|
|
293
315
|
provider: providerId,
|
|
294
316
|
model: modelId,
|
|
295
317
|
apiKey,
|
|
296
318
|
baseUrl: providerRow?.base_url || undefined,
|
|
297
|
-
numCtx
|
|
319
|
+
numCtx,
|
|
298
320
|
numGpu: providerRow?.num_gpu ?? undefined,
|
|
299
|
-
contextWindow
|
|
321
|
+
contextWindow,
|
|
300
322
|
}
|
|
301
323
|
}
|
|
@@ -3,6 +3,20 @@ import { sanitizeMessages, resolveMaxTokens, ensureArrayItems } from "./interfac
|
|
|
3
3
|
import type { LLMCallOptions, LLMProvider, LLMResponse, LLMToolCall } from "./interface"
|
|
4
4
|
import type { ContentPart, LLMMessage } from "../llm-client"
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Ollama reads only `num_ctx` tokens of a prompt and silently drops the rest,
|
|
8
|
+
* so this is the window Hive must budget for, not the model's nominal one.
|
|
9
|
+
* 4096 used to be the default and did not even fit the coordinator's base
|
|
10
|
+
* prompt (~6k tokens of instructions and tools); 16k fits a real turn while
|
|
11
|
+
* staying far below what exhausts RAM on 4B–8B models. providers.num_ctx
|
|
12
|
+
* overrides it.
|
|
13
|
+
*/
|
|
14
|
+
export const OLLAMA_DEFAULT_NUM_CTX = 16384
|
|
15
|
+
|
|
16
|
+
export function ollamaDefaultNumCtx(modelContextWindow?: number): number {
|
|
17
|
+
return modelContextWindow ? Math.min(modelContextWindow, OLLAMA_DEFAULT_NUM_CTX) : OLLAMA_DEFAULT_NUM_CTX
|
|
18
|
+
}
|
|
19
|
+
|
|
6
20
|
const log = logger.child("llm-client")
|
|
7
21
|
|
|
8
22
|
// Local models known to support Ollama's `think` request flag (returns
|
|
@@ -90,11 +104,10 @@ export class OllamaProvider implements LLMProvider {
|
|
|
90
104
|
},
|
|
91
105
|
}))
|
|
92
106
|
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
// Users can override via providers.num_ctx in DB.
|
|
107
|
+
// resolveProviderConfig already sends the window the context was budgeted
|
|
108
|
+
// for; the fallback only covers callers that build options by hand.
|
|
96
109
|
const runtimeOptions: Record<string, unknown> = {
|
|
97
|
-
num_ctx: options.numCtx ??
|
|
110
|
+
num_ctx: options.numCtx ?? ollamaDefaultNumCtx(options.contextWindow),
|
|
98
111
|
}
|
|
99
112
|
if (options.numGpu !== undefined) runtimeOptions.num_gpu = options.numGpu
|
|
100
113
|
if (options.temperature !== undefined) runtimeOptions.temperature = options.temperature
|
|
@@ -78,8 +78,8 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
78
78
|
/** Override to true for providers running on localhost. */
|
|
79
79
|
protected isLocalProvider(): boolean { return false }
|
|
80
80
|
|
|
81
|
-
/** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch). */
|
|
82
|
-
protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined): Promise<any> {
|
|
81
|
+
/** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch, per-call headers). */
|
|
82
|
+
protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, _options?: LLMCallOptions): Promise<any> {
|
|
83
83
|
const { default: OpenAI } = await import("openai")
|
|
84
84
|
return new OpenAI({ apiKey, baseURL })
|
|
85
85
|
}
|
|
@@ -131,7 +131,7 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
131
131
|
throw new Error(`API key missing for provider: ${this.providerName}. Configure it in Settings → Providers.`)
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
-
const client = await this.resolveOpenAIClient(apiKey, baseURL)
|
|
134
|
+
const client = await this.resolveOpenAIClient(apiKey, baseURL, options)
|
|
135
135
|
|
|
136
136
|
const sanitized = sanitizeMessages(options.messages)
|
|
137
137
|
const rawMessages = this.needsReasoningRoundtrip()
|
|
@@ -268,9 +268,23 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
268
268
|
sendTools: boolean,
|
|
269
269
|
profile: ReturnType<typeof getProviderProfile>,
|
|
270
270
|
): Promise<LLMResponse> {
|
|
271
|
+
// Without stream_options.include_usage an OpenAI-compatible stream reports
|
|
272
|
+
// no tokens at all: every NVIDIA call was recorded as 0 in / 0 out, so its
|
|
273
|
+
// cost and Jev's savings on it never reached the dashboard. A server that
|
|
274
|
+
// does not know the field gets the same request without it.
|
|
275
|
+
const createStream = async (request: any) => {
|
|
276
|
+
try {
|
|
277
|
+
return await client.chat.completions.create({ ...request, stream: true, stream_options: { include_usage: true } }, { signal: options.signal })
|
|
278
|
+
} catch (err: any) {
|
|
279
|
+
const message = String(err?.error?.message ?? err?.message ?? "").toLowerCase()
|
|
280
|
+
if (!message.includes("stream_options") && !message.includes("include_usage")) throw err
|
|
281
|
+
return await client.chat.completions.create({ ...request, stream: true }, { signal: options.signal })
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
271
285
|
let stream
|
|
272
286
|
try {
|
|
273
|
-
stream = await
|
|
287
|
+
stream = await createStream(this.modifyRequestBody(body, options))
|
|
274
288
|
} catch (err: any) {
|
|
275
289
|
const status = err?.status ?? err?.response?.status
|
|
276
290
|
const errMsg = (err?.error?.message ?? err?.message ?? "").toLowerCase()
|
|
@@ -280,17 +294,17 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
280
294
|
const originalCount = body.messages.length
|
|
281
295
|
compactBodyForContextOverflow(body, err)
|
|
282
296
|
log.info(`[llm-client] ${this.providerName}: compacted ${originalCount} msgs → ${body.messages.length} msgs, max_tokens=${body.max_tokens}`)
|
|
283
|
-
stream = await
|
|
297
|
+
stream = await createStream(this.modifyRequestBody(body, options))
|
|
284
298
|
} else if (sendTools && profile.retryWithoutToolsOnCodes.includes(status)) {
|
|
285
299
|
log.warn(`[llm-client] ${this.providerName}: tools rejected (HTTP ${status}) — retrying stream without tools`)
|
|
286
300
|
const bodyNoTools = { ...body }
|
|
287
301
|
delete bodyNoTools.tools
|
|
288
302
|
delete bodyNoTools.tool_choice
|
|
289
303
|
delete bodyNoTools.parallel_tool_calls
|
|
290
|
-
stream = await
|
|
304
|
+
stream = await createStream(stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)))
|
|
291
305
|
} else if (EXTRAS_REJECTED_CODES.includes(status) && this.modifyRequestBody(body, options).chat_template_kwargs) {
|
|
292
306
|
log.warn(`[llm-client] ${this.providerName}: request rejected (HTTP ${status}) — retrying stream without chat_template_kwargs`)
|
|
293
|
-
stream = await
|
|
307
|
+
stream = await createStream(stripProviderExtras(this.modifyRequestBody(body, options)))
|
|
294
308
|
} else {
|
|
295
309
|
throw err
|
|
296
310
|
}
|
|
@@ -304,6 +318,12 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
304
318
|
let output_tokens = 0
|
|
305
319
|
|
|
306
320
|
for await (const chunk of stream) {
|
|
321
|
+
// Usage arrives in its own final chunk with an empty `choices`: read it
|
|
322
|
+
// before skipping choice-less chunks, or it is dropped even when sent.
|
|
323
|
+
if (chunk.usage) {
|
|
324
|
+
input_tokens = chunk.usage.prompt_tokens ?? input_tokens
|
|
325
|
+
output_tokens = chunk.usage.completion_tokens ?? output_tokens
|
|
326
|
+
}
|
|
307
327
|
const choice = chunk.choices?.[0]
|
|
308
328
|
if (!choice) continue
|
|
309
329
|
|
|
@@ -329,11 +349,6 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
329
349
|
}
|
|
330
350
|
}
|
|
331
351
|
if (choice.finish_reason) finish_reason = choice.finish_reason
|
|
332
|
-
|
|
333
|
-
if (chunk.usage) {
|
|
334
|
-
input_tokens = chunk.usage.prompt_tokens ?? 0
|
|
335
|
-
output_tokens = chunk.usage.completion_tokens ?? 0
|
|
336
|
-
}
|
|
337
352
|
}
|
|
338
353
|
|
|
339
354
|
const tool_calls: LLMToolCall[] = [...toolCallMap.values()].map((tc) => ({
|