@johpaz/hive-agents 1.1.6 → 1.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -10
- package/dist/hive.js +5258 -2985
- package/dist/tool-worker.js +197 -75
- package/dist/ui/assets/{A2UIPage-CxE3jH4_.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-SGj5AqAX.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-xvAmX6kw.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-NLw2wHjH.js → ApiClientPage-uuBnrh0y.js} +1 -1
- package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
- package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
- package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
- package/dist/ui/assets/{LogsPage-G9d2G1nL.js → LogsPage-mcqOYvGw.js} +1 -1
- package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
- package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
- package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
- package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
- package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
- package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
- package/dist/ui/assets/{RecoverPage-Dr6qKgV5.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-BoVKIf4r.js → SetupPage-OaouFLGD.js} +1 -1
- package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
- package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
- package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
- package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
- package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
- package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
- package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
- package/dist/ui/assets/{conversationsStore-ns_ZfKgg.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-C3n2xYF2.js → dialog-DO1fQCF7.js} +1 -1
- package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
- package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
- package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
- package/dist/ui/assets/index-BKNFH2al.css +2 -0
- package/dist/ui/assets/index-U0e4e5mL.js +156 -0
- package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
- package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
- package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
- package/dist/ui/assets/select-BjBXxyxL.js +1 -0
- package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
- package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
- package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
- package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
- package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
- package/dist/ui/assets/{useAudioDevices-CsPrtpWY.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-nn4gON9g.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-9tvEC3hX.js → useProviders-CeSzDnx-.js} +1 -1
- package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
- package/dist/ui/index.html +5 -5
- package/package.json +1 -3
- package/packages/core/src/agent/agent-catalog.ts +98 -1
- package/packages/core/src/agent/agent-loop.ts +5 -44
- package/packages/core/src/agent/context-compiler.ts +6 -94
- package/packages/core/src/agent/conversation-store.ts +23 -1
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +8 -0
- package/packages/core/src/artifacts/store.ts +66 -8
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/gateway/google-host.ts +228 -0
- package/packages/core/src/gateway/initializer.ts +8 -0
- package/packages/core/src/gateway/routes/agents.ts +14 -0
- package/packages/core/src/gateway/routes/auth.ts +25 -3
- package/packages/core/src/gateway/routes/chat.ts +14 -1
- package/packages/core/src/gateway/routes/google.ts +252 -0
- package/packages/core/src/gateway/routes/meeting.ts +11 -3
- package/packages/core/src/gateway/routes/models.ts +27 -11
- package/packages/core/src/gateway/routes/multimodal.ts +19 -0
- package/packages/core/src/gateway/routes/providers.ts +19 -18
- package/packages/core/src/gateway/routes/system.ts +1 -3
- package/packages/core/src/gateway/routes/tts-local.ts +20 -374
- package/packages/core/src/gateway/routes/voice.ts +29 -35
- package/packages/core/src/gateway/server.ts +58 -32
- package/packages/core/src/gateway/tts/README.md +7 -86
- package/packages/core/src/gateway/tts/build.py +105 -0
- package/packages/core/src/gateway/tts/kitten.ts +282 -0
- package/packages/core/src/gateway/tts/python.d.ts +4 -0
- package/packages/core/src/gateway/tts/src/detect.ts +33 -39
- package/packages/core/src/gateway/tts/worker.py +80 -0
- package/packages/core/src/google/client.ts +123 -0
- package/packages/core/src/google/config.ts +60 -0
- package/packages/core/src/google/google.test.ts +287 -0
- package/packages/core/src/google/index.ts +5 -0
- package/packages/core/src/google/oauth.ts +144 -0
- package/packages/core/src/google/scopes.ts +41 -0
- package/packages/core/src/google/token-store.ts +33 -0
- package/packages/core/src/multimodal/attachment-ingest.ts +19 -4
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/storage/collections.ts +8 -8
- package/packages/core/src/storage/google-capabilities.ts +91 -0
- package/packages/core/src/storage/model-activation.ts +18 -0
- package/packages/core/src/storage/model-sync.ts +66 -14
- package/packages/core/src/storage/onboarding.ts +10 -2
- package/packages/core/src/storage/seed.ts +81 -18
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +1 -1
- package/packages/core/src/tools/google/calendar.ts +204 -0
- package/packages/core/src/tools/google/drive.ts +160 -0
- package/packages/core/src/tools/google/gmail.ts +579 -0
- package/packages/core/src/tools/google/index.ts +18 -0
- package/packages/core/src/tools/google/shared.ts +80 -0
- package/packages/core/src/tools/image/image-generate.ts +90 -0
- package/packages/core/src/tools/image/index.ts +13 -0
- package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
- package/packages/core/src/tools/index.ts +27 -0
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +10 -1
- package/packages/core/src/tools/office/office-leer-pdf.ts +1 -1
- package/packages/core/src/tools/office/office-leer-pptx.ts +4 -1
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +2 -2
- package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
- package/packages/core/src/voice/index.ts +123 -155
- package/packages/core/src/voice/local-model.ts +8 -0
- package/packages/core/src/voice/stt-models.ts +39 -0
- package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
- package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
- package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
- package/packages/skills/src/bundled-data.generated.ts +45 -0
- package/dist/ui/assets/AgentDetailPage-CyYbqzHr.js +0 -1
- package/dist/ui/assets/AgentsPage-CEWNs4Lt.js +0 -10
- package/dist/ui/assets/ChannelsPage-CmeXP-hI.js +0 -8
- package/dist/ui/assets/DashboardPage-C3z4kZXD.js +0 -6
- package/dist/ui/assets/LoginPage-DDisP8hm.js +0 -1
- package/dist/ui/assets/MeetingPage-CKyjxtFr.js +0 -1
- package/dist/ui/assets/ModelSelector-VVwpDrYF.js +0 -1
- package/dist/ui/assets/Office3DPage-CYxB6z2p.js +0 -727
- package/dist/ui/assets/ProvidersPage-CM9-E-Pf.js +0 -1
- package/dist/ui/assets/SettingsPage-BvD-vs5g.js +0 -9
- package/dist/ui/assets/VoicePage-CmudxYny.js +0 -307
- package/dist/ui/assets/WebChatPage-CnoXpEOl.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-C0W6p0lk.js +0 -156
- package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
- package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
- package/dist/ui/assets/select-v_3QBYrD.js +0 -1
- package/dist/ui/assets/terminal-BEcTK780.js +0 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
- package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
- package/packages/core/src/agent/jev-decisions.ts +0 -242
- package/packages/core/src/agent/jev-planner.ts +0 -293
- package/packages/core/src/gateway/tts/package.json +0 -25
- package/packages/core/src/gateway/tts/src/client.ts +0 -59
- package/packages/core/src/gateway/tts/src/index.ts +0 -15
- package/packages/core/src/gateway/tts/src/install.ts +0 -137
- package/packages/core/src/gateway/tts/src/models.ts +0 -50
- package/packages/core/src/gateway/tts/src/server.ts +0 -253
- /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
- /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
- /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
- /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
- /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
- /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
- /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
- /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
- /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
- /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
- /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
- /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
- /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
- /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
- /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
- /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
- /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
- /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
- /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
- /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
- /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
- /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
- /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
- /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
- /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
- /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gmail: buscar, leer y enviar.
|
|
3
|
+
*
|
|
4
|
+
* @category google
|
|
5
|
+
* @spanish correo, gmail, email, bandeja de entrada, enviar correo, leer correo
|
|
6
|
+
*/
|
|
7
|
+
import type { ToolParameter } from "../types.ts";
|
|
8
|
+
import { googleJson } from "../../google/client.ts";
|
|
9
|
+
import { getWorkspace } from "../filesystem/workspace-guard.ts";
|
|
10
|
+
import { createArtifact, readArtifactBytes } from "../../artifacts/store.ts";
|
|
11
|
+
import { CONFIRMED_PARAM, googleTool, headerSafe, needsConfirmation, num, str } from "./shared.ts";
|
|
12
|
+
|
|
13
|
+
const API = "https://gmail.googleapis.com/gmail/v1/users/me";
|
|
14
|
+
|
|
15
|
+
const b64urlDecode = (s: string) => Buffer.from(s, "base64url").toString("utf-8");
|
|
16
|
+
|
|
17
|
+
function header(msg: any, name: string): string {
|
|
18
|
+
return msg.payload?.headers?.find((h: any) => h.name?.toLowerCase() === name.toLowerCase())?.value ?? "";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Primer text/plain; si no hay, text/html sin etiquetas. */
|
|
22
|
+
function extractBody(payload: any): string {
|
|
23
|
+
const walk = (p: any, mime: string): string | null => {
|
|
24
|
+
if (!p) return null;
|
|
25
|
+
if (p.mimeType === mime && p.body?.data) return b64urlDecode(p.body.data);
|
|
26
|
+
for (const part of p.parts ?? []) {
|
|
27
|
+
const found = walk(part, mime);
|
|
28
|
+
if (found) return found;
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
};
|
|
32
|
+
const plain = walk(payload, "text/plain");
|
|
33
|
+
if (plain) return plain;
|
|
34
|
+
const html = walk(payload, "text/html");
|
|
35
|
+
return html ? html.replace(/<style[\s\S]*?<\/style>|<script[\s\S]*?<\/script>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim() : "";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function attachments(payload: any): Array<{ filename: string; mime_type: string; size: number; attachment_id: string }> {
|
|
39
|
+
const out: Array<{ filename: string; mime_type: string; size: number; attachment_id: string }> = [];
|
|
40
|
+
const walk = (p: any) => {
|
|
41
|
+
if (p?.filename && p.body?.attachmentId) out.push({ filename: p.filename, mime_type: p.mimeType, size: p.body?.size ?? 0, attachment_id: p.body.attachmentId });
|
|
42
|
+
for (const part of p?.parts ?? []) walk(part);
|
|
43
|
+
};
|
|
44
|
+
walk(payload);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const encodeWord = (s: string) => (/^[\x20-\x7e]*$/.test(s) ? s : `=?UTF-8?B?${Buffer.from(s, "utf-8").toString("base64")}?=`);
|
|
49
|
+
|
|
50
|
+
export const gmailSearchTool = googleTool({
|
|
51
|
+
name: "gmail_search",
|
|
52
|
+
description:
|
|
53
|
+
"Search the user's Gmail. Accepts Gmail query syntax (from:, to:, subject:, is:unread, after:2026/01/31, has:attachment, label:). " +
|
|
54
|
+
"Returns id, sender, subject, date and snippet. Spanish: buscar correos, correos sin leer, correos de, bandeja de entrada",
|
|
55
|
+
parameters: {
|
|
56
|
+
type: "object",
|
|
57
|
+
properties: {
|
|
58
|
+
query: { type: "string", description: "Gmail search query. Empty = most recent messages." },
|
|
59
|
+
max_results: { type: "number", description: "1-20. Default 10.", minimum: 1, maximum: 20 },
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
run: async (p, { userId }) => {
|
|
63
|
+
const max = num(p.max_results, 10, 1, 20);
|
|
64
|
+
const list = await googleJson<{ messages?: Array<{ id: string }> }>(userId, "gmail", `${API}/messages`, {
|
|
65
|
+
query: { q: str(p.query), maxResults: max },
|
|
66
|
+
});
|
|
67
|
+
const ids = (list.messages ?? []).map((m) => m.id);
|
|
68
|
+
const full = await Promise.all(ids.map((id) =>
|
|
69
|
+
googleJson<any>(
|
|
70
|
+
userId, "gmail",
|
|
71
|
+
`${API}/messages/${id}?format=metadata&metadataHeaders=From&metadataHeaders=Subject&metadataHeaders=Date`,
|
|
72
|
+
).catch(() => null)));
|
|
73
|
+
return {
|
|
74
|
+
ok: true,
|
|
75
|
+
count: full.filter(Boolean).length,
|
|
76
|
+
messages: full.filter(Boolean).map((m) => ({
|
|
77
|
+
id: m.id,
|
|
78
|
+
thread_id: m.threadId,
|
|
79
|
+
from: header(m, "From"),
|
|
80
|
+
subject: header(m, "Subject"),
|
|
81
|
+
date: header(m, "Date"),
|
|
82
|
+
snippet: m.snippet,
|
|
83
|
+
unread: (m.labelIds ?? []).includes("UNREAD"),
|
|
84
|
+
})),
|
|
85
|
+
};
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
export const gmailReadTool = googleTool({
|
|
90
|
+
name: "gmail_read",
|
|
91
|
+
description:
|
|
92
|
+
"Read one Gmail message in full (headers, text body, attachment names) by id from gmail_search. Spanish: leer correo, abrir correo, contenido del correo",
|
|
93
|
+
parameters: {
|
|
94
|
+
type: "object",
|
|
95
|
+
properties: { message_id: { type: "string", description: "Message id returned by gmail_search." } },
|
|
96
|
+
required: ["message_id"],
|
|
97
|
+
},
|
|
98
|
+
run: async (p, { userId }) => {
|
|
99
|
+
const id = str(p.message_id);
|
|
100
|
+
if (!id) return { ok: false, error: "message_id es obligatorio." };
|
|
101
|
+
const m = await googleJson<any>(userId, "gmail", `${API}/messages/${encodeURIComponent(id)}`, { query: { format: "full" } });
|
|
102
|
+
const body = extractBody(m.payload);
|
|
103
|
+
const MAX = 20_000;
|
|
104
|
+
return {
|
|
105
|
+
ok: true,
|
|
106
|
+
id: m.id,
|
|
107
|
+
thread_id: m.threadId,
|
|
108
|
+
from: header(m, "From"),
|
|
109
|
+
to: header(m, "To"),
|
|
110
|
+
cc: header(m, "Cc"),
|
|
111
|
+
subject: header(m, "Subject"),
|
|
112
|
+
date: header(m, "Date"),
|
|
113
|
+
message_id_header: header(m, "Message-ID"),
|
|
114
|
+
body: body.slice(0, MAX),
|
|
115
|
+
truncated: body.length > MAX,
|
|
116
|
+
attachments: attachments(m.payload),
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
// ─── Construcción de mensajes ───────────────────────────────────────────────
|
|
123
|
+
|
|
124
|
+
const MAX_ATTACH_TOTAL = 18 * 1024 * 1024; // el límite de Gmail es 25 MB y base64 infla ~33 %
|
|
125
|
+
|
|
126
|
+
const ATTACHMENTS_PARAM: ToolParameter = {
|
|
127
|
+
type: "array",
|
|
128
|
+
description: "Files to attach, taken from Hive artifacts.",
|
|
129
|
+
items: {
|
|
130
|
+
type: "object",
|
|
131
|
+
properties: {
|
|
132
|
+
artifact_id: { type: "string" },
|
|
133
|
+
filename: { type: "string", description: "Name shown to the recipient, with extension." },
|
|
134
|
+
},
|
|
135
|
+
required: ["artifact_id", "filename"],
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const wrap76 = (b64: string) => b64.replace(/(.{76})/g, "$1\r\n");
|
|
140
|
+
|
|
141
|
+
interface RawMessage {
|
|
142
|
+
to: string; cc?: string; bcc?: string; subject: string; body: string;
|
|
143
|
+
inReplyTo?: string; references?: string;
|
|
144
|
+
attachments?: Array<{ filename: string; mimeType: string; bytes: Uint8Array }>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function buildRaw(m: RawMessage): string {
|
|
148
|
+
const lines = [`To: ${headerSafe(m.to, "to")}`];
|
|
149
|
+
if (m.cc) lines.push(`Cc: ${headerSafe(m.cc, "cc")}`);
|
|
150
|
+
if (m.bcc) lines.push(`Bcc: ${headerSafe(m.bcc, "bcc")}`);
|
|
151
|
+
lines.push(`Subject: ${encodeWord(headerSafe(m.subject, "subject"))}`);
|
|
152
|
+
if (m.inReplyTo) lines.push(`In-Reply-To: ${headerSafe(m.inReplyTo, "Message-ID")}`);
|
|
153
|
+
if (m.references) lines.push(`References: ${headerSafe(m.references, "References")}`);
|
|
154
|
+
lines.push("MIME-Version: 1.0");
|
|
155
|
+
const bodyB64 = wrap76(Buffer.from(m.body, "utf-8").toString("base64"));
|
|
156
|
+
const files = m.attachments ?? [];
|
|
157
|
+
if (!files.length) {
|
|
158
|
+
lines.push("Content-Type: text/plain; charset=UTF-8", "Content-Transfer-Encoding: base64", "", bodyB64);
|
|
159
|
+
} else {
|
|
160
|
+
const b = `hive_${crypto.randomUUID()}`;
|
|
161
|
+
lines.push(`Content-Type: multipart/mixed; boundary="${b}"`, "",
|
|
162
|
+
`--${b}`, "Content-Type: text/plain; charset=UTF-8", "Content-Transfer-Encoding: base64", "", bodyB64);
|
|
163
|
+
for (const f of files) {
|
|
164
|
+
const name = encodeWord(headerSafe(f.filename, "filename")).replace(/"/g, "");
|
|
165
|
+
lines.push(`--${b}`, `Content-Type: ${f.mimeType}; name="${name}"`, `Content-Disposition: attachment; filename="${name}"`,
|
|
166
|
+
"Content-Transfer-Encoding: base64", "", wrap76(Buffer.from(f.bytes).toString("base64")));
|
|
167
|
+
}
|
|
168
|
+
lines.push(`--${b}--`);
|
|
169
|
+
}
|
|
170
|
+
return Buffer.from(lines.join("\r\n"), "utf-8").toString("base64url");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function loadAttachments(p: Record<string, unknown>) {
|
|
174
|
+
const list = Array.isArray(p.attachments) ? (p.attachments as Array<Record<string, unknown>>) : [];
|
|
175
|
+
const out: NonNullable<RawMessage["attachments"]> = [];
|
|
176
|
+
let total = 0;
|
|
177
|
+
for (const a of list.slice(0, 10)) {
|
|
178
|
+
const id = str(a.artifact_id), filename = str(a.filename);
|
|
179
|
+
if (!id || !filename) throw new Error("Cada adjunto necesita artifact_id y filename.");
|
|
180
|
+
const art = await readArtifactBytes(id);
|
|
181
|
+
if (!art) throw new Error(`No existe el artifact ${id} o ya expiró.`);
|
|
182
|
+
total += art.bytes.byteLength;
|
|
183
|
+
if (total > MAX_ATTACH_TOTAL) throw new Error("Los adjuntos superan los 18 MB permitidos por correo.");
|
|
184
|
+
out.push({ filename, mimeType: art.mimeType, bytes: art.bytes });
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const attachSummary = (p: Record<string, unknown>) =>
|
|
190
|
+
(Array.isArray(p.attachments) ? (p.attachments as Array<Record<string, unknown>>) : []).map((a) => a.filename);
|
|
191
|
+
|
|
192
|
+
/** Cabeceras necesarias para contestar un mensaje y mantener el hilo. */
|
|
193
|
+
async function replyContext(userId: string, messageId: string, replyAll: boolean) {
|
|
194
|
+
const orig = await googleJson<any>(userId, "gmail", `${API}/messages/${encodeURIComponent(messageId)}?format=metadata` +
|
|
195
|
+
["From", "To", "Cc", "Reply-To", "Subject", "Message-ID", "References"].map((h) => `&metadataHeaders=${h}`).join(""));
|
|
196
|
+
const mid = header(orig, "Message-ID");
|
|
197
|
+
let to = header(orig, "Reply-To") || header(orig, "From");
|
|
198
|
+
let cc = "";
|
|
199
|
+
if (replyAll) {
|
|
200
|
+
const me = (await googleJson<any>(userId, "gmail", `${API}/profile`)).emailAddress?.toLowerCase();
|
|
201
|
+
const others = [header(orig, "To"), header(orig, "Cc")].join(",").split(",").map((x) => x.trim()).filter(Boolean)
|
|
202
|
+
.filter((x) => !(me && x.toLowerCase().includes(me)) && !to.includes(x));
|
|
203
|
+
cc = others.join(", ");
|
|
204
|
+
}
|
|
205
|
+
const subject = header(orig, "Subject");
|
|
206
|
+
const refs = [header(orig, "References"), mid].filter(Boolean).join(" ");
|
|
207
|
+
return {
|
|
208
|
+
threadId: orig.threadId as string, to, cc: cc || undefined,
|
|
209
|
+
subject: /^re:/i.test(subject) ? subject : `Re: ${subject}`,
|
|
210
|
+
inReplyTo: mid || undefined, references: refs || undefined,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ─── Enviar y responder ─────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
export const gmailSendTool = googleTool({
|
|
217
|
+
name: "gmail_send",
|
|
218
|
+
description:
|
|
219
|
+
"Send a NEW email from the user's Gmail (to reply use gmail_reply). IRREVERSIBLE: first call returns a preview and needs_confirmation; repeat with confirmed=true only after the user approves. " +
|
|
220
|
+
"Spanish: enviar correo, mandar email, escribir un correo, enviar con adjunto",
|
|
221
|
+
parameters: {
|
|
222
|
+
type: "object",
|
|
223
|
+
properties: {
|
|
224
|
+
to: { type: "string", description: "Recipients, comma separated." },
|
|
225
|
+
subject: { type: "string" },
|
|
226
|
+
body: { type: "string", description: "Plain-text body." },
|
|
227
|
+
cc: { type: "string" },
|
|
228
|
+
bcc: { type: "string" },
|
|
229
|
+
attachments: ATTACHMENTS_PARAM,
|
|
230
|
+
confirmed: CONFIRMED_PARAM,
|
|
231
|
+
},
|
|
232
|
+
required: ["to", "subject", "body"],
|
|
233
|
+
},
|
|
234
|
+
run: async (p, { userId }) => {
|
|
235
|
+
const to = str(p.to), subject = str(p.subject), body = typeof p.body === "string" ? p.body : "";
|
|
236
|
+
if (!to || !subject || !body) return { ok: false, error: "to, subject y body son obligatorios." };
|
|
237
|
+
const cc = str(p.cc), bcc = str(p.bcc);
|
|
238
|
+
const pending = needsConfirmation(p, { to, cc, bcc, subject, body: body.slice(0, 500), attachments: attachSummary(p) });
|
|
239
|
+
if (pending) return pending;
|
|
240
|
+
const raw = buildRaw({ to, cc, bcc, subject, body, attachments: await loadAttachments(p) });
|
|
241
|
+
const sent = await googleJson<any>(userId, "gmail", `${API}/messages/send`, { method: "POST", body: { raw } });
|
|
242
|
+
return { ok: true, id: sent.id, thread_id: sent.threadId };
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
export const gmailReplyTool = googleTool({
|
|
247
|
+
name: "gmail_reply",
|
|
248
|
+
description:
|
|
249
|
+
"Reply to an email in its thread (keeps subject, In-Reply-To and recipients). reply_all=true also includes the other recipients. " +
|
|
250
|
+
"IRREVERSIBLE unless save_as_draft=true: first call returns a preview and needs_confirmation; repeat with confirmed=true after the user approves. " +
|
|
251
|
+
"Spanish: responder correo, contestar email, responder a todos",
|
|
252
|
+
parameters: {
|
|
253
|
+
type: "object",
|
|
254
|
+
properties: {
|
|
255
|
+
message_id: { type: "string", description: "Id of the message being answered (from gmail_search/gmail_read)." },
|
|
256
|
+
body: { type: "string", description: "Plain-text reply." },
|
|
257
|
+
reply_all: { type: "boolean", description: "Include the original To/Cc recipients. Default false." },
|
|
258
|
+
save_as_draft: { type: "boolean", description: "Save the reply as a draft instead of sending." },
|
|
259
|
+
attachments: ATTACHMENTS_PARAM,
|
|
260
|
+
confirmed: CONFIRMED_PARAM,
|
|
261
|
+
},
|
|
262
|
+
required: ["message_id", "body"],
|
|
263
|
+
},
|
|
264
|
+
run: async (p, { userId }) => {
|
|
265
|
+
const id = str(p.message_id), body = typeof p.body === "string" ? p.body : "";
|
|
266
|
+
if (!id || !body) return { ok: false, error: "message_id y body son obligatorios." };
|
|
267
|
+
const ctx = await replyContext(userId, id, p.reply_all === true);
|
|
268
|
+
const draft = p.save_as_draft === true;
|
|
269
|
+
if (!draft) {
|
|
270
|
+
const pending = needsConfirmation(p, { to: ctx.to, cc: ctx.cc, subject: ctx.subject, body: body.slice(0, 500), attachments: attachSummary(p) });
|
|
271
|
+
if (pending) return pending;
|
|
272
|
+
}
|
|
273
|
+
const raw = buildRaw({ ...ctx, body, attachments: await loadAttachments(p) });
|
|
274
|
+
if (draft) {
|
|
275
|
+
const d = await googleJson<any>(userId, "gmail", `${API}/drafts`, { method: "POST", body: { message: { raw, threadId: ctx.threadId } } });
|
|
276
|
+
return { ok: true, draft_id: d.id, message_id: d.message?.id, thread_id: ctx.threadId };
|
|
277
|
+
}
|
|
278
|
+
const sent = await googleJson<any>(userId, "gmail", `${API}/messages/send`, { method: "POST", body: { raw, threadId: ctx.threadId } });
|
|
279
|
+
return { ok: true, id: sent.id, thread_id: sent.threadId, to: ctx.to, cc: ctx.cc };
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// ─── Borradores ─────────────────────────────────────────────────────────────
|
|
284
|
+
|
|
285
|
+
export const gmailDraftSaveTool = googleTool({
|
|
286
|
+
name: "gmail_draft_save",
|
|
287
|
+
description:
|
|
288
|
+
"Create a Gmail draft, or EDIT an existing one by passing draft_id (the whole draft is replaced: read it first with gmail_read and resend every field). Never sends anything. " +
|
|
289
|
+
"Spanish: crear borrador, editar borrador, guardar borrador",
|
|
290
|
+
parameters: {
|
|
291
|
+
type: "object",
|
|
292
|
+
properties: {
|
|
293
|
+
draft_id: { type: "string", description: "Existing draft to replace. Omit to create a new one." },
|
|
294
|
+
to: { type: "string" }, subject: { type: "string" }, body: { type: "string" },
|
|
295
|
+
cc: { type: "string" }, bcc: { type: "string" },
|
|
296
|
+
attachments: ATTACHMENTS_PARAM,
|
|
297
|
+
},
|
|
298
|
+
required: ["to", "subject", "body"],
|
|
299
|
+
},
|
|
300
|
+
run: async (p, { userId }) => {
|
|
301
|
+
const to = str(p.to), subject = str(p.subject), body = typeof p.body === "string" ? p.body : "";
|
|
302
|
+
if (!to || !subject || !body) return { ok: false, error: "to, subject y body son obligatorios." };
|
|
303
|
+
const raw = buildRaw({ to, cc: str(p.cc), bcc: str(p.bcc), subject, body, attachments: await loadAttachments(p) });
|
|
304
|
+
const id = str(p.draft_id);
|
|
305
|
+
const d = await googleJson<any>(userId, "gmail", id ? `${API}/drafts/${encodeURIComponent(id)}` : `${API}/drafts`, {
|
|
306
|
+
method: id ? "PUT" : "POST", body: { message: { raw } },
|
|
307
|
+
});
|
|
308
|
+
return { ok: true, draft_id: d.id, message_id: d.message?.id, updated: !!id };
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
export const gmailDraftListTool = googleTool({
|
|
313
|
+
name: "gmail_draft_list",
|
|
314
|
+
description: "List the user's Gmail drafts (draft_id, message_id, recipients, subject). Use gmail_read with message_id for the body. Spanish: ver borradores, mis borradores",
|
|
315
|
+
parameters: { type: "object", properties: { max_results: { type: "number", minimum: 1, maximum: 20, description: "Default 10." } } },
|
|
316
|
+
run: async (p, { userId }) => {
|
|
317
|
+
const list = await googleJson<{ drafts?: Array<{ id: string }> }>(userId, "gmail", `${API}/drafts`, { query: { maxResults: num(p.max_results, 10, 1, 20) } });
|
|
318
|
+
const drafts = await Promise.all((list.drafts ?? []).map(async (d) => {
|
|
319
|
+
const full = await googleJson<any>(userId, "gmail", `${API}/drafts/${d.id}?format=metadata&metadataHeaders=To&metadataHeaders=Subject&metadataHeaders=Date`).catch(() => null);
|
|
320
|
+
return full && { draft_id: d.id, message_id: full.message?.id, to: header(full.message, "To"), subject: header(full.message, "Subject"), snippet: full.message?.snippet };
|
|
321
|
+
}));
|
|
322
|
+
return { ok: true, drafts: drafts.filter(Boolean) };
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
export const gmailDraftSendTool = googleTool({
|
|
327
|
+
name: "gmail_draft_send",
|
|
328
|
+
description: "Send an existing draft. IRREVERSIBLE: needs_confirmation first, then confirmed=true after user approval. Spanish: enviar borrador",
|
|
329
|
+
parameters: { type: "object", properties: { draft_id: { type: "string" }, confirmed: CONFIRMED_PARAM }, required: ["draft_id"] },
|
|
330
|
+
run: async (p, { userId }) => {
|
|
331
|
+
const id = str(p.draft_id);
|
|
332
|
+
if (!id) return { ok: false, error: "draft_id es obligatorio." };
|
|
333
|
+
const d = await googleJson<any>(userId, "gmail", `${API}/drafts/${encodeURIComponent(id)}?format=metadata&metadataHeaders=To&metadataHeaders=Subject`);
|
|
334
|
+
const pending = needsConfirmation(p, { draft_id: id, to: header(d.message, "To"), subject: header(d.message, "Subject"), snippet: d.message?.snippet });
|
|
335
|
+
if (pending) return pending;
|
|
336
|
+
const sent = await googleJson<any>(userId, "gmail", `${API}/drafts/send`, { method: "POST", body: { id } });
|
|
337
|
+
return { ok: true, id: sent.id, thread_id: sent.threadId };
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
export const gmailDraftDeleteTool = googleTool({
|
|
342
|
+
name: "gmail_draft_delete",
|
|
343
|
+
description: "Permanently delete a draft. Needs confirmation (needs_confirmation, then confirmed=true). Spanish: borrar borrador, eliminar borrador",
|
|
344
|
+
parameters: { type: "object", properties: { draft_id: { type: "string" }, confirmed: CONFIRMED_PARAM }, required: ["draft_id"] },
|
|
345
|
+
run: async (p, { userId }) => {
|
|
346
|
+
const id = str(p.draft_id);
|
|
347
|
+
if (!id) return { ok: false, error: "draft_id es obligatorio." };
|
|
348
|
+
const pending = needsConfirmation(p, { draft_id: id, action: "delete_draft" });
|
|
349
|
+
if (pending) return pending;
|
|
350
|
+
await googleJson(userId, "gmail", `${API}/drafts/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
351
|
+
return { ok: true, deleted: id };
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
// ─── Organizar: leído, destacado, archivo, papelera, etiquetas ──────────────
|
|
356
|
+
|
|
357
|
+
const MODIFY_ACTIONS = [
|
|
358
|
+
"mark_read", "mark_unread", "star", "unstar", "archive", "move_to_inbox",
|
|
359
|
+
"mark_important", "mark_not_important", "trash", "untrash",
|
|
360
|
+
] as const;
|
|
361
|
+
|
|
362
|
+
const LABEL_EFFECT: Record<string, { add?: string[]; remove?: string[] }> = {
|
|
363
|
+
mark_read: { remove: ["UNREAD"] },
|
|
364
|
+
mark_unread: { add: ["UNREAD"] },
|
|
365
|
+
star: { add: ["STARRED"] },
|
|
366
|
+
unstar: { remove: ["STARRED"] },
|
|
367
|
+
archive: { remove: ["INBOX"] },
|
|
368
|
+
move_to_inbox: { add: ["INBOX"] },
|
|
369
|
+
mark_important: { add: ["IMPORTANT"] },
|
|
370
|
+
mark_not_important: { remove: ["IMPORTANT"] },
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
async function resolveLabels(userId: string, names: string[]): Promise<string[]> {
|
|
374
|
+
if (!names.length) return [];
|
|
375
|
+
const { labels = [] } = await googleJson<{ labels?: Array<{ id: string; name: string }> }>(userId, "gmail", `${API}/labels`);
|
|
376
|
+
return names.map((n) => {
|
|
377
|
+
const hit = labels.find((l) => l.id === n || l.name.toLowerCase() === n.toLowerCase());
|
|
378
|
+
if (!hit) throw new Error(`No existe la etiqueta "${n}". Usa gmail_labels para listarlas o crearla.`);
|
|
379
|
+
return hit.id;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export const gmailModifyTool = googleTool({
|
|
384
|
+
name: "gmail_modify",
|
|
385
|
+
description:
|
|
386
|
+
"Organize one or many messages (up to 50): mark read/unread, star/unstar, archive, move back to inbox, mark important, send to trash or restore, and add/remove labels. Reversible, no confirmation needed. " +
|
|
387
|
+
"Spanish: marcar como leído, marcar no leído, archivar correo, destacar, mover a la papelera, poner etiqueta",
|
|
388
|
+
parameters: {
|
|
389
|
+
type: "object",
|
|
390
|
+
properties: {
|
|
391
|
+
message_ids: { type: "array", items: { type: "string" }, description: "Message ids (from gmail_search). Max 50." },
|
|
392
|
+
action: { type: "string", enum: [...MODIFY_ACTIONS], description: "Optional preset action." },
|
|
393
|
+
add_labels: { type: "array", items: { type: "string" }, description: "Label names or ids to add." },
|
|
394
|
+
remove_labels: { type: "array", items: { type: "string" }, description: "Label names or ids to remove." },
|
|
395
|
+
},
|
|
396
|
+
required: ["message_ids"],
|
|
397
|
+
},
|
|
398
|
+
run: async (p, { userId }) => {
|
|
399
|
+
const ids = (Array.isArray(p.message_ids) ? p.message_ids : []).filter((x): x is string => typeof x === "string" && !!x).slice(0, 50);
|
|
400
|
+
if (!ids.length) return { ok: false, error: "message_ids es obligatorio." };
|
|
401
|
+
const action = str(p.action);
|
|
402
|
+
if (action && !(MODIFY_ACTIONS as readonly string[]).includes(action)) return { ok: false, error: `action inválida: ${action}.` };
|
|
403
|
+
const strs = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && !!x) : []);
|
|
404
|
+
const extraAdd = strs(p.add_labels), extraRemove = strs(p.remove_labels);
|
|
405
|
+
if (!action && !extraAdd.length && !extraRemove.length) return { ok: false, error: "Indica action, add_labels o remove_labels." };
|
|
406
|
+
|
|
407
|
+
if (action === "trash" || action === "untrash") {
|
|
408
|
+
await Promise.all(ids.map((id) => googleJson(userId, "gmail", `${API}/messages/${encodeURIComponent(id)}/${action}`, { method: "POST" })));
|
|
409
|
+
if (!extraAdd.length && !extraRemove.length) return { ok: true, action, count: ids.length };
|
|
410
|
+
}
|
|
411
|
+
const effect = action ? LABEL_EFFECT[action] : undefined;
|
|
412
|
+
const addLabelIds = [...(effect?.add ?? []), ...(await resolveLabels(userId, extraAdd))];
|
|
413
|
+
const removeLabelIds = [...(effect?.remove ?? []), ...(await resolveLabels(userId, extraRemove))];
|
|
414
|
+
if (addLabelIds.length || removeLabelIds.length) {
|
|
415
|
+
await googleJson(userId, "gmail", `${API}/messages/batchModify`, { method: "POST", body: { ids, addLabelIds, removeLabelIds } });
|
|
416
|
+
}
|
|
417
|
+
return { ok: true, action: action ?? "labels", count: ids.length, added: addLabelIds, removed: removeLabelIds };
|
|
418
|
+
},
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
export const gmailLabelsTool = googleTool({
|
|
422
|
+
name: "gmail_labels",
|
|
423
|
+
description:
|
|
424
|
+
"Manage Gmail labels: list them (no params), create (create=<name>), rename (label + new_name) or delete (delete=<label>, needs confirmation; mails keep existing but lose the label). System labels cannot be changed. " +
|
|
425
|
+
"Spanish: ver etiquetas, crear etiqueta, renombrar etiqueta, borrar etiqueta, carpetas de gmail",
|
|
426
|
+
parameters: {
|
|
427
|
+
type: "object",
|
|
428
|
+
properties: {
|
|
429
|
+
create: { type: "string", description: "Name of a label to create." },
|
|
430
|
+
label: { type: "string", description: "Label name or id to rename (use with new_name)." },
|
|
431
|
+
new_name: { type: "string" },
|
|
432
|
+
delete: { type: "string", description: "Label name or id to delete." },
|
|
433
|
+
confirmed: CONFIRMED_PARAM,
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
run: async (p, { userId }) => {
|
|
437
|
+
const create = str(p.create), label = str(p.label), del = str(p.delete);
|
|
438
|
+
const all = async () => (await googleJson<{ labels?: any[] }>(userId, "gmail", `${API}/labels`)).labels ?? [];
|
|
439
|
+
const find = async (name: string) => {
|
|
440
|
+
const hit = (await all()).find((l) => l.id === name || l.name.toLowerCase() === name.toLowerCase());
|
|
441
|
+
if (!hit) throw new Error(`No existe la etiqueta "${name}".`);
|
|
442
|
+
if (hit.type === "system") throw new Error(`"${hit.name}" es una etiqueta del sistema y no se puede modificar.`);
|
|
443
|
+
return hit;
|
|
444
|
+
};
|
|
445
|
+
if (create) {
|
|
446
|
+
const l = await googleJson<any>(userId, "gmail", `${API}/labels`, { method: "POST", body: { name: create, labelListVisibility: "labelShow", messageListVisibility: "show" } });
|
|
447
|
+
return { ok: true, created: { id: l.id, name: l.name } };
|
|
448
|
+
}
|
|
449
|
+
if (label) {
|
|
450
|
+
const newName = str(p.new_name);
|
|
451
|
+
if (!newName) return { ok: false, error: "new_name es obligatorio para renombrar." };
|
|
452
|
+
const l = await find(label);
|
|
453
|
+
const r = await googleJson<any>(userId, "gmail", `${API}/labels/${encodeURIComponent(l.id)}`, { method: "PATCH", body: { name: newName } });
|
|
454
|
+
return { ok: true, renamed: { id: r.id, from: l.name, to: r.name } };
|
|
455
|
+
}
|
|
456
|
+
if (del) {
|
|
457
|
+
const l = await find(del);
|
|
458
|
+
const pending = needsConfirmation(p, { action: "delete_label", label: l.name });
|
|
459
|
+
if (pending) return pending;
|
|
460
|
+
await googleJson(userId, "gmail", `${API}/labels/${encodeURIComponent(l.id)}`, { method: "DELETE" });
|
|
461
|
+
return { ok: true, deleted: l.name };
|
|
462
|
+
}
|
|
463
|
+
return { ok: true, labels: (await all()).map((l) => ({ id: l.id, name: l.name, type: l.type })) };
|
|
464
|
+
},
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
// ─── Reenviar ───────────────────────────────────────────────────────────────
|
|
468
|
+
|
|
469
|
+
export const gmailForwardTool = googleTool({
|
|
470
|
+
name: "gmail_forward",
|
|
471
|
+
description:
|
|
472
|
+
"Forward an email to new recipients with an optional note, including the original text and (by default) its attachments. IRREVERSIBLE: needs_confirmation first, then confirmed=true after user approval. " +
|
|
473
|
+
"Spanish: reenviar correo, forward, pasar este correo a",
|
|
474
|
+
parameters: {
|
|
475
|
+
type: "object",
|
|
476
|
+
properties: {
|
|
477
|
+
message_id: { type: "string" },
|
|
478
|
+
to: { type: "string", description: "Recipients, comma separated." },
|
|
479
|
+
note: { type: "string", description: "Optional text placed above the forwarded message." },
|
|
480
|
+
cc: { type: "string" },
|
|
481
|
+
include_attachments: { type: "boolean", description: "Default true." },
|
|
482
|
+
confirmed: CONFIRMED_PARAM,
|
|
483
|
+
},
|
|
484
|
+
required: ["message_id", "to"],
|
|
485
|
+
},
|
|
486
|
+
run: async (p, { userId }) => {
|
|
487
|
+
const id = str(p.message_id), to = str(p.to);
|
|
488
|
+
if (!id || !to) return { ok: false, error: "message_id y to son obligatorios." };
|
|
489
|
+
const m = await googleJson<any>(userId, "gmail", `${API}/messages/${encodeURIComponent(id)}`, { query: { format: "full" } });
|
|
490
|
+
const files = attachments(m.payload);
|
|
491
|
+
const withFiles = p.include_attachments !== false;
|
|
492
|
+
const subject = header(m, "Subject");
|
|
493
|
+
const pending = needsConfirmation(p, {
|
|
494
|
+
to, cc: str(p.cc), subject: /^fwd?:/i.test(subject) ? subject : `Fwd: ${subject}`,
|
|
495
|
+
note: str(p.note), original_from: header(m, "From"), attachments: withFiles ? files.map((f) => f.filename) : [],
|
|
496
|
+
});
|
|
497
|
+
if (pending) return pending;
|
|
498
|
+
|
|
499
|
+
const body = [
|
|
500
|
+
str(p.note) ?? "",
|
|
501
|
+
"",
|
|
502
|
+
"---------- Mensaje reenviado ----------",
|
|
503
|
+
`De: ${header(m, "From")}`, `Fecha: ${header(m, "Date")}`, `Asunto: ${subject}`, `Para: ${header(m, "To")}`,
|
|
504
|
+
"", extractBody(m.payload),
|
|
505
|
+
].join("\n");
|
|
506
|
+
|
|
507
|
+
const loaded: NonNullable<RawMessage["attachments"]> = [];
|
|
508
|
+
let total = 0;
|
|
509
|
+
if (withFiles) {
|
|
510
|
+
for (const f of files.slice(0, 10)) {
|
|
511
|
+
total += f.size;
|
|
512
|
+
if (total > MAX_ATTACH_TOTAL) return { ok: false, error: "Los adjuntos del original superan los 18 MB; reenvía con include_attachments=false." };
|
|
513
|
+
const a = await googleJson<{ data?: string }>(userId, "gmail", `${API}/messages/${encodeURIComponent(id)}/attachments/${encodeURIComponent(f.attachment_id)}`);
|
|
514
|
+
loaded.push({ filename: f.filename, mimeType: f.mime_type || "application/octet-stream", bytes: new Uint8Array(Buffer.from(a.data ?? "", "base64url")) });
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const raw = buildRaw({ to, cc: str(p.cc), subject: /^fwd?:/i.test(subject) ? subject : `Fwd: ${subject}`, body, attachments: loaded });
|
|
518
|
+
const sent = await googleJson<any>(userId, "gmail", `${API}/messages/send`, { method: "POST", body: { raw } });
|
|
519
|
+
return { ok: true, id: sent.id, thread_id: sent.threadId, forwarded_attachments: loaded.length };
|
|
520
|
+
},
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
// ─── Hilos y adjuntos recibidos ─────────────────────────────────────────────
|
|
524
|
+
|
|
525
|
+
export const gmailThreadTool = googleTool({
|
|
526
|
+
name: "gmail_thread",
|
|
527
|
+
description: "Read a whole conversation thread (all messages in order, text bodies trimmed). Spanish: leer conversación, hilo de correos, historial del correo",
|
|
528
|
+
parameters: { type: "object", properties: { thread_id: { type: "string" } }, required: ["thread_id"] },
|
|
529
|
+
run: async (p, { userId }) => {
|
|
530
|
+
const id = str(p.thread_id);
|
|
531
|
+
if (!id) return { ok: false, error: "thread_id es obligatorio." };
|
|
532
|
+
const t = await googleJson<any>(userId, "gmail", `${API}/threads/${encodeURIComponent(id)}`, { query: { format: "full" } });
|
|
533
|
+
const PER = 4000, TOTAL = 24_000;
|
|
534
|
+
let used = 0;
|
|
535
|
+
const messages = (t.messages ?? []).map((m: any) => {
|
|
536
|
+
const body = extractBody(m.payload).slice(0, PER);
|
|
537
|
+
used += body.length;
|
|
538
|
+
return {
|
|
539
|
+
id: m.id, from: header(m, "From"), to: header(m, "To"), date: header(m, "Date"), subject: header(m, "Subject"),
|
|
540
|
+
body: used > TOTAL ? "[omitido por tamaño: usa gmail_read]" : body, attachments: attachments(m.payload),
|
|
541
|
+
};
|
|
542
|
+
});
|
|
543
|
+
return { ok: true, thread_id: t.id, count: messages.length, messages };
|
|
544
|
+
},
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
export const gmailAttachmentTool = googleTool({
|
|
548
|
+
name: "gmail_attachment_download",
|
|
549
|
+
description:
|
|
550
|
+
"Download an attachment of a received email into a Hive artifact (ids come from gmail_read: message id + attachment_id). Spanish: descargar adjunto, guardar adjunto del correo",
|
|
551
|
+
parameters: {
|
|
552
|
+
type: "object",
|
|
553
|
+
properties: { message_id: { type: "string" }, attachment_id: { type: "string" }, filename: { type: "string", description: "Original file name (for the extension)." } },
|
|
554
|
+
required: ["message_id", "attachment_id"],
|
|
555
|
+
},
|
|
556
|
+
run: async (p, { userId, config }) => {
|
|
557
|
+
const mid = str(p.message_id), aid = str(p.attachment_id);
|
|
558
|
+
if (!mid || !aid) return { ok: false, error: "message_id y attachment_id son obligatorios." };
|
|
559
|
+
const a = await googleJson<{ data?: string; size?: number }>(userId, "gmail", `${API}/messages/${encodeURIComponent(mid)}/attachments/${encodeURIComponent(aid)}`);
|
|
560
|
+
const bytes = new Uint8Array(Buffer.from(a.data ?? "", "base64url"));
|
|
561
|
+
if (!bytes.byteLength) return { ok: false, error: "El adjunto está vacío." };
|
|
562
|
+
const filename = str(p.filename);
|
|
563
|
+
const ext = filename ? /\.([A-Za-z0-9]{1,8})$/.exec(filename)?.[1]?.toLowerCase() : undefined;
|
|
564
|
+
const mime = ext === "pdf" ? "application/pdf" : "application/octet-stream";
|
|
565
|
+
const artifact = await createArtifact({
|
|
566
|
+
bytes, mimeType: mime, kind: "gmail_attachment", userId, extension: ext,
|
|
567
|
+
visible: { workspace: getWorkspace(config), folder: "descargas", label: filename ? filename.replace(/\.[^.]+$/, "") : "adjunto" },
|
|
568
|
+
runId: config?.configurable?.run_id ?? null, taskId: config?.configurable?.task_id ?? null,
|
|
569
|
+
});
|
|
570
|
+
return { ok: true, artifact_id: artifact.id, size: bytes.byteLength, filename };
|
|
571
|
+
},
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
export const gmailTools = [
|
|
575
|
+
gmailSearchTool, gmailReadTool, gmailThreadTool,
|
|
576
|
+
gmailSendTool, gmailReplyTool, gmailForwardTool,
|
|
577
|
+
gmailDraftSaveTool, gmailDraftListTool, gmailDraftSendTool, gmailDraftDeleteTool,
|
|
578
|
+
gmailModifyTool, gmailLabelsTool, gmailAttachmentTool,
|
|
579
|
+
];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Workspace tools (Gmail, Calendar, Drive).
|
|
3
|
+
*
|
|
4
|
+
* Sólo entran en el loadout cuando el host llamó `configureGoogle()`.
|
|
5
|
+
* Cada tool opera con la cuenta que el usuario de la sesión conectó.
|
|
6
|
+
*/
|
|
7
|
+
import type { Tool } from "../types.ts";
|
|
8
|
+
import { gmailTools } from "./gmail.ts";
|
|
9
|
+
import { calendarTools } from "./calendar.ts";
|
|
10
|
+
import { driveTools } from "./drive.ts";
|
|
11
|
+
|
|
12
|
+
export function createTools(): Tool[] {
|
|
13
|
+
return [...gmailTools, ...calendarTools, ...driveTools];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export * from "./gmail.ts";
|
|
17
|
+
export * from "./calendar.ts";
|
|
18
|
+
export * from "./drive.ts";
|