@johpaz/hive-agents 1.1.6 → 1.1.11
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 +4 -10
- package/dist/hive.js +5258 -2985
- package/dist/tool-worker.js +197 -75
- package/dist/ui/assets/{A2UIPage-CxE3jH4_.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-SGj5AqAX.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-xvAmX6kw.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-NLw2wHjH.js → ApiClientPage-uuBnrh0y.js} +1 -1
- package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
- package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
- package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
- package/dist/ui/assets/{LogsPage-G9d2G1nL.js → LogsPage-mcqOYvGw.js} +1 -1
- package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
- package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
- package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
- package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
- package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
- package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
- package/dist/ui/assets/{RecoverPage-Dr6qKgV5.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-BoVKIf4r.js → SetupPage-OaouFLGD.js} +1 -1
- package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
- package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
- package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
- package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
- package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
- package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
- package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
- package/dist/ui/assets/{conversationsStore-ns_ZfKgg.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-C3n2xYF2.js → dialog-DO1fQCF7.js} +1 -1
- package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
- package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
- package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
- package/dist/ui/assets/index-BKNFH2al.css +2 -0
- package/dist/ui/assets/index-U0e4e5mL.js +156 -0
- package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
- package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
- package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
- package/dist/ui/assets/select-BjBXxyxL.js +1 -0
- package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
- package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
- package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
- package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
- package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
- package/dist/ui/assets/{useAudioDevices-CsPrtpWY.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-nn4gON9g.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-9tvEC3hX.js → useProviders-CeSzDnx-.js} +1 -1
- package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
- package/dist/ui/index.html +5 -5
- package/package.json +1 -3
- package/packages/core/src/agent/agent-catalog.ts +98 -1
- package/packages/core/src/agent/agent-loop.ts +5 -44
- package/packages/core/src/agent/context-compiler.ts +6 -94
- package/packages/core/src/agent/conversation-store.ts +23 -1
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +8 -0
- package/packages/core/src/artifacts/store.ts +66 -8
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/gateway/google-host.ts +228 -0
- package/packages/core/src/gateway/initializer.ts +8 -0
- package/packages/core/src/gateway/routes/agents.ts +14 -0
- package/packages/core/src/gateway/routes/auth.ts +25 -3
- package/packages/core/src/gateway/routes/chat.ts +14 -1
- package/packages/core/src/gateway/routes/google.ts +252 -0
- package/packages/core/src/gateway/routes/meeting.ts +11 -3
- package/packages/core/src/gateway/routes/models.ts +27 -11
- package/packages/core/src/gateway/routes/multimodal.ts +19 -0
- package/packages/core/src/gateway/routes/providers.ts +19 -18
- package/packages/core/src/gateway/routes/system.ts +1 -3
- package/packages/core/src/gateway/routes/tts-local.ts +20 -374
- package/packages/core/src/gateway/routes/voice.ts +29 -35
- package/packages/core/src/gateway/server.ts +58 -32
- package/packages/core/src/gateway/tts/README.md +7 -86
- package/packages/core/src/gateway/tts/build.py +105 -0
- package/packages/core/src/gateway/tts/kitten.ts +282 -0
- package/packages/core/src/gateway/tts/python.d.ts +4 -0
- package/packages/core/src/gateway/tts/src/detect.ts +33 -39
- package/packages/core/src/gateway/tts/worker.py +80 -0
- package/packages/core/src/google/client.ts +123 -0
- package/packages/core/src/google/config.ts +60 -0
- package/packages/core/src/google/google.test.ts +287 -0
- package/packages/core/src/google/index.ts +5 -0
- package/packages/core/src/google/oauth.ts +144 -0
- package/packages/core/src/google/scopes.ts +41 -0
- package/packages/core/src/google/token-store.ts +33 -0
- package/packages/core/src/multimodal/attachment-ingest.ts +19 -4
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/storage/collections.ts +8 -8
- package/packages/core/src/storage/google-capabilities.ts +91 -0
- package/packages/core/src/storage/model-activation.ts +18 -0
- package/packages/core/src/storage/model-sync.ts +66 -14
- package/packages/core/src/storage/onboarding.ts +10 -2
- package/packages/core/src/storage/seed.ts +81 -18
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +1 -1
- package/packages/core/src/tools/google/calendar.ts +204 -0
- package/packages/core/src/tools/google/drive.ts +160 -0
- package/packages/core/src/tools/google/gmail.ts +579 -0
- package/packages/core/src/tools/google/index.ts +18 -0
- package/packages/core/src/tools/google/shared.ts +80 -0
- package/packages/core/src/tools/image/image-generate.ts +90 -0
- package/packages/core/src/tools/image/index.ts +13 -0
- package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
- package/packages/core/src/tools/index.ts +27 -0
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +10 -1
- package/packages/core/src/tools/office/office-leer-pdf.ts +1 -1
- package/packages/core/src/tools/office/office-leer-pptx.ts +4 -1
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +2 -2
- package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
- package/packages/core/src/voice/index.ts +123 -155
- package/packages/core/src/voice/local-model.ts +8 -0
- package/packages/core/src/voice/stt-models.ts +39 -0
- package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
- package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
- package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
- package/packages/skills/src/bundled-data.generated.ts +45 -0
- package/dist/ui/assets/AgentDetailPage-CyYbqzHr.js +0 -1
- package/dist/ui/assets/AgentsPage-CEWNs4Lt.js +0 -10
- package/dist/ui/assets/ChannelsPage-CmeXP-hI.js +0 -8
- package/dist/ui/assets/DashboardPage-C3z4kZXD.js +0 -6
- package/dist/ui/assets/LoginPage-DDisP8hm.js +0 -1
- package/dist/ui/assets/MeetingPage-CKyjxtFr.js +0 -1
- package/dist/ui/assets/ModelSelector-VVwpDrYF.js +0 -1
- package/dist/ui/assets/Office3DPage-CYxB6z2p.js +0 -727
- package/dist/ui/assets/ProvidersPage-CM9-E-Pf.js +0 -1
- package/dist/ui/assets/SettingsPage-BvD-vs5g.js +0 -9
- package/dist/ui/assets/VoicePage-CmudxYny.js +0 -307
- package/dist/ui/assets/WebChatPage-CnoXpEOl.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-C0W6p0lk.js +0 -156
- package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
- package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
- package/dist/ui/assets/select-v_3QBYrD.js +0 -1
- package/dist/ui/assets/terminal-BEcTK780.js +0 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
- package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
- package/packages/core/src/agent/jev-decisions.ts +0 -242
- package/packages/core/src/agent/jev-planner.ts +0 -293
- package/packages/core/src/gateway/tts/package.json +0 -25
- package/packages/core/src/gateway/tts/src/client.ts +0 -59
- package/packages/core/src/gateway/tts/src/index.ts +0 -15
- package/packages/core/src/gateway/tts/src/install.ts +0 -137
- package/packages/core/src/gateway/tts/src/models.ts +0 -50
- package/packages/core/src/gateway/tts/src/server.ts +0 -253
- /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
- /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
- /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
- /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
- /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
- /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
- /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
- /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
- /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
- /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
- /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
- /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
- /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
- /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
- /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
- /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
- /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
- /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
- /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
- /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
- /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
- /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
- /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
- /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
- /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
- /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
|
@@ -47,7 +47,6 @@ import { getHiveDb } from "../storage/hivedb"
|
|
|
47
47
|
import { listCatalogAgents, renderAgentRoutingCatalog } from "./catalog-selector"
|
|
48
48
|
import { expandToolAllowlist } from "./delegation-runtime"
|
|
49
49
|
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
50
|
-
import { describeSwarmCapabilities, planJevContext, renderSpecialistLine } from "./jev-planner"
|
|
51
50
|
|
|
52
51
|
const log = logger.child("context-compiler")
|
|
53
52
|
|
|
@@ -102,8 +101,6 @@ export interface CompiledContext {
|
|
|
102
101
|
tools: LLMToolDef[]
|
|
103
102
|
allTools: ContextTool[]
|
|
104
103
|
skills: SkillDescriptor[] // Skills loaded (minimal + discovered)
|
|
105
|
-
/** Jev's context plan, for the caller to publish once it knows the agent's resolved model. */
|
|
106
|
-
jevDecision?: { summary: string; savedTokens: number; latencyMs: number; costUsd: number; recommendedAgentId: string | null; mcpOff: string[] }
|
|
107
104
|
}
|
|
108
105
|
|
|
109
106
|
// ─── G9 causal context (buildAgentContext) ────────────────────────────────
|
|
@@ -219,7 +216,6 @@ export async function compileContext(opts: {
|
|
|
219
216
|
/** G9 causal stream id for this invocation (agent-loop.ts's causalStreamId). */
|
|
220
217
|
causalStreamId?: string
|
|
221
218
|
/** A resumed run restores the exact previously selected prompt and loadout. */
|
|
222
|
-
skipJev?: boolean
|
|
223
219
|
/**
|
|
224
220
|
* The window the provider will really read (resolveProviderConfig): the
|
|
225
221
|
* smaller of the model's and, for Ollama, num_ctx. Falls back to the model row.
|
|
@@ -637,11 +633,7 @@ export async function compileContext(opts: {
|
|
|
637
633
|
// (openai-compat-base.ts) — silently replaces the real prompt. The summary
|
|
638
634
|
// lives in `systemPrompt` instead (see conversationSummarySection below).
|
|
639
635
|
let messages: LLMMessage[] = toAPIMessages(recentMessages)
|
|
640
|
-
|
|
641
|
-
let jevAgentId: string | null = null
|
|
642
|
-
let jevAgentMcpOff: string[] = []
|
|
643
|
-
let omittedMessageIds: number[] = []
|
|
644
|
-
let omittedScratchpadKeys: string[] = []
|
|
636
|
+
const selectedSkills = allSkills
|
|
645
637
|
const objectiveSource = taskContext ?? userMessage
|
|
646
638
|
const objective = typeof objectiveSource === "string" ? objectiveSource
|
|
647
639
|
: objectiveSource.filter((p: ContentPart) => p.type === "text").map((p: ContentPart) => (p as { text: string }).text).join("\n")
|
|
@@ -649,33 +641,6 @@ export async function compileContext(opts: {
|
|
|
649
641
|
if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
|
|
650
642
|
return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
|
|
651
643
|
})
|
|
652
|
-
const swarm = opts.skipJev ? undefined : await describeSwarmCapabilities(effectiveMcpManager, { includeSpecialists: !isWorker })
|
|
653
|
-
.catch((err) => { log.warn(`[context-compiler] Swarm capability map failed: ${(err as Error).message}`); return undefined })
|
|
654
|
-
const jevPlan = opts.skipJev ? null : await planJevContext({
|
|
655
|
-
objective, messages, tools: toolsForLLM, allTools, skills: allSkills, scratchpadNotes, playbookRules, isWorker, swarm,
|
|
656
|
-
}).catch((err) => { log.warn(`[context-compiler] Jev planning failed: ${(err as Error).message}`); return null })
|
|
657
|
-
// Characters the classic path would have sent minus what Jev's plan sends,
|
|
658
|
-
// accumulated section by section; the office shows it as estimated savings.
|
|
659
|
-
let jevSavedChars = 0
|
|
660
|
-
const classicToolCount = toolsForLLM.length
|
|
661
|
-
if (jevPlan) {
|
|
662
|
-
jevSavedChars += JSON.stringify(messages).length - JSON.stringify(jevPlan.messages).length
|
|
663
|
-
jevSavedChars += JSON.stringify(toolsForLLM).length
|
|
664
|
-
messages = jevPlan.messages
|
|
665
|
-
toolsForLLM = jevPlan.tools
|
|
666
|
-
selectedSkills = allSkills.filter(s => minimalSkills.some(m => m.id === s.id) || jevPlan.selectedSkillNames.includes(s.name))
|
|
667
|
-
jevAgentId = jevPlan.agentId
|
|
668
|
-
jevAgentMcpOff = jevPlan.agentMcpOff
|
|
669
|
-
omittedMessageIds = recentMessages.filter((_, i) => !jevPlan.selectedMessageIds.includes(i)).map(row => row.id)
|
|
670
|
-
omittedScratchpadKeys = scratchpadNotes.filter(note => !jevPlan.selectedScratchpadKeys.includes(note.key)).map(note => note.key)
|
|
671
|
-
if (!isWorker && (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) && !toolsForLLM.some(t => t.function.name === "conversation_read")) {
|
|
672
|
-
const reader = allTools.find(t => t.name === "conversation_read")
|
|
673
|
-
if (reader) toolsForLLM.push({ type: "function", function: { name: reader.name, description: reader.description, parameters: reader.parameters } })
|
|
674
|
-
}
|
|
675
|
-
jevSavedChars -= JSON.stringify(toolsForLLM).length
|
|
676
|
-
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"}`)
|
|
677
|
-
}
|
|
678
|
-
|
|
679
644
|
// [STEP-10] STRATEGY 4: ISOLATE — Build context based on agent role
|
|
680
645
|
log.info(`[context-compiler] [STEP-10] Building system prompt...`)
|
|
681
646
|
let systemPrompt: string
|
|
@@ -716,49 +681,21 @@ export async function compileContext(opts: {
|
|
|
716
681
|
log.info(`[context-compiler] Injected ${related.length} related thread summar${related.length === 1 ? "y" : "ies"}`)
|
|
717
682
|
}
|
|
718
683
|
}
|
|
719
|
-
if (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) {
|
|
720
|
-
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`
|
|
721
|
-
systemPrompt += recoverable
|
|
722
|
-
jevSavedChars -= recoverable.length
|
|
723
|
-
}
|
|
724
|
-
|
|
725
684
|
// Only the live roster goes here — how to delegate, fan-out/fan-in and the
|
|
726
685
|
// execution-truth rules are static doctrine and live in the coordinator's
|
|
727
686
|
// stored prompt (storage/onboarding.ts), not duplicated per turn.
|
|
728
687
|
if (!isWorker) {
|
|
729
688
|
const catalogAgents = await listCatalogAgents()
|
|
730
|
-
|
|
731
|
-
if (jevPlan) {
|
|
732
|
-
// Ids, names and MCP state only: without them the coordinator spent
|
|
733
|
-
// iterations on agent_find just to learn who exists and what is
|
|
734
|
-
// connected. Descriptions stay behind agent_find.
|
|
735
|
-
const roster = swarm?.specialists.length
|
|
736
|
-
? swarm.specialists.map(renderSpecialistLine).join("\n")
|
|
737
|
-
: catalogAgents.map(a => `- ${a.id} (${a.name})`).join("\n")
|
|
738
|
-
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` : ""
|
|
739
|
-
if (jevAgentId && jevAgentMcpOff.length > 0) {
|
|
740
|
-
// Turning a server on starts processes and uses credentials: that is
|
|
741
|
-
// the user's call, so the coordinator asks instead of delegating.
|
|
742
|
-
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`
|
|
743
|
-
} else if (jevAgentId) {
|
|
744
|
-
rosterSection += `\n\n# ESPECIALISTA RECOMENDADO\nJev seleccionó ${jevAgentId} para una subtarea acotada. Delega con task_delegate cuando puedas formular objetivo y criterios verificables.\n`
|
|
745
|
-
}
|
|
746
|
-
systemPrompt += rosterSection
|
|
747
|
-
jevSavedChars += fullCatalog.length - rosterSection.length
|
|
748
|
-
} else {
|
|
749
|
-
systemPrompt += fullCatalog
|
|
750
|
-
}
|
|
689
|
+
systemPrompt += `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${renderAgentRoutingCatalog(catalogAgents)}\n`
|
|
751
690
|
}
|
|
752
691
|
|
|
753
|
-
const selectedPlaybookRules =
|
|
754
|
-
for (const rule of playbookRules) if (!selectedPlaybookRules.includes(rule)) jevSavedChars += rule.rule.length + 3
|
|
692
|
+
const selectedPlaybookRules = playbookRules
|
|
755
693
|
if (selectedPlaybookRules.length > 0) {
|
|
756
694
|
systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${selectedPlaybookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
|
|
757
695
|
}
|
|
758
696
|
|
|
759
697
|
// Inject scratchpad (Strategy: WRITE) — usando TOON para ahorro de tokens
|
|
760
|
-
const selectedScratchpadNotes =
|
|
761
|
-
for (const note of scratchpadNotes) if (!selectedScratchpadNotes.includes(note)) jevSavedChars += note.key.length + note.value.length + 4
|
|
698
|
+
const selectedScratchpadNotes = scratchpadNotes
|
|
762
699
|
if (selectedScratchpadNotes.length > 0) {
|
|
763
700
|
const scratchpadData: Record<string, string> = {}
|
|
764
701
|
for (const n of selectedScratchpadNotes) {
|
|
@@ -844,22 +781,11 @@ export async function compileContext(opts: {
|
|
|
844
781
|
|
|
845
782
|
// Discovered skills: list only (body arrives via agent-loop when tools are injected)
|
|
846
783
|
const discoveredOnly = selectedSkills.filter(s => !minimalNames.has(s.name))
|
|
847
|
-
if (jevPlan) {
|
|
848
|
-
// Classic lists every discovered skill in one line; Jev inlines the chosen bodies.
|
|
849
|
-
for (const skill of allSkills) {
|
|
850
|
-
if (minimalNames.has(skill.name)) continue
|
|
851
|
-
jevSavedChars += `- **${skill.name}**${skill.description ? ` — ${skill.description}` : ""}\n`.length
|
|
852
|
-
if (discoveredOnly.includes(skill)) jevSavedChars -= skill.body ? `\n## ${skill.name}\n${skill.body}\n`.length : 0
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
784
|
if (discoveredOnly.length > 0) {
|
|
856
785
|
let discoveredSection = `\n\n# SKILLS DESCUBIERTAS (relevantes para esta tarea)\n`
|
|
857
786
|
for (const skill of discoveredOnly) {
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
const desc = skill.description ? ` — ${skill.description}` : ""
|
|
861
|
-
discoveredSection += `- **${skill.name}**${desc}\n`
|
|
862
|
-
}
|
|
787
|
+
const desc = skill.description ? ` — ${skill.description}` : ""
|
|
788
|
+
discoveredSection += `- **${skill.name}**${desc}\n`
|
|
863
789
|
}
|
|
864
790
|
systemPrompt += discoveredSection
|
|
865
791
|
}
|
|
@@ -919,19 +845,6 @@ export async function compileContext(opts: {
|
|
|
919
845
|
`total=${estimatedTotal}/${modelContextWindow} (${budgetPct}%)`
|
|
920
846
|
)
|
|
921
847
|
|
|
922
|
-
const jevDecision = jevPlan ? {
|
|
923
|
-
summary: [
|
|
924
|
-
`${jevPlan.selectedMessageIds.length}/${recentMessages.length} mensajes`,
|
|
925
|
-
`${toolsForLLM.length}/${classicToolCount} herramientas`,
|
|
926
|
-
`${selectedSkills.length}/${allSkills.length} skills`,
|
|
927
|
-
].join(" · "),
|
|
928
|
-
savedTokens: Math.round(jevSavedChars / 4),
|
|
929
|
-
latencyMs: jevPlan.decision.latencyMs,
|
|
930
|
-
costUsd: jevPlan.decision.costUsd,
|
|
931
|
-
recommendedAgentId: jevAgentId,
|
|
932
|
-
mcpOff: jevAgentMcpOff,
|
|
933
|
-
} : undefined
|
|
934
|
-
|
|
935
848
|
return {
|
|
936
849
|
systemPrompt,
|
|
937
850
|
conversationSummarySection,
|
|
@@ -939,7 +852,6 @@ export async function compileContext(opts: {
|
|
|
939
852
|
tools: toolsForLLM,
|
|
940
853
|
allTools,
|
|
941
854
|
skills: selectedSkills,
|
|
942
|
-
jevDecision,
|
|
943
855
|
}
|
|
944
856
|
}
|
|
945
857
|
|
|
@@ -76,6 +76,25 @@ function storageId(threadId: string, seq: number): string {
|
|
|
76
76
|
return `${threadId}:${String(seq).padStart(15, "0")}`
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Lo que el modelo lee de una respuesta que entregó imágenes. Los resultados de
|
|
81
|
+
* herramienta no se guardan en el historial, así que sin esta nota el turno
|
|
82
|
+
* siguiente solo vería el texto y no sabría que la imagen ya existe ni su id
|
|
83
|
+
* (necesario para adjuntarla a un correo o reenviarla). Solo es contexto del
|
|
84
|
+
* modelo: lo que ve el usuario (content guardado, historial de la web) no cambia.
|
|
85
|
+
*/
|
|
86
|
+
function withImageNote(doc: ConversationDoc): string {
|
|
87
|
+
if (doc.role !== "assistant" || !doc.images_json) return doc.content
|
|
88
|
+
try {
|
|
89
|
+
const images = JSON.parse(doc.images_json) as Array<{ artifactId: string; mimeType: string }>
|
|
90
|
+
if (!images.length) return doc.content
|
|
91
|
+
const list = images.map((i) => `artifact_id=${i.artifactId} (${i.mimeType})`).join("; ")
|
|
92
|
+
return `${doc.content}\n\n[Sistema: con esta respuesta ya se entregó al usuario la imagen ${list}. ` +
|
|
93
|
+
`Ya existe: no la generes de nuevo. Para enviarla o adjuntarla (correo, canal) usa ese artifact_id con ` +
|
|
94
|
+
`send_file o con los adjuntos de la herramienta de correo.]`
|
|
95
|
+
} catch { return doc.content }
|
|
96
|
+
}
|
|
97
|
+
|
|
79
98
|
function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
|
|
80
99
|
const seq = parseInt(id.slice(id.lastIndexOf(":") + 1), 10)
|
|
81
100
|
// Legacy rows (written before `source` existed) used role:"system" as the
|
|
@@ -89,7 +108,7 @@ function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
|
|
|
89
108
|
channel: doc.channel,
|
|
90
109
|
role: legacyInternal ? "user" : (doc.role as StoredMessage["role"]),
|
|
91
110
|
source: doc.source ?? (legacyInternal ? "legacy_internal" : "message"),
|
|
92
|
-
content: doc
|
|
111
|
+
content: withImageNote(doc),
|
|
93
112
|
tool_calls_json: doc.tool_calls_json,
|
|
94
113
|
tool_call_id: doc.tool_call_id,
|
|
95
114
|
reasoning_content: doc.reasoning_content,
|
|
@@ -121,6 +140,8 @@ export async function addMessage(
|
|
|
121
140
|
tool_call_id?: string
|
|
122
141
|
reasoning_content?: string
|
|
123
142
|
source?: MessageSource
|
|
143
|
+
/** Imágenes entregadas al usuario con esta respuesta (se recuperan al recargar el historial). */
|
|
144
|
+
images?: Array<{ artifactId: string; mimeType: string }>
|
|
124
145
|
}
|
|
125
146
|
): Promise<number> {
|
|
126
147
|
// Handle multimodal content by extracting text for the content column
|
|
@@ -149,6 +170,7 @@ export async function addMessage(
|
|
|
149
170
|
tool_call_id: opts?.tool_call_id ?? null,
|
|
150
171
|
reasoning_content: opts?.reasoning_content ?? null,
|
|
151
172
|
source: opts?.source ?? "message",
|
|
173
|
+
images_json: opts?.images?.length ? JSON.stringify(opts.images) : null,
|
|
152
174
|
// Estimate tokens: content + tool_calls JSON
|
|
153
175
|
token_count: Math.max(1, estimateTokens(textContent) + estimateTokens(tool_calls_json ?? "")),
|
|
154
176
|
created_at: now,
|
|
@@ -270,7 +270,7 @@ export abstract class OpenAICompatBase implements LLMProvider {
|
|
|
270
270
|
): Promise<LLMResponse> {
|
|
271
271
|
// Without stream_options.include_usage an OpenAI-compatible stream reports
|
|
272
272
|
// no tokens at all: every NVIDIA call was recorded as 0 in / 0 out, so its
|
|
273
|
-
// cost
|
|
273
|
+
// cost never reached the dashboard. A server that
|
|
274
274
|
// does not know the field gets the same request without it.
|
|
275
275
|
const createStream = async (request: any) => {
|
|
276
276
|
try {
|
|
@@ -148,7 +148,23 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
|
|
|
148
148
|
// ──────────────────────────────────────────────────────────────────────────
|
|
149
149
|
// Ensamblar secciones en orden
|
|
150
150
|
// ──────────────────────────────────────────────────────────────────────────
|
|
151
|
-
|
|
151
|
+
// Capacidad de imágenes: solo se anuncia si hay un modelo generador elegido,
|
|
152
|
+
// para no prometer algo que la herramienta no puede cumplir.
|
|
153
|
+
let capabilitiesSection = ""
|
|
154
|
+
if (agent.role === "coordinator") {
|
|
155
|
+
try {
|
|
156
|
+
const { getImageModelId } = await import("../multimodal/image-generation")
|
|
157
|
+
if (await getImageModelId()) {
|
|
158
|
+
capabilitiesSection = `# CAPACIDADES\n\n` +
|
|
159
|
+
`Sí puedes crear imágenes nuevas (ilustraciones, logos, pósters, arte). La herramienta \`image_generate\` no está en tu lista inicial: ` +
|
|
160
|
+
`descúbrela con \`search_knowledge\` (por ejemplo "generar imagen") y úsala enseguida. ` +
|
|
161
|
+
`La imagen se muestra sola al usuario en el chat y en Telegram. No puedes editar imágenes existentes. ` +
|
|
162
|
+
`Nunca respondas que no puedes generar imágenes sin haber buscado antes la herramienta.\n\n`
|
|
163
|
+
}
|
|
164
|
+
} catch { /* sin modelo de imagen: no se anuncia */ }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const systemPrompt = `${ethicsSection}${agentSection}${userSection}${capabilitiesSection}`.trim()
|
|
152
168
|
|
|
153
169
|
log.info(`[prompt-builder] Built system prompt for agent=${agent.name} role=${agent.role}`)
|
|
154
170
|
|
|
@@ -240,6 +240,10 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
|
|
|
240
240
|
{ name: "search_knowledge", description: "Search everything Hive knows: native tools, MCP tools, skills, catalog agents and playbook rules. Spanish keywords: buscar herramienta, descubrir capacidades, qué puedo hacer, buscar skill, buscar conocimiento", category: "core", abstractionLevel: "atomic" },
|
|
241
241
|
{ name: "conversation_read", description: "Read earlier messages from this conversation by ID or search text when context is missing. Spanish keywords: recuperar contexto, leer historial, conversación anterior", category: "core", abstractionLevel: "atomic" },
|
|
242
242
|
|
|
243
|
+
// Imagen
|
|
244
|
+
{ name: "image_generate", description: "Create a new image from a text description (illustration, logo, poster, concept art, picture) using the image model chosen in Providers. Delivered to the user automatically. Cannot edit an existing image. Spanish keywords: crear imagen, generar imagen, dibujar, hazme una imagen, genera una foto, ilustración, logo, póster, arte, imagen de, dibuja", category: "image", abstractionLevel: "atomic" },
|
|
245
|
+
{ name: "office_leer_imagenes", description: "Read the images inside a Word or PowerPoint file (screenshots, charts, diagrams, scanned pages) by describing and transcribing them with the vision model chosen in Providers. Complements office_leer_docx / office_leer_pptx, which only return text. Spanish keywords: leer imágenes de un documento, imágenes dentro de word, imágenes de powerpoint, ocr de documento, capturas, gráficos de una presentación, leer figuras", category: "image", abstractionLevel: "atomic" },
|
|
246
|
+
|
|
243
247
|
// HTTP / REST
|
|
244
248
|
{ name: "api_request", description: "Perform an authorized HTTP request against a REST endpoint and validate the response. Spanish keywords: llamar api, request rest, consumir endpoint, petición http, hacer get, hacer post", category: "api", abstractionLevel: "atomic" },
|
|
245
249
|
|
|
@@ -475,6 +479,10 @@ export async function syncToolCatalogToIndex(tools?: ToolDescriptor[]): Promise<
|
|
|
475
479
|
for (const row of dbTools) {
|
|
476
480
|
if (catalogByName.has(row.name)) continue
|
|
477
481
|
|
|
482
|
+
// Las tools de Google solo se ofrecen con la cuenta conectada: sin conexión
|
|
483
|
+
// (o sin credenciales) no hay ejecutor y el modelo las descubriría para nada.
|
|
484
|
+
if (row.category === "google" && !row.active) continue
|
|
485
|
+
|
|
478
486
|
// Check if this is a legacy name with different separator
|
|
479
487
|
// (e.g. "cron_create" vs "cron.create" — seed was wrong, tools use dots)
|
|
480
488
|
const altName = row.name.includes("_")
|
|
@@ -7,7 +7,8 @@ import {
|
|
|
7
7
|
unlinkSync,
|
|
8
8
|
writeFileSync,
|
|
9
9
|
} from "node:fs";
|
|
10
|
-
import {
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { extname, join, resolve } from "node:path";
|
|
11
12
|
import { getHiveDir } from "../config/loader";
|
|
12
13
|
import { col, updateDoc } from "../storage/hive";
|
|
13
14
|
import type { ArtifactDoc } from "../storage/collections";
|
|
@@ -25,6 +26,31 @@ function extensionFor(mimeType: string, hint?: string): string {
|
|
|
25
26
|
return "bin";
|
|
26
27
|
}
|
|
27
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Dónde deja el usuario lo que Hive crea para él: el workspace del agente o, si
|
|
31
|
+
* no tiene, `~/Hive` (HIVE_OUTPUT_DIR lo reemplaza). Es una carpeta VISIBLE del
|
|
32
|
+
* usuario, a propósito: lo que se promete como "creado" no puede quedar oculto
|
|
33
|
+
* dentro de ~/.hive junto a la base de datos.
|
|
34
|
+
*/
|
|
35
|
+
export function resolveOutputDir(workspace?: string | null): string {
|
|
36
|
+
const ws = workspace?.trim();
|
|
37
|
+
if (ws) return resolve(ws.startsWith("~") ? join(homedir(), ws.slice(1)) : ws);
|
|
38
|
+
const override = process.env.HIVE_OUTPUT_DIR?.trim();
|
|
39
|
+
if (override) return resolve(override.startsWith("~") ? join(homedir(), override.slice(1)) : override);
|
|
40
|
+
return join(homedir(), "Hive");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Nombre de archivo legible y seguro: `2026-11-24_2158_abeja-robot-con-casco`. */
|
|
44
|
+
export function visibleFileBase(label: string, now: number): string {
|
|
45
|
+
const d = new Date(now);
|
|
46
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
47
|
+
const stamp = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}`;
|
|
48
|
+
const slug = label
|
|
49
|
+
.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
|
|
50
|
+
.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
|
|
51
|
+
return slug ? `${stamp}_${slug}` : stamp;
|
|
52
|
+
}
|
|
53
|
+
|
|
28
54
|
function hash(bytes: Uint8Array): string {
|
|
29
55
|
return createHash("sha256").update(bytes).digest("hex");
|
|
30
56
|
}
|
|
@@ -58,16 +84,46 @@ export async function createArtifact(input: {
|
|
|
58
84
|
width?: number | null;
|
|
59
85
|
height?: number | null;
|
|
60
86
|
now?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Cuándo caduca. `null` = nunca, para lo que es del usuario y no basura
|
|
89
|
+
* transitoria (p. ej. una imagen que pidió generar). Por omisión, 7 días.
|
|
90
|
+
*/
|
|
91
|
+
expiresAt?: number | null;
|
|
92
|
+
/**
|
|
93
|
+
* Guarda el archivo en una carpeta visible del usuario (workspace del agente
|
|
94
|
+
* o ~/Hive) en lugar de ~/.hive/artifacts. `folder` es una subcarpeta fija
|
|
95
|
+
* ("imagenes", "descargas"…) y `label` da el nombre legible del archivo.
|
|
96
|
+
*/
|
|
97
|
+
visible?: { workspace?: string | null; folder: string; label: string };
|
|
61
98
|
}): Promise<ArtifactDoc> {
|
|
62
99
|
const now = input.now ?? Date.now();
|
|
63
100
|
const id = randomUUID();
|
|
64
101
|
const root = input.rootDir ?? getHiveDir();
|
|
65
102
|
const mimeType = detectedMime(input.bytes, input.mimeType);
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
103
|
+
const ext = extensionFor(mimeType, input.extension);
|
|
104
|
+
let path: string;
|
|
105
|
+
if (input.visible) {
|
|
106
|
+
const dir = join(resolveOutputDir(input.visible.workspace), input.visible.folder.replace(/[^A-Za-z0-9_-]/g, ""));
|
|
107
|
+
mkdirSync(dir, { recursive: true });
|
|
108
|
+
const base = visibleFileBase(input.visible.label, now);
|
|
109
|
+
// "wx" no pisa nada: si ya existe un archivo con ese nombre, se numera.
|
|
110
|
+
for (let n = 0; ; n++) {
|
|
111
|
+
const candidate = join(dir, `${base}${n ? `-${n + 1}` : ""}.${ext}`);
|
|
112
|
+
try {
|
|
113
|
+
writeFileSync(candidate, input.bytes, { flag: "wx" });
|
|
114
|
+
path = candidate;
|
|
115
|
+
break;
|
|
116
|
+
} catch (e) {
|
|
117
|
+
if ((e as NodeJS.ErrnoException).code !== "EEXIST" || n > 999) throw e;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
122
|
+
const dir = join(root, "artifacts", day);
|
|
123
|
+
mkdirSync(dir, { recursive: true });
|
|
124
|
+
path = join(dir, `${id}.${ext}`);
|
|
125
|
+
writeFileSync(path, input.bytes, { flag: "wx" });
|
|
126
|
+
}
|
|
71
127
|
|
|
72
128
|
const doc: ArtifactDoc = {
|
|
73
129
|
id,
|
|
@@ -83,7 +139,7 @@ export async function createArtifact(input: {
|
|
|
83
139
|
height: input.height ?? null,
|
|
84
140
|
status: "active",
|
|
85
141
|
created_at: now,
|
|
86
|
-
expires_at: now + ARTIFACT_RETENTION_MS,
|
|
142
|
+
expires_at: input.expiresAt !== undefined ? input.expiresAt : now + ARTIFACT_RETENTION_MS,
|
|
87
143
|
expired_at: null,
|
|
88
144
|
};
|
|
89
145
|
|
|
@@ -233,7 +289,9 @@ export async function expireArtifacts(now = Date.now()): Promise<{ expired: numb
|
|
|
233
289
|
const rows = await artifacts.scan({});
|
|
234
290
|
let expired = 0;
|
|
235
291
|
for (const row of rows) {
|
|
236
|
-
|
|
292
|
+
// `null` es explícito: el usuario pidió conservarlo. Saltarlo ANTES de
|
|
293
|
+
// comparar fechas evita que un `null > now` (que es false) lo borre.
|
|
294
|
+
if (row.doc.status !== "active" || row.doc.expires_at === null || row.doc.expires_at > now) continue;
|
|
237
295
|
try {
|
|
238
296
|
if (existsSync(row.doc.path)) unlinkSync(row.doc.path);
|
|
239
297
|
} catch {
|
|
@@ -15,8 +15,6 @@ export type CanvasEventType =
|
|
|
15
15
|
| "canvas:edge_add"
|
|
16
16
|
| "canvas:edge_remove"
|
|
17
17
|
| "canvas:work_event"
|
|
18
|
-
| "canvas:jev_decision"
|
|
19
|
-
| "canvas:jev_status"
|
|
20
18
|
| "ag-ui:event"
|
|
21
19
|
|
|
22
20
|
export type CanvasWorkPhase =
|
|
@@ -39,23 +37,6 @@ export interface CanvasWorkEvent {
|
|
|
39
37
|
detail?: string | null
|
|
40
38
|
}
|
|
41
39
|
|
|
42
|
-
/** One Jev decision, shown by the office's oracle as a beam to the agent it advised. */
|
|
43
|
-
export interface CanvasJevDecision {
|
|
44
|
-
eventId: string
|
|
45
|
-
agentId: string
|
|
46
|
-
kind: "context" | "iteration" | "parallel"
|
|
47
|
-
/** Short Spanish description of what was selected ("4/15 mensajes · 9/24 herramientas"). */
|
|
48
|
-
summary: string
|
|
49
|
-
/** Estimated main-model input tokens this decision avoided (chars/4); negative when it added context. */
|
|
50
|
-
savedTokens: number
|
|
51
|
-
latencyMs: number
|
|
52
|
-
costUsd: number
|
|
53
|
-
recommendedAgentId?: string | null
|
|
54
|
-
/** MCP servers the recommended specialist needs that are off; the coordinator asks the user to turn them on. */
|
|
55
|
-
mcpOff?: string[]
|
|
56
|
-
totals: { decisions: number; savedTokens: number; costUsd: number }
|
|
57
|
-
}
|
|
58
|
-
|
|
59
40
|
const subscribers = new Set<{ send: (data: string) => void }>()
|
|
60
41
|
let workEventSequence = 0
|
|
61
42
|
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integración de Hive con el módulo `google/`: credenciales desde el entorno,
|
|
3
|
+
* tokens cifrados en el almacén de secretos y estado efímero del flujo OAuth.
|
|
4
|
+
*/
|
|
5
|
+
import { configureGoogle, isGoogleConfigured } from "../google/config.ts";
|
|
6
|
+
import { parseServices } from "../google/scopes.ts";
|
|
7
|
+
import type { GoogleService } from "../google/scopes.ts";
|
|
8
|
+
import type { GoogleTokenSet, GoogleTokenStore } from "../google/token-store.ts";
|
|
9
|
+
import { deleteSecret, loadSecret, storeSecret } from "../storage/crypto.ts";
|
|
10
|
+
import { logger } from "../utils/logger.ts";
|
|
11
|
+
|
|
12
|
+
const log = logger.child("google");
|
|
13
|
+
|
|
14
|
+
const secretKey = (userId: string) => `google:tokens:${userId}`;
|
|
15
|
+
|
|
16
|
+
/** Los tokens van por el almacén de secretos (keychain o colección cifrada), nunca en claro. */
|
|
17
|
+
export const secretTokenStore: GoogleTokenStore = {
|
|
18
|
+
async get(userId) {
|
|
19
|
+
const raw = await loadSecret(secretKey(userId));
|
|
20
|
+
if (!raw) return null;
|
|
21
|
+
try { return JSON.parse(raw) as GoogleTokenSet; } catch { return null; }
|
|
22
|
+
},
|
|
23
|
+
async put(userId, tokens) {
|
|
24
|
+
await storeSecret(secretKey(userId), JSON.stringify(tokens));
|
|
25
|
+
},
|
|
26
|
+
async delete(userId) {
|
|
27
|
+
await deleteSecret(secretKey(userId));
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export function publicBaseUrl(): string | null {
|
|
32
|
+
const v = process.env.HIVE_PUBLIC_URL?.replace(/\/$/, "");
|
|
33
|
+
return v || null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Activa Google si hay `GOOGLE_CLIENT_ID` y `GOOGLE_CLIENT_SECRET`. Idempotente.
|
|
38
|
+
* Sin ellas no pasa nada: las tools no entran al loadout y la UI oculta el botón.
|
|
39
|
+
*/
|
|
40
|
+
export function initGoogleFromEnv(): boolean {
|
|
41
|
+
if (isGoogleConfigured()) return true;
|
|
42
|
+
const clientId = process.env.GOOGLE_CLIENT_ID?.trim();
|
|
43
|
+
const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
|
|
44
|
+
if (!clientId || !clientSecret) return false;
|
|
45
|
+
const base = publicBaseUrl() ?? `http://127.0.0.1:${process.env.HIVE_PORT ?? "18790"}`;
|
|
46
|
+
const redirectUri = process.env.GOOGLE_REDIRECT_URI?.trim() || `${base}/api/google/oauth/callback`;
|
|
47
|
+
configureGoogle({
|
|
48
|
+
clientId, clientSecret, redirectUri,
|
|
49
|
+
services: parseServices(process.env.GOOGLE_SCOPES),
|
|
50
|
+
tokenStore: secretTokenStore,
|
|
51
|
+
});
|
|
52
|
+
log.info(`Google activado (redirect ${redirectUri})`);
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ─── Estado efímero del flujo OAuth y códigos de login ──────────────────────
|
|
57
|
+
|
|
58
|
+
export interface OAuthState {
|
|
59
|
+
purpose: "login" | "connect";
|
|
60
|
+
userId: string | null;
|
|
61
|
+
codeVerifier: string;
|
|
62
|
+
services: GoogleService[];
|
|
63
|
+
/** El mismo que se envió a Google: el intercambio debe repetirlo idéntico. */
|
|
64
|
+
redirectUri: string;
|
|
65
|
+
/** Origen al que se devuelve al navegador (el mismo desde el que se inició). */
|
|
66
|
+
origin: string;
|
|
67
|
+
/** Si el flujo se abrió en el navegador del sistema (app de escritorio): ticket que la app consulta. */
|
|
68
|
+
ticket?: string;
|
|
69
|
+
expiresAt: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const STATE_TTL_MS = 10 * 60_000;
|
|
73
|
+
const CODE_TTL_MS = 60_000;
|
|
74
|
+
const states = new Map<string, OAuthState>();
|
|
75
|
+
const loginCodes = new Map<string, number>();
|
|
76
|
+
|
|
77
|
+
function sweep(now = Date.now()) {
|
|
78
|
+
for (const [k, v] of states) if (v.expiresAt <= now) states.delete(k);
|
|
79
|
+
for (const [k, exp] of loginCodes) if (exp <= now) loginCodes.delete(k);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function saveState(state: string, data: Omit<OAuthState, "expiresAt">): void {
|
|
83
|
+
sweep();
|
|
84
|
+
states.set(state, { ...data, expiresAt: Date.now() + STATE_TTL_MS });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Un solo uso: el `state` se consume al leerlo. */
|
|
88
|
+
export function takeState(state: string | null): OAuthState | null {
|
|
89
|
+
if (!state) return null;
|
|
90
|
+
const s = states.get(state);
|
|
91
|
+
states.delete(state);
|
|
92
|
+
return s && s.expiresAt > Date.now() ? s : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function issueLoginCode(): string {
|
|
96
|
+
sweep();
|
|
97
|
+
const code = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
|
|
98
|
+
loginCodes.set(code, Date.now() + CODE_TTL_MS);
|
|
99
|
+
return code;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function consumeLoginCode(code: string | undefined): boolean {
|
|
103
|
+
if (!code) return false;
|
|
104
|
+
const exp = loginCodes.get(code);
|
|
105
|
+
loginCodes.delete(code);
|
|
106
|
+
return !!exp && exp > Date.now();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ─── Traspaso al navegador del sistema (app de escritorio) ──────────────────
|
|
110
|
+
//
|
|
111
|
+
// Google rechaza OAuth dentro de un WebView embebido (`disallowed_useragent`),
|
|
112
|
+
// así que en Tauri el flujo corre en el navegador del sistema y la ventana de
|
|
113
|
+
// la app consulta un ticket hasta que el callback lo resuelve.
|
|
114
|
+
|
|
115
|
+
export type TicketResult =
|
|
116
|
+
| { status: "pending" }
|
|
117
|
+
| { status: "done"; purpose: "login" | "connect" }
|
|
118
|
+
| { status: "error"; error: string };
|
|
119
|
+
|
|
120
|
+
const tickets = new Map<string, { result: TicketResult; expiresAt: number }>();
|
|
121
|
+
|
|
122
|
+
export function createTicket(): string {
|
|
123
|
+
sweep();
|
|
124
|
+
const id = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
|
|
125
|
+
tickets.set(id, { result: { status: "pending" }, expiresAt: Date.now() + STATE_TTL_MS });
|
|
126
|
+
return id;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function resolveTicket(id: string, result: TicketResult): void {
|
|
130
|
+
const t = tickets.get(id);
|
|
131
|
+
if (t) t.result = result;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Devuelve el estado; un resultado final se entrega una sola vez. */
|
|
135
|
+
export function pollTicket(id: string | null): TicketResult {
|
|
136
|
+
const t = id ? tickets.get(id) : undefined;
|
|
137
|
+
if (!id || !t || t.expiresAt <= Date.now()) {
|
|
138
|
+
if (id) tickets.delete(id);
|
|
139
|
+
return { status: "error", error: "expired" };
|
|
140
|
+
}
|
|
141
|
+
if (t.result.status !== "pending") tickets.delete(id);
|
|
142
|
+
return t.result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ─── Redirect URI y origen ──────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
const CALLBACK_PATH = "/api/google/oauth/callback";
|
|
148
|
+
|
|
149
|
+
export function isLoopbackHostname(hostname: string): boolean {
|
|
150
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const hasForwardHeaders = (req: Request) =>
|
|
154
|
+
req.headers.has("x-forwarded-for") || req.headers.has("x-forwarded-host") || req.headers.has("forwarded");
|
|
155
|
+
|
|
156
|
+
/** Petición directa a una dirección de loopback, sin proxy de por medio. */
|
|
157
|
+
export function isLoopbackRequest(req: Request): boolean {
|
|
158
|
+
return isLoopbackHostname(new URL(req.url).hostname) && !hasForwardHeaders(req);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* La app de escritorio lanza el gateway como hijo (`HIVE_GATEWAY_CHILD=1`) y
|
|
163
|
+
* habla con él por loopback: solo ahí tiene sentido abrir el navegador del
|
|
164
|
+
* sistema desde el servidor.
|
|
165
|
+
*/
|
|
166
|
+
export function isDesktopGatewayRequest(req: Request): boolean {
|
|
167
|
+
return process.env.HIVE_GATEWAY_CHILD === "1" && isLoopbackRequest(req);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* URI de retorno de esta solicitud. En loopback el puerto cambia (18790 o uno
|
|
172
|
+
* libre), así que se toma del origen real; un cliente OAuth de Google «de
|
|
173
|
+
* escritorio» lo admite sin registrarlo, uno «web» exige registrar cada URI.
|
|
174
|
+
*/
|
|
175
|
+
export function resolveRedirectUri(req: Request): string {
|
|
176
|
+
const forced = process.env.GOOGLE_REDIRECT_URI?.trim();
|
|
177
|
+
if (forced) return forced;
|
|
178
|
+
const url = new URL(req.url);
|
|
179
|
+
if (isLoopbackRequest(req)) return `${url.origin}${CALLBACK_PATH}`;
|
|
180
|
+
return `${publicBaseUrl() ?? url.origin}${CALLBACK_PATH}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A dónde vuelve el navegador al terminar: la misma origin desde la que empezó. */
|
|
184
|
+
export function resolveReturnOrigin(req: Request): string {
|
|
185
|
+
const url = new URL(req.url);
|
|
186
|
+
return isLoopbackRequest(req) ? url.origin : publicBaseUrl() ?? url.origin;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ─── Abrir el navegador del sistema ─────────────────────────────────────────
|
|
190
|
+
|
|
191
|
+
type Opener = (url: string) => void;
|
|
192
|
+
|
|
193
|
+
/** Sin shell ni interpolación: la URL va como argumento, no como texto de un comando. */
|
|
194
|
+
const defaultOpener: Opener = (url) => {
|
|
195
|
+
const attempts: string[][] =
|
|
196
|
+
process.platform === "win32" ? [["rundll32", "url.dll,FileProtocolHandler", url]]
|
|
197
|
+
: process.platform === "darwin" ? [["open", url]]
|
|
198
|
+
: [["gio", "open", url], ["xdg-open", url], ["sensible-browser", url], ["x-www-browser", url]];
|
|
199
|
+
for (const argv of attempts) {
|
|
200
|
+
try {
|
|
201
|
+
Bun.spawn(argv, { stdin: "ignore", stdout: "ignore", stderr: "ignore" }).unref();
|
|
202
|
+
return;
|
|
203
|
+
} catch { /* probar el siguiente */ }
|
|
204
|
+
}
|
|
205
|
+
log.warn("No se encontró ningún navegador para abrir el flujo de Google");
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
let opener: Opener = defaultOpener;
|
|
209
|
+
|
|
210
|
+
/** Solo abre URLs de Google: este servidor nunca abre algo que no generó. */
|
|
211
|
+
export function openExternal(url: string): boolean {
|
|
212
|
+
if (new URL(url).origin !== "https://accounts.google.com") return false;
|
|
213
|
+
opener(url);
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Sólo para tests. */
|
|
218
|
+
export function setExternalOpener(fn: Opener | null): void {
|
|
219
|
+
opener = fn ?? defaultOpener;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Sólo para tests. */
|
|
223
|
+
export function resetGoogleHostState(): void {
|
|
224
|
+
states.clear();
|
|
225
|
+
loginCodes.clear();
|
|
226
|
+
tickets.clear();
|
|
227
|
+
opener = defaultOpener;
|
|
228
|
+
}
|