@johpaz/hive-agents 1.1.5 → 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.
Files changed (206) hide show
  1. package/README.md +4 -10
  2. package/dist/hive.js +218257 -148718
  3. package/dist/tool-worker.js +68422 -1622
  4. package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-v-VggXW3.js} +4 -4
  5. package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
  6. package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
  7. package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-D7557C0J.js} +1 -1
  8. package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-R9UDWfR2.js → ApiClientPage-uuBnrh0y.js} +1 -1
  10. package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
  11. package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
  12. package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
  13. package/dist/ui/assets/{LogsPage-DICMU_7m.js → LogsPage-mcqOYvGw.js} +1 -1
  14. package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
  15. package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
  16. package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
  17. package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
  18. package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
  19. package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
  20. package/dist/ui/assets/{RecoverPage-Blms3NBa.js → RecoverPage-B6qvBBIl.js} +1 -1
  21. package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
  22. package/dist/ui/assets/{SetupPage-CAjLseE_.js → SetupPage-OaouFLGD.js} +1 -1
  23. package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
  24. package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
  25. package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
  26. package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
  27. package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
  28. package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
  29. package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
  30. package/dist/ui/assets/{conversationsStore-DhM07qYi.js → conversationsStore-D6XgjMr1.js} +1 -1
  31. package/dist/ui/assets/{dialog-BP3GTCPn.js → dialog-DO1fQCF7.js} +1 -1
  32. package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
  33. package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
  34. package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
  35. package/dist/ui/assets/index-BKNFH2al.css +2 -0
  36. package/dist/ui/assets/index-U0e4e5mL.js +156 -0
  37. package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
  38. package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
  39. package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
  40. package/dist/ui/assets/select-BjBXxyxL.js +1 -0
  41. package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
  42. package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
  43. package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
  44. package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
  45. package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
  46. package/dist/ui/assets/{useAudioDevices-zj0fuGwZ.js → useAudioDevices-wZArmV3m.js} +1 -1
  47. package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
  48. package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
  49. package/dist/ui/assets/{useProviders-Dj1k5PCk.js → useProviders-CeSzDnx-.js} +1 -1
  50. package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
  51. package/dist/ui/index.html +5 -5
  52. package/package.json +1 -3
  53. package/packages/cli/src/commands/onboard.ts +3 -2
  54. package/packages/core/src/agent/agent-catalog.ts +98 -1
  55. package/packages/core/src/agent/agent-loop.ts +5 -44
  56. package/packages/core/src/agent/context-compiler.ts +6 -94
  57. package/packages/core/src/agent/conversation-store.ts +23 -1
  58. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
  59. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  60. package/packages/core/src/agent/prompt-builder.ts +17 -1
  61. package/packages/core/src/agent/tool-selector.ts +12 -0
  62. package/packages/core/src/artifacts/store.ts +73 -9
  63. package/packages/core/src/canvas/emitter.ts +0 -19
  64. package/packages/core/src/channels/base.ts +26 -0
  65. package/packages/core/src/channels/discord.ts +18 -2
  66. package/packages/core/src/channels/slack.ts +37 -7
  67. package/packages/core/src/channels/telegram.ts +39 -11
  68. package/packages/core/src/channels/whatsapp.ts +16 -1
  69. package/packages/core/src/gateway/channel-notify.ts +42 -0
  70. package/packages/core/src/gateway/google-host.ts +228 -0
  71. package/packages/core/src/gateway/initializer.ts +8 -0
  72. package/packages/core/src/gateway/routes/agents.ts +14 -0
  73. package/packages/core/src/gateway/routes/artifacts.ts +4 -0
  74. package/packages/core/src/gateway/routes/auth.ts +25 -3
  75. package/packages/core/src/gateway/routes/chat.ts +14 -1
  76. package/packages/core/src/gateway/routes/google.ts +252 -0
  77. package/packages/core/src/gateway/routes/meeting.ts +11 -3
  78. package/packages/core/src/gateway/routes/models.ts +27 -11
  79. package/packages/core/src/gateway/routes/multimodal.ts +38 -0
  80. package/packages/core/src/gateway/routes/providers.ts +19 -18
  81. package/packages/core/src/gateway/routes/system.ts +1 -3
  82. package/packages/core/src/gateway/routes/tts-local.ts +20 -374
  83. package/packages/core/src/gateway/routes/voice.ts +29 -35
  84. package/packages/core/src/gateway/server.ts +97 -48
  85. package/packages/core/src/gateway/tts/README.md +7 -86
  86. package/packages/core/src/gateway/tts/build.py +105 -0
  87. package/packages/core/src/gateway/tts/kitten.ts +282 -0
  88. package/packages/core/src/gateway/tts/python.d.ts +4 -0
  89. package/packages/core/src/gateway/tts/src/detect.ts +33 -39
  90. package/packages/core/src/gateway/tts/worker.py +80 -0
  91. package/packages/core/src/gateway/webchat-turn.ts +15 -13
  92. package/packages/core/src/google/client.ts +123 -0
  93. package/packages/core/src/google/config.ts +60 -0
  94. package/packages/core/src/google/google.test.ts +287 -0
  95. package/packages/core/src/google/index.ts +5 -0
  96. package/packages/core/src/google/oauth.ts +144 -0
  97. package/packages/core/src/google/scopes.ts +41 -0
  98. package/packages/core/src/google/token-store.ts +33 -0
  99. package/packages/core/src/multimodal/attachment-ingest.ts +190 -0
  100. package/packages/core/src/multimodal/image-generation.ts +244 -0
  101. package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
  102. package/packages/core/src/multimodal/vision-service.ts +25 -0
  103. package/packages/core/src/storage/collections.ts +8 -8
  104. package/packages/core/src/storage/google-capabilities.ts +91 -0
  105. package/packages/core/src/storage/model-activation.ts +18 -0
  106. package/packages/core/src/storage/model-sync.ts +66 -14
  107. package/packages/core/src/storage/onboarding.ts +10 -2
  108. package/packages/core/src/storage/seed.ts +107 -24
  109. package/packages/core/src/storage/usage.ts +0 -52
  110. package/packages/core/src/tool-runtime/index.ts +2 -0
  111. package/packages/core/src/tools/agents/get-available-models.ts +1 -3
  112. package/packages/core/src/tools/core/index.ts +80 -2
  113. package/packages/core/src/tools/google/calendar.ts +204 -0
  114. package/packages/core/src/tools/google/drive.ts +160 -0
  115. package/packages/core/src/tools/google/gmail.ts +579 -0
  116. package/packages/core/src/tools/google/index.ts +18 -0
  117. package/packages/core/src/tools/google/shared.ts +80 -0
  118. package/packages/core/src/tools/image/image-generate.ts +90 -0
  119. package/packages/core/src/tools/image/index.ts +13 -0
  120. package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
  121. package/packages/core/src/tools/index.ts +27 -0
  122. package/packages/core/src/tools/office/index.ts +9 -0
  123. package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
  124. package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
  125. package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
  126. package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
  127. package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
  128. package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
  129. package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
  130. package/packages/core/src/tools/office/office-images.ts +137 -0
  131. package/packages/core/src/tools/office/office-leer-docx.ts +16 -3
  132. package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
  133. package/packages/core/src/tools/office/office-leer-pptx.ts +54 -88
  134. package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
  135. package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
  136. package/packages/core/src/tools/office/pdf-text.ts +186 -0
  137. package/packages/core/src/tools/office/pptx-slides.ts +83 -0
  138. package/packages/core/src/tools/office/resolve-input.ts +49 -0
  139. package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
  140. package/packages/core/src/voice/index.ts +123 -155
  141. package/packages/core/src/voice/local-model.ts +8 -0
  142. package/packages/core/src/voice/stt-models.ts +39 -0
  143. package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
  144. package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
  145. package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
  146. package/packages/skills/src/bundled-data.generated.ts +45 -0
  147. package/dist/ui/assets/AgentDetailPage-BVtE88U5.js +0 -1
  148. package/dist/ui/assets/AgentsPage-BOIJ55cj.js +0 -10
  149. package/dist/ui/assets/ChannelsPage-C5V2BmjL.js +0 -8
  150. package/dist/ui/assets/DashboardPage-B18gMzNj.js +0 -6
  151. package/dist/ui/assets/LoginPage-nrsYF9AY.js +0 -1
  152. package/dist/ui/assets/MeetingPage-xslJGfIz.js +0 -1
  153. package/dist/ui/assets/ModelSelector-BX4IvuYY.js +0 -1
  154. package/dist/ui/assets/Office3DPage-a6cuzt5X.js +0 -727
  155. package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
  156. package/dist/ui/assets/SettingsPage-BBeeq_QS.js +0 -9
  157. package/dist/ui/assets/VoicePage-BeSSYstD.js +0 -307
  158. package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
  159. package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
  160. package/dist/ui/assets/index-BG3nUPKq.js +0 -156
  161. package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
  162. package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
  163. package/dist/ui/assets/select-v_3QBYrD.js +0 -1
  164. package/dist/ui/assets/terminal-BEcTK780.js +0 -1
  165. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
  166. package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
  167. package/packages/core/src/agent/jev-decisions.ts +0 -242
  168. package/packages/core/src/agent/jev-planner.ts +0 -293
  169. package/packages/core/src/gateway/tts/package.json +0 -25
  170. package/packages/core/src/gateway/tts/src/client.ts +0 -59
  171. package/packages/core/src/gateway/tts/src/index.ts +0 -15
  172. package/packages/core/src/gateway/tts/src/install.ts +0 -137
  173. package/packages/core/src/gateway/tts/src/models.ts +0 -50
  174. package/packages/core/src/gateway/tts/src/server.ts +0 -253
  175. /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
  176. /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
  177. /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
  178. /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
  179. /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
  180. /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
  181. /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
  182. /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
  183. /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
  184. /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
  185. /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
  186. /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
  187. /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
  188. /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
  189. /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
  190. /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
  191. /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
  192. /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
  193. /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
  194. /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
  195. /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
  196. /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
  197. /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
  198. /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
  199. /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
  200. /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
  201. /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
  202. /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
  203. /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
  204. /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
  205. /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
  206. /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
- let selectedSkills = allSkills
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
- const fullCatalog = `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${renderAgentRoutingCatalog(catalogAgents)}\n`
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 = jevPlan ? playbookRules.filter(rule => jevPlan.selectedPlaybookIds.includes(rule.id)) : playbookRules
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 = jevPlan ? scratchpadNotes.filter(note => jevPlan.selectedScratchpadKeys.includes(note.key)) : scratchpadNotes
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
- if (jevPlan && skill.body) discoveredSection += `\n## ${skill.name}\n${skill.body}\n`
859
- else {
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.content,
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 and Jev's savings on it never reached the dashboard. A server that
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 {
@@ -18,6 +18,7 @@ export const MINIMAL_TOOLS = new Set([
18
18
  "search_knowledge",
19
19
  // Communication with the user
20
20
  "notify",
21
+ "send_file",
21
22
  "report_progress",
22
23
  // Notes that survive context compaction
23
24
  "save_note",
@@ -148,7 +148,23 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
148
148
  // ──────────────────────────────────────────────────────────────────────────
149
149
  // Ensamblar secciones en orden
150
150
  // ──────────────────────────────────────────────────────────────────────────
151
- const systemPrompt = `${ethicsSection}${agentSection}${userSection}`.trim()
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
 
@@ -158,6 +158,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
158
158
 
159
159
  // Notifications/reporting
160
160
  { name: "notify", description: "Send system notification, alert user with message or alert. Spanish keywords: notificar, enviar notificación, alertar, aviso, alarma", category: "core", abstractionLevel: "atomic" },
161
+ { name: "send_file", description: "Send a file (Word, Excel, PDF, image) to the user in the current chat, return a corrected document. Spanish keywords: enviar archivo, enviar documento, devolver archivo corregido, mandar excel, mandar word, mandar pdf", category: "core", abstractionLevel: "atomic" },
161
162
  { name: "report_progress", description: "Report progress to user, inform user of current status and completion. Spanish keywords: reportar progreso, informar estado, actualizar,报告进度, progreso", category: "core", abstractionLevel: "atomic" },
162
163
 
163
164
  // Browser automation
@@ -239,6 +240,10 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
239
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" },
240
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" },
241
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
+
242
247
  // HTTP / REST
243
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" },
244
249
 
@@ -256,6 +261,9 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
256
261
  { name: "office_escribir_pdf", description: "Generate a PDF document. Spanish keywords: crear pdf, generar pdf, escribir pdf, exportar a pdf", category: "office", abstractionLevel: "atomic" },
257
262
  { name: "office_escribir_docx", description: "Generate a Word document. Spanish keywords: crear word, generar docx, escribir documento word, exportar a word", category: "office", abstractionLevel: "atomic" },
258
263
  { name: "office_escribir_xlsx", description: "Generate an Excel spreadsheet. Spanish keywords: crear excel, generar xlsx, escribir hoja de cálculo, exportar a excel, armar planilla", category: "office", abstractionLevel: "atomic" },
264
+ { name: "office_editar_xlsx", description: "Edit an existing Excel file changing only given cells, keeping formatting; saves a copy. Spanish keywords: editar excel, corregir excel, modificar celdas, mejorar planilla", category: "office", abstractionLevel: "atomic" },
265
+ { name: "office_editar_docx", description: "Edit an existing Word file: replace text and append paragraphs keeping styles; saves a copy. Spanish keywords: editar word, corregir word, reemplazar texto en documento, mejorar documento", category: "office", abstractionLevel: "atomic" },
266
+ { name: "office_editar_pptx", description: "Edit an existing PowerPoint file replacing text in slides and notes, keeping design; saves a copy. Spanish keywords: editar powerpoint, corregir presentación, reemplazar texto en diapositivas, mejorar pptx", category: "office", abstractionLevel: "atomic" },
259
267
  { name: "office_escribir_pptx", description: "Generate a PowerPoint presentation. Spanish keywords: crear powerpoint, generar pptx, escribir presentación, armar diapositivas", category: "office", abstractionLevel: "atomic" },
260
268
  ]
261
269
 
@@ -471,6 +479,10 @@ export async function syncToolCatalogToIndex(tools?: ToolDescriptor[]): Promise<
471
479
  for (const row of dbTools) {
472
480
  if (catalogByName.has(row.name)) continue
473
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
+
474
486
  // Check if this is a legacy name with different separator
475
487
  // (e.g. "cron_create" vs "cron.create" — seed was wrong, tools use dots)
476
488
  const altName = row.name.includes("_")
@@ -7,20 +7,50 @@ import {
7
7
  unlinkSync,
8
8
  writeFileSync,
9
9
  } from "node:fs";
10
- import { extname, join } from "node:path";
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";
14
15
 
15
16
  const ARTIFACT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
16
17
 
17
- function extensionFor(mimeType: string): string {
18
+ function extensionFor(mimeType: string, hint?: string): string {
19
+ // Un adjunto del usuario conserva su extensión real (.docx, .xlsx, .pdf…): las
20
+ // tools office_leer_* deciden por extensión y un ".bin" no se abriría.
21
+ const clean = hint?.toLowerCase().replace(/^\./, "");
22
+ if (clean && /^[a-z0-9]{1,8}$/.test(clean)) return clean;
18
23
  if (mimeType === "image/png") return "png";
19
24
  if (mimeType === "image/jpeg") return "jpg";
20
25
  if (mimeType === "image/webp") return "webp";
21
26
  return "bin";
22
27
  }
23
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
+
24
54
  function hash(bytes: Uint8Array): string {
25
55
  return createHash("sha256").update(bytes).digest("hex");
26
56
  }
@@ -49,19 +79,51 @@ export async function createArtifact(input: {
49
79
  runId?: string | null;
50
80
  taskId?: string | null;
51
81
  rootDir?: string;
82
+ /** Extensión original del archivo (sin punto), p. ej. "docx". */
83
+ extension?: string;
52
84
  width?: number | null;
53
85
  height?: number | null;
54
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 };
55
98
  }): Promise<ArtifactDoc> {
56
99
  const now = input.now ?? Date.now();
57
100
  const id = randomUUID();
58
101
  const root = input.rootDir ?? getHiveDir();
59
102
  const mimeType = detectedMime(input.bytes, input.mimeType);
60
- const day = new Date(now).toISOString().slice(0, 10);
61
- const dir = join(root, "artifacts", day);
62
- mkdirSync(dir, { recursive: true });
63
- const path = join(dir, `${id}.${extensionFor(mimeType)}`);
64
- writeFileSync(path, input.bytes, { flag: "wx" });
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
+ }
65
127
 
66
128
  const doc: ArtifactDoc = {
67
129
  id,
@@ -77,7 +139,7 @@ export async function createArtifact(input: {
77
139
  height: input.height ?? null,
78
140
  status: "active",
79
141
  created_at: now,
80
- expires_at: now + ARTIFACT_RETENTION_MS,
142
+ expires_at: input.expiresAt !== undefined ? input.expiresAt : now + ARTIFACT_RETENTION_MS,
81
143
  expired_at: null,
82
144
  };
83
145
 
@@ -227,7 +289,9 @@ export async function expireArtifacts(now = Date.now()): Promise<{ expired: numb
227
289
  const rows = await artifacts.scan({});
228
290
  let expired = 0;
229
291
  for (const row of rows) {
230
- if (row.doc.status !== "active" || row.doc.expires_at > now) continue;
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;
231
295
  try {
232
296
  if (existsSync(row.doc.path)) unlinkSync(row.doc.path);
233
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
 
@@ -1,3 +1,5 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { basename } from "node:path";
1
3
  import { readArtifactBytes } from "../artifacts/store";
2
4
 
3
5
  /**
@@ -17,6 +19,26 @@ export async function readOutboundImageBytes(
17
19
  return null;
18
20
  }
19
21
 
22
+ /**
23
+ * Resuelve un OutboundMessage.document a bytes + nombre para los canales que
24
+ * suben el archivo directamente. Prefiere el artifact, luego la ruta en disco y
25
+ * al final el base64 en línea.
26
+ */
27
+ export async function readOutboundDocument(
28
+ doc: NonNullable<OutboundMessage["document"]>,
29
+ ): Promise<{ bytes: Buffer; filename: string; mimeType: string } | null> {
30
+ const filename = doc.filename || (doc.path ? basename(doc.path) : "documento");
31
+ if (doc.artifactId) {
32
+ const artifact = await readArtifactBytes(doc.artifactId);
33
+ if (artifact) return { bytes: artifact.bytes, filename, mimeType: doc.mimeType || artifact.mimeType };
34
+ }
35
+ if (doc.path && existsSync(doc.path)) {
36
+ return { bytes: readFileSync(doc.path), filename, mimeType: doc.mimeType || "application/octet-stream" };
37
+ }
38
+ if (doc.base64) return { bytes: Buffer.from(doc.base64, "base64"), filename, mimeType: doc.mimeType || "application/octet-stream" };
39
+ return null;
40
+ }
41
+
20
42
  export interface OutboundMessage {
21
43
  type: "message" | "stream" | "status" | "error" | "pong" | "command_result" | "log" | "typing" | "audio" | "process" | "progress" | "notification";
22
44
  sessionId: string;
@@ -46,11 +68,15 @@ export interface OutboundMessage {
46
68
  mimeType?: string;
47
69
  caption?: string;
48
70
  };
71
+ /** Archivo para el usuario (Word, Excel, PDF…). `artifactId` o `path` los leen los canales del servidor; `url` es para la web. */
49
72
  document?: {
73
+ artifactId?: string;
74
+ path?: string;
50
75
  url?: string;
51
76
  base64?: string;
52
77
  mimeType?: string;
53
78
  filename?: string;
79
+ caption?: string;
54
80
  };
55
81
  status?: {
56
82
  state: string;
@@ -7,7 +7,7 @@ import {
7
7
  type DMChannel,
8
8
  type NewsChannel,
9
9
  } from "discord.js";
10
- import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes } from "./base.ts";
10
+ import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes, readOutboundDocument } from "./base.ts";
11
11
  import { logger } from "../utils/logger.ts";
12
12
  import { updateDoc } from "../storage/hive.ts";
13
13
  import type { ChannelDoc } from "../storage/collections.ts";
@@ -101,7 +101,7 @@ export class DiscordChannel extends BaseChannel {
101
101
  );
102
102
 
103
103
  const documentAttachment = !audioAttachment && !imageAttachment
104
- ? message.attachments.find(a => a.contentType?.startsWith("application/") || a.url.endsWith(".pdf") || a.url.endsWith(".doc") || a.url.endsWith(".docx") || a.url.endsWith(".txt"))
104
+ ? message.attachments.find(a => a.contentType?.startsWith("application/") || a.contentType?.startsWith("text/") || /\.(pdf|docx?|xlsx?|xlsm|pptx?|csv|tsv|txt|md|json|rtf)(\?|$)/i.test(a.name ?? a.url))
105
105
  : undefined;
106
106
 
107
107
  const incomingMessage: IncomingMessage = {
@@ -224,6 +224,22 @@ export class DiscordChannel extends BaseChannel {
224
224
  }
225
225
  }
226
226
 
227
+ if (message.document) {
228
+ try {
229
+ const doc = await readOutboundDocument(message.document);
230
+ if (doc) {
231
+ await channel.send({
232
+ content: message.document.caption,
233
+ files: [{ attachment: doc.bytes, name: doc.filename }],
234
+ });
235
+ } else {
236
+ this.log.warn(`Document unavailable, skipping file send`, { sessionId });
237
+ }
238
+ } catch (error) {
239
+ this.log.error(`Failed to send Discord document: ${(error as Error).message}`);
240
+ }
241
+ }
242
+
227
243
  const content = message.content ?? "";
228
244
  const maxLength = 2000;
229
245