@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.
- package/README.md +4 -10
- package/dist/hive.js +218257 -148718
- package/dist/tool-worker.js +68422 -1622
- package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-R9UDWfR2.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-DICMU_7m.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-Blms3NBa.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-CAjLseE_.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-DhM07qYi.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-BP3GTCPn.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-zj0fuGwZ.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-Dj1k5PCk.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/cli/src/commands/onboard.ts +3 -2
- 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/minimal-loadout.ts +1 -0
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +12 -0
- package/packages/core/src/artifacts/store.ts +73 -9
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/channels/base.ts +26 -0
- package/packages/core/src/channels/discord.ts +18 -2
- package/packages/core/src/channels/slack.ts +37 -7
- package/packages/core/src/channels/telegram.ts +39 -11
- package/packages/core/src/channels/whatsapp.ts +16 -1
- package/packages/core/src/gateway/channel-notify.ts +42 -0
- 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/artifacts.ts +4 -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 +38 -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 +97 -48
- 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/gateway/webchat-turn.ts +15 -13
- 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 +190 -0
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
- package/packages/core/src/multimodal/vision-service.ts +25 -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 +107 -24
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tool-runtime/index.ts +2 -0
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +80 -2
- 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/index.ts +9 -0
- package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
- package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
- package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
- package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +16 -3
- package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
- package/packages/core/src/tools/office/office-leer-pptx.ts +54 -88
- package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +186 -0
- package/packages/core/src/tools/office/pptx-slides.ts +83 -0
- package/packages/core/src/tools/office/resolve-input.ts +49 -0
- 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-BVtE88U5.js +0 -1
- package/dist/ui/assets/AgentsPage-BOIJ55cj.js +0 -10
- package/dist/ui/assets/ChannelsPage-C5V2BmjL.js +0 -8
- package/dist/ui/assets/DashboardPage-B18gMzNj.js +0 -6
- package/dist/ui/assets/LoginPage-nrsYF9AY.js +0 -1
- package/dist/ui/assets/MeetingPage-xslJGfIz.js +0 -1
- package/dist/ui/assets/ModelSelector-BX4IvuYY.js +0 -1
- package/dist/ui/assets/Office3DPage-a6cuzt5X.js +0 -727
- package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
- package/dist/ui/assets/SettingsPage-BBeeq_QS.js +0 -9
- package/dist/ui/assets/VoicePage-BeSSYstD.js +0 -307
- package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-BG3nUPKq.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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { App, ExpressReceiver, type SlashCommand } from "@slack/bolt";
|
|
2
2
|
import type { ChannelConfig, IncomingMessage, OutboundMessage } from "./base.ts";
|
|
3
|
-
import { BaseChannel, readOutboundImageBytes } from "./base.ts";
|
|
3
|
+
import { BaseChannel, readOutboundImageBytes, readOutboundDocument } from "./base.ts";
|
|
4
4
|
import { logger } from "../utils/logger.ts";
|
|
5
5
|
import { updateDoc } from "../storage/hive.ts";
|
|
6
6
|
import type { ChannelDoc } from "../storage/collections.ts";
|
|
@@ -18,6 +18,13 @@ export interface SlackConnectionState {
|
|
|
18
18
|
error?: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
const DOCUMENT_EXTENSIONS = /\.(pdf|docx?|xlsx?|xlsm|pptx?|csv|tsv|txt|md|json|rtf)$/i;
|
|
22
|
+
|
|
23
|
+
/** Qué cuenta como documento: cualquier application/*, text/* o una extensión de oficina conocida. */
|
|
24
|
+
function isDocumentFile(f: { mimetype?: string; name?: string }): boolean {
|
|
25
|
+
return !!(f.mimetype?.startsWith("application/") || f.mimetype?.startsWith("text/") || (f.name && DOCUMENT_EXTENSIONS.test(f.name)));
|
|
26
|
+
}
|
|
27
|
+
|
|
21
28
|
export class SlackChannel extends BaseChannel {
|
|
22
29
|
name = "slack";
|
|
23
30
|
accountId: string;
|
|
@@ -129,6 +136,13 @@ export class SlackChannel extends BaseChannel {
|
|
|
129
136
|
} catch { /* ignore DB errors */ }
|
|
130
137
|
}
|
|
131
138
|
|
|
139
|
+
/** Los archivos de Slack (url_private) solo se descargan con el token del bot: sin él devuelven una página de login. */
|
|
140
|
+
private async downloadPrivateFile(url: string): Promise<Buffer> {
|
|
141
|
+
const res = await fetch(url, { headers: { Authorization: `Bearer ${this.config.botToken}` }, signal: AbortSignal.timeout(60_000) });
|
|
142
|
+
if (!res.ok) throw new Error(`Slack no entregó el archivo (HTTP ${res.status})`);
|
|
143
|
+
return Buffer.from(await res.arrayBuffer());
|
|
144
|
+
}
|
|
145
|
+
|
|
132
146
|
private async handleMention(event: { user?: string; text?: string; channel?: string; ts?: string; files?: Array<{ url_private?: string; mimetype?: string; name?: string }> }): Promise<void> {
|
|
133
147
|
if (!event.user || !event.channel) return;
|
|
134
148
|
|
|
@@ -149,7 +163,7 @@ f.name?.endsWith(".png") || f.name?.endsWith(".gif") || f.name?.endsWith(".webp"
|
|
|
149
163
|
);
|
|
150
164
|
|
|
151
165
|
const docFile = !audioFile && !imageFile
|
|
152
|
-
? event.files?.find(f =>
|
|
166
|
+
? event.files?.find(f => isDocumentFile(f))
|
|
153
167
|
: undefined;
|
|
154
168
|
|
|
155
169
|
const incoming: IncomingMessage = {
|
|
@@ -160,8 +174,8 @@ peerId: event.channel,
|
|
|
160
174
|
peerKind: "group",
|
|
161
175
|
content,
|
|
162
176
|
audio: audioFile?.url_private ? { url: audioFile.url_private, mimeType: audioFile.mimetype || "audio/webm" } : undefined,
|
|
163
|
-
image: imageFile?.url_private ? {
|
|
164
|
-
document: docFile?.url_private ? {
|
|
177
|
+
image: imageFile?.url_private ? { buffer: await this.downloadPrivateFile(imageFile.url_private), mimeType: imageFile.mimetype || "image/png" } : undefined,
|
|
178
|
+
document: docFile?.url_private ? { buffer: await this.downloadPrivateFile(docFile.url_private), mimeType: docFile.mimetype || "application/octet-stream", fileName: docFile.name } : undefined,
|
|
165
179
|
metadata: {
|
|
166
180
|
userId: event.user,
|
|
167
181
|
timestamp: event.ts,
|
|
@@ -191,7 +205,7 @@ f.name?.endsWith(".png") || f.name?.endsWith(".gif") || f.name?.endsWith(".webp"
|
|
|
191
205
|
);
|
|
192
206
|
|
|
193
207
|
const docFile = !audioFile && !imageFile
|
|
194
|
-
? event.files?.find(f =>
|
|
208
|
+
? event.files?.find(f => isDocumentFile(f))
|
|
195
209
|
: undefined;
|
|
196
210
|
|
|
197
211
|
const incoming: IncomingMessage = {
|
|
@@ -202,8 +216,8 @@ peerId: event.user,
|
|
|
202
216
|
peerKind: "direct",
|
|
203
217
|
content: event.text || "",
|
|
204
218
|
audio: audioFile?.url_private ? { url: audioFile.url_private, mimeType: audioFile.mimetype || "audio/webm" } : undefined,
|
|
205
|
-
image: imageFile?.url_private ? {
|
|
206
|
-
document: docFile?.url_private ? {
|
|
219
|
+
image: imageFile?.url_private ? { buffer: await this.downloadPrivateFile(imageFile.url_private), mimeType: imageFile.mimetype || "image/png" } : undefined,
|
|
220
|
+
document: docFile?.url_private ? { buffer: await this.downloadPrivateFile(docFile.url_private), mimeType: docFile.mimetype || "application/octet-stream", fileName: docFile.name } : undefined,
|
|
207
221
|
metadata: {
|
|
208
222
|
channel: event.channel,
|
|
209
223
|
timestamp: event.ts,
|
|
@@ -280,6 +294,22 @@ await this.handleMessage(incoming);
|
|
|
280
294
|
}
|
|
281
295
|
}
|
|
282
296
|
|
|
297
|
+
if (message.document) {
|
|
298
|
+
try {
|
|
299
|
+
const doc = await readOutboundDocument(message.document);
|
|
300
|
+
if (doc) {
|
|
301
|
+
await this.app.client.files.uploadV2({
|
|
302
|
+
channel_id: peerId, file: doc.bytes, filename: doc.filename,
|
|
303
|
+
title: message.document.caption ?? doc.filename,
|
|
304
|
+
});
|
|
305
|
+
} else {
|
|
306
|
+
this.log.warn(`Document unavailable, skipping file send`, { sessionId });
|
|
307
|
+
}
|
|
308
|
+
} catch (error) {
|
|
309
|
+
this.log.error(`Failed to send Slack document: ${(error as Error).message}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
283
313
|
const text = message.content ?? message.chunk ?? "";
|
|
284
314
|
if (!text) return;
|
|
285
315
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Bot, GrammyError, InputFile, type Context } from "grammy";
|
|
2
|
-
import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes } from "./base.ts";
|
|
2
|
+
import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage, readOutboundImageBytes, readOutboundDocument } from "./base.ts";
|
|
3
3
|
import { logger } from "../utils/logger.ts";
|
|
4
4
|
import { col, updateDoc } from "../storage/hive.ts";
|
|
5
5
|
import type { ChannelDoc, UserIdentityDoc } from "../storage/collections.ts";
|
|
@@ -10,6 +10,9 @@ export interface TelegramConfig extends ChannelConfig {
|
|
|
10
10
|
groups?: boolean;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/** Límite de getFile para bots: https://core.telegram.org/bots/api#getfile */
|
|
14
|
+
const TELEGRAM_BOT_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
|
|
15
|
+
|
|
13
16
|
export class TelegramChannel extends BaseChannel {
|
|
14
17
|
name = "telegram";
|
|
15
18
|
accountId: string;
|
|
@@ -230,6 +233,8 @@ export class TelegramChannel extends BaseChannel {
|
|
|
230
233
|
}
|
|
231
234
|
} catch (err) {
|
|
232
235
|
this.log.warn(`Failed to download photo: ${(err as Error).message}`);
|
|
236
|
+
await ctx.reply(`⚠️ No pude descargar la imagen: ${(err as Error).message}. Inténtalo de nuevo.`);
|
|
237
|
+
return;
|
|
233
238
|
}
|
|
234
239
|
content = caption || "";
|
|
235
240
|
}
|
|
@@ -288,19 +293,27 @@ export class TelegramChannel extends BaseChannel {
|
|
|
288
293
|
const docName = (message.document as any).file_name ?? "documento";
|
|
289
294
|
const caption = message.caption ?? "";
|
|
290
295
|
contentType = "document";
|
|
296
|
+
// La Bot API de Telegram solo deja descargar archivos de hasta 20 MB (getFile).
|
|
297
|
+
if ((message.document.file_size ?? 0) > TELEGRAM_BOT_DOWNLOAD_LIMIT) {
|
|
298
|
+
await ctx.reply(
|
|
299
|
+
`⚠️ «${docName}» pesa ${((message.document.file_size ?? 0) / 1048576).toFixed(1)} MB y Telegram solo permite que un bot descargue archivos de hasta 20 MB. ` +
|
|
300
|
+
`Envíalo comprimido o más liviano, o súbelo por el chat web.`,
|
|
301
|
+
);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
291
304
|
try {
|
|
292
|
-
if (this.bot)
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
}
|
|
301
|
-
}
|
|
305
|
+
if (!this.bot) throw new Error("el bot no está conectado");
|
|
306
|
+
const file = await this.bot.api.getFile(message.document.file_id);
|
|
307
|
+
if (!file.file_path) throw new Error("Telegram no devolvió la ruta del archivo");
|
|
308
|
+
document_ = {
|
|
309
|
+
url: `https://api.telegram.org/file/bot${this.config.botToken}/${file.file_path}`,
|
|
310
|
+
mimeType: message.document.mime_type || "application/octet-stream",
|
|
311
|
+
fileName: docName,
|
|
312
|
+
};
|
|
302
313
|
} catch (err) {
|
|
303
314
|
this.log.warn(`Failed to download document: ${(err as Error).message}`);
|
|
315
|
+
await ctx.reply(`⚠️ No pude descargar «${docName}»: ${(err as Error).message}. Inténtalo de nuevo.`);
|
|
316
|
+
return;
|
|
304
317
|
}
|
|
305
318
|
content = caption || "";
|
|
306
319
|
}
|
|
@@ -437,6 +450,21 @@ export class TelegramChannel extends BaseChannel {
|
|
|
437
450
|
}
|
|
438
451
|
}
|
|
439
452
|
|
|
453
|
+
if (message.document) {
|
|
454
|
+
try {
|
|
455
|
+
const doc = await readOutboundDocument(message.document);
|
|
456
|
+
if (doc) {
|
|
457
|
+
await this.bot.api.sendDocument(chatId, new InputFile(doc.bytes, doc.filename), {
|
|
458
|
+
caption: message.document.caption,
|
|
459
|
+
});
|
|
460
|
+
} else {
|
|
461
|
+
this.log.warn(`Document unavailable, skipping file send`, { sessionId });
|
|
462
|
+
}
|
|
463
|
+
} catch (error) {
|
|
464
|
+
this.log.error(`Telegram sendDocument failed: ${(error as Error).message}`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
440
468
|
const content = message.content ?? "";
|
|
441
469
|
|
|
442
470
|
if (!content || content.trim().length === 0) {
|
|
@@ -8,7 +8,7 @@ import makeWASocket, {
|
|
|
8
8
|
type WAMessage,
|
|
9
9
|
} from "@whiskeysockets/baileys";
|
|
10
10
|
import type { ChannelConfig, IncomingMessage, OutboundMessage } from "./base.ts";
|
|
11
|
-
import { BaseChannel, readOutboundImageBytes } from "./base.ts";
|
|
11
|
+
import { BaseChannel, readOutboundImageBytes, readOutboundDocument } from "./base.ts";
|
|
12
12
|
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
|
13
13
|
import * as path from "node:path";
|
|
14
14
|
import { homedir } from "node:os";
|
|
@@ -503,6 +503,21 @@ export class WhatsAppChannel extends BaseChannel {
|
|
|
503
503
|
}
|
|
504
504
|
}
|
|
505
505
|
|
|
506
|
+
if (message.document) {
|
|
507
|
+
try {
|
|
508
|
+
const doc = await readOutboundDocument(message.document);
|
|
509
|
+
if (doc) {
|
|
510
|
+
await this.socket.sendMessage(jid, {
|
|
511
|
+
document: doc.bytes, fileName: doc.filename, mimetype: doc.mimeType, caption: message.document.caption,
|
|
512
|
+
});
|
|
513
|
+
} else {
|
|
514
|
+
this.log.warn(`Document unavailable, skipping file send`, { sessionId });
|
|
515
|
+
}
|
|
516
|
+
} catch (error) {
|
|
517
|
+
this.log.error(`Failed to send WhatsApp document: ${(error as Error).message}`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
506
521
|
const text = message.content ?? message.chunk ?? "";
|
|
507
522
|
if (!text) return;
|
|
508
523
|
|
|
@@ -23,7 +23,27 @@ type SendFn = (
|
|
|
23
23
|
metadata?: { notificationId?: string; accountId?: string },
|
|
24
24
|
) => Promise<void>
|
|
25
25
|
|
|
26
|
+
export interface OutboundFile {
|
|
27
|
+
artifactId: string
|
|
28
|
+
filename: string
|
|
29
|
+
mimeType: string
|
|
30
|
+
caption?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type SendFileFn = (
|
|
34
|
+
channel: string,
|
|
35
|
+
sessionId: string,
|
|
36
|
+
file: OutboundFile,
|
|
37
|
+
metadata?: { accountId?: string },
|
|
38
|
+
) => Promise<void>
|
|
39
|
+
|
|
26
40
|
let _sendFn: SendFn | null = null
|
|
41
|
+
let _sendFileFn: SendFileFn | null = null
|
|
42
|
+
|
|
43
|
+
/** Llamar en server.ts junto a setChannelSendFn: permite que la tool send_file entregue archivos. */
|
|
44
|
+
export function setChannelFileFn(fn: SendFileFn): void {
|
|
45
|
+
_sendFileFn = fn
|
|
46
|
+
}
|
|
27
47
|
|
|
28
48
|
/** Llamar en server.ts una vez que channelManager esté listo */
|
|
29
49
|
export function setChannelSendFn(fn: SendFn): void {
|
|
@@ -113,3 +133,25 @@ export async function sendToUserChannel(
|
|
|
113
133
|
return { ok: false, error: (err as Error).message }
|
|
114
134
|
}
|
|
115
135
|
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Entrega un archivo (Word, Excel, PDF…) al chat desde el que escribió el usuario.
|
|
139
|
+
* Misma resolución de destino que sendToUserChannel; sin socket vivo no hay cola
|
|
140
|
+
* (a diferencia del texto), así que un fallo se devuelve para que el agente avise.
|
|
141
|
+
*/
|
|
142
|
+
export async function sendFileToUserChannel(
|
|
143
|
+
channel: string,
|
|
144
|
+
userId: string,
|
|
145
|
+
file: OutboundFile,
|
|
146
|
+
opts?: { threadId?: string },
|
|
147
|
+
): Promise<{ ok: boolean; error?: string }> {
|
|
148
|
+
if (!_sendFileFn) return { ok: false, error: "El envío de archivos no está inicializado" }
|
|
149
|
+
const { sessionId, accountId } = await resolveSession(userId, channel, opts?.threadId)
|
|
150
|
+
try {
|
|
151
|
+
await _sendFileFn(channel, sessionId, file, { accountId })
|
|
152
|
+
return { ok: true }
|
|
153
|
+
} catch (err) {
|
|
154
|
+
log.warn(`[channel-notify] Falló el envío de archivo: ${(err as Error).message}`)
|
|
155
|
+
return { ok: false, error: (err as Error).message }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { Config } from "../config/loader";
|
|
2
|
+
import { initGoogleFromEnv } from "./google-host.ts";
|
|
3
|
+
import { syncGoogleCapabilities } from "../storage/google-capabilities.ts";
|
|
2
4
|
import { logger } from "../utils/logger";
|
|
3
5
|
import { ensureHiveDb } from "../storage/bootstrap";
|
|
4
6
|
import { col, fromIndexable } from "../storage/hive";
|
|
@@ -205,6 +207,9 @@ export async function initializeGateway(
|
|
|
205
207
|
config: Config,
|
|
206
208
|
pidFile: string
|
|
207
209
|
): Promise<GatewayInitializationResult> {
|
|
210
|
+
// Google es opt-in por entorno: debe estar configurado antes de armar el loadout de tools.
|
|
211
|
+
initGoogleFromEnv();
|
|
212
|
+
|
|
208
213
|
// Setup mode: 0 usuarios (ensureHiveDb() ya fue llamado antes en server.ts)
|
|
209
214
|
let setupMode = false;
|
|
210
215
|
try {
|
|
@@ -237,6 +242,9 @@ export async function initializeGateway(
|
|
|
237
242
|
// 3. Cargar configuración del agente desde DB
|
|
238
243
|
const { provider, model } = await loadAgentConfigFromDB(config);
|
|
239
244
|
|
|
245
|
+
// 3b. Los agentes y tools de Google solo están activos mientras haya cuenta conectada.
|
|
246
|
+
await syncGoogleCapabilities("boot").catch((err) => log.warn(`[initialize] google: ${(err as Error).message}`));
|
|
247
|
+
|
|
240
248
|
// 4. Sync HiveDB capability index (tools + skills + playbook + mcp_tools)
|
|
241
249
|
log.info("[initialize] Syncing HiveDB capability index...")
|
|
242
250
|
try {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { GOOGLE_AGENT_BY_SERVICE, connectedGoogleServices, isGoogleAgentId } from "../../storage/google-capabilities.ts"
|
|
2
|
+
import type { GoogleService } from "../../google/scopes.ts"
|
|
1
3
|
import { col, updateDoc, toIndexable, fromIndexable } from "../../storage/hive"
|
|
2
4
|
import type { AgentDoc, AgentProposalDoc, McpServerDoc, SkillDoc, TaskDoc, UserDoc } from "../../storage/collections"
|
|
3
5
|
import { emitCanvas } from "../../canvas/emitter"
|
|
@@ -253,6 +255,18 @@ export async function handleUpdateAgent(req: Request, addCorsHeaders: (r: Respon
|
|
|
253
255
|
}
|
|
254
256
|
}
|
|
255
257
|
|
|
258
|
+
// Los especialistas de Google solo pueden activarse con la cuenta conectada.
|
|
259
|
+
if (patch.enabled === true && isGoogleAgentId(agentId)) {
|
|
260
|
+
const service = (Object.entries(GOOGLE_AGENT_BY_SERVICE).find(([, id]) => id === agentId)?.[0]) as GoogleService
|
|
261
|
+
if (!(await connectedGoogleServices()).includes(service)) {
|
|
262
|
+
return addCorsHeaders(Response.json({
|
|
263
|
+
ok: false,
|
|
264
|
+
error: "Conecta tu cuenta de Google en Ajustes → Perfil para activar este agente.",
|
|
265
|
+
needs_google: true,
|
|
266
|
+
}, { status: 409 }), req)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
256
270
|
const agentHeaders = body.headers !== undefined ? body.headers : body.config?.headers
|
|
257
271
|
if (agentHeaders !== undefined) {
|
|
258
272
|
await storeAgentHeaders(agentId, agentHeaders)
|
|
@@ -36,6 +36,7 @@ export async function handleDownloadArtifact(
|
|
|
36
36
|
return addCorsHeaders(Response.json({ ok: false, error: "Artifact not found" }, { status: 404 }), req);
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
const downloadName = new URL(req.url).searchParams.get("name")?.replace(/[\\/\0\r\n]/g, "_").slice(0, 200);
|
|
39
40
|
const file = Bun.file(entry.doc.path);
|
|
40
41
|
if (!(await file.exists())) {
|
|
41
42
|
return addCorsHeaders(Response.json({ ok: false, error: "Artifact binary is missing" }, { status: 404 }), req);
|
|
@@ -59,6 +60,9 @@ export async function handleDownloadArtifact(
|
|
|
59
60
|
"Cache-Control": "private, max-age=3600",
|
|
60
61
|
ETag: etag,
|
|
61
62
|
"Accept-Ranges": "bytes",
|
|
63
|
+
...(downloadName
|
|
64
|
+
? { "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(downloadName)}` }
|
|
65
|
+
: {}),
|
|
62
66
|
},
|
|
63
67
|
}),
|
|
64
68
|
req,
|
|
@@ -5,6 +5,7 @@ import { getHiveDir } from "../../config/loader";
|
|
|
5
5
|
import * as path from "node:path";
|
|
6
6
|
import jwt from "jsonwebtoken";
|
|
7
7
|
import { normalizeUserEmail } from "../../storage/user-email";
|
|
8
|
+
import { isGoogleConfigured } from "../../google/config";
|
|
8
9
|
|
|
9
10
|
type CorsHelper = (res: Response, req: Request) => Response;
|
|
10
11
|
|
|
@@ -49,6 +50,20 @@ async function generateTokens(userId: string): Promise<AuthTokens> {
|
|
|
49
50
|
};
|
|
50
51
|
}
|
|
51
52
|
|
|
53
|
+
/**
|
|
54
|
+
* `true` cuando la instancia exige iniciar sesión: hay email y al menos un
|
|
55
|
+
* método (contraseña o cuenta de Google vinculada). Es la única definición de
|
|
56
|
+
* «acceso protegido»: server.ts y /api/auth/status deben usarla.
|
|
57
|
+
*/
|
|
58
|
+
export function isAuthEnabled(user: Pick<UserDoc, "email" | "password_hash" | "google_sub"> | undefined | null): boolean {
|
|
59
|
+
return !!(user?.email && (user.password_hash || user.google_sub));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Token de acceso vigente (el mismo que devuelve /api/auth/login). */
|
|
63
|
+
export function currentAuthToken(): string {
|
|
64
|
+
return process.env.HIVE_AUTH_TOKEN ?? getAuthTokenFromFile();
|
|
65
|
+
}
|
|
66
|
+
|
|
52
67
|
function getAuthTokenFromFile(): string {
|
|
53
68
|
// The auth token lives in ~/.hive/.auth_token — same value as HIVE_AUTH_TOKEN env var
|
|
54
69
|
try {
|
|
@@ -68,8 +83,15 @@ export async function handleAuthStatus(
|
|
|
68
83
|
): Promise<Response> {
|
|
69
84
|
const user = (await getSingleUser())?.doc;
|
|
70
85
|
|
|
71
|
-
const hasCredentials =
|
|
72
|
-
|
|
86
|
+
const hasCredentials = isAuthEnabled(user);
|
|
87
|
+
const googleConfigured = isGoogleConfigured();
|
|
88
|
+
return cors(Response.json({
|
|
89
|
+
hasCredentials,
|
|
90
|
+
email: hasCredentials ? user?.email ?? null : null,
|
|
91
|
+
hasPassword: !!user?.password_hash,
|
|
92
|
+
googleConfigured,
|
|
93
|
+
googleLogin: googleConfigured && !!user?.google_sub,
|
|
94
|
+
}), req);
|
|
73
95
|
}
|
|
74
96
|
|
|
75
97
|
/** GET /api/auth/recovery-key — requires auth
|
|
@@ -233,7 +255,7 @@ export async function handleDisableAuth(
|
|
|
233
255
|
const usersCol = await col<UserDoc>("users");
|
|
234
256
|
const entry = await getSingleUser();
|
|
235
257
|
if (entry) {
|
|
236
|
-
await usersCol.put(entry.id, { ...entry.doc, email: null, password_hash: null }, { expectedVersion: entry.version });
|
|
258
|
+
await usersCol.put(entry.id, { ...entry.doc, email: null, password_hash: null, google_sub: null, google_email: null }, { expectedVersion: entry.version });
|
|
237
259
|
}
|
|
238
260
|
return cors(Response.json({ success: true }), req);
|
|
239
261
|
}
|
|
@@ -200,6 +200,16 @@ export async function handleChat(
|
|
|
200
200
|
|
|
201
201
|
// ── Original Chat API Functions ─────────────────────────────────────────────
|
|
202
202
|
|
|
203
|
+
/** Última imagen guardada junto a una respuesta del asistente, como la espera la web. */
|
|
204
|
+
function storedImage(imagesJson: string | null | undefined): { image: string; imageMimeType: string } | null {
|
|
205
|
+
if (!imagesJson) return null
|
|
206
|
+
try {
|
|
207
|
+
const list = JSON.parse(imagesJson) as Array<{ artifactId: string; mimeType: string }>
|
|
208
|
+
const last = list[list.length - 1]
|
|
209
|
+
return last ? { image: `/api/artifacts/${last.artifactId}/download`, imageMimeType: last.mimeType } : null
|
|
210
|
+
} catch { return null }
|
|
211
|
+
}
|
|
212
|
+
|
|
203
213
|
export async function handleGetChatHistory(req: Request, addCorsHeaders: (r: Response, req: Request) => Response): Promise<Response> {
|
|
204
214
|
const url = new URL(req.url)
|
|
205
215
|
const requested = url.searchParams.get("threadId") || url.searchParams.get("sessionId")
|
|
@@ -210,7 +220,9 @@ export async function handleGetChatHistory(req: Request, addCorsHeaders: (r: Res
|
|
|
210
220
|
const limit = parseInt(url.searchParams.get("limit") || String(DEFAULT_CHAT_HISTORY_LIMIT))
|
|
211
221
|
|
|
212
222
|
const conversationsCol = await col<ConversationDoc>("conversations")
|
|
213
|
-
const
|
|
223
|
+
const all = await conversationsCol.scan({ prefix: `${threadId}:`, reverse: true })
|
|
224
|
+
|
|
225
|
+
const entries = all
|
|
214
226
|
// Legacy internal turns still carry role:"system" and are excluded by the
|
|
215
227
|
// role allowlist; current ones persist as role:"user" + an internal
|
|
216
228
|
// `source` and are excluded by isInternalSource instead.
|
|
@@ -230,6 +242,7 @@ export async function handleGetChatHistory(req: Request, addCorsHeaders: (r: Res
|
|
|
230
242
|
token_count: e.doc.token_count,
|
|
231
243
|
created_at: e.doc.created_at,
|
|
232
244
|
updated_at: e.doc.updated_at,
|
|
245
|
+
...storedImage(e.doc.images_json),
|
|
233
246
|
})).reverse()
|
|
234
247
|
|
|
235
248
|
return addCorsHeaders(Response.json({ messages }), req)
|