Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/admin/views/agente.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ const TOOL_META: Record<string, ToolMeta> = {
desc: "Guardrail de abuso: manda a cooldown (default 1h) a quien insulta, spamea, es otro bot o usa al bot como ChatGPT gratis — el bot ignora sus mensajes ese rato.",
icon: "shield",
},
pauseSuspectedBot: {
label: "Frenar bots",
desc: "Pausa 24 h cuando del otro lado hay una cuenta automatizada. Ignora los avisos de audio o foto que no se pudieron leer.",
icon: "shield-alert",
},
captureLead: {
label: "Capturar lead",
desc: "Guarda los datos del cliente interesado (nombre, contacto, intención) en la tabla de leads.",
Expand Down
77 changes: 68 additions & 9 deletions src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { MessagesRepo } from "./db/messages";
import { isPro } from "./config";
import { resolveAgentConfig } from "./settings-loader";
import { buildTools } from "./tools";
import { buildMultimodalUserMessage } from "./media/vision";
import { AUDIO_EMPTY, AUDIO_NOT_UNDERSTOOD, textAfterImageFetchFailure } from "./media/placeholders";
import { buildMultimodalUserMessage, describeImage } from "./media/vision";
import { chunkReply } from "./replies/chunker";
import { pickAdapter } from "./replies/sender";
import { selectModel } from "./upgrade/modelSelector";
Expand Down Expand Up @@ -126,10 +127,10 @@ export class SupportAgent extends Agent<Env, SupportAgentState> {
try {
const { transcribeAudio } = await import("./media/transcribe");
const result = await transcribeAudio(payload.audioUrl, this.env);
processedText = result.text || "(audio sin transcripción)";
processedText = result.text || AUDIO_EMPTY;
} catch (e) {
console.error("[ingest] transcription failed:", e);
processedText = "(no pude entender el audio)";
processedText = AUDIO_NOT_UNDERSTOOD;
}
}

Expand Down Expand Up @@ -226,12 +227,44 @@ export class SupportAgent extends Agent<Env, SupportAgentState> {
return;
}

// Persist user message
await msgs.append(convId, "user", combined);
await convs.touchLastMessage(convId);
// Si el insert no llega a D1, el mensaje sigue en el buffer y se rearma
// la alarma. Si ya se guardó, no se reintenta: un segundo append lo duplicaría.
let userMsgId: string | null = null;
try {
userMsgId = await msgs.append(convId, "user", combined);
} catch (e) {
console.error("[SupportAgent.processBuffer] no se pudo guardar el mensaje:", e);
this.setState({ ...this.state, pendingMessages: buffered });
const alarmAt = Date.now() + 500;
const alarmAtSec = Math.floor(alarmAt / 1000);
try {
this.sql`
INSERT OR REPLACE INTO cf_agents_schedules
(id, callback, payload, type, time, created_at)
VALUES
('msg-buffer', 'processBuffer', '{}', 'delayed', ${alarmAtSec}, unixepoch())
`;
await this.ctx.storage.setAlarm(alarmAt);
} catch (armErr) {
console.error("[SupportAgent.processBuffer] no se pudo rearmar el buffer:", armErr);
}
return;
}
try {
await convs.touchLastMessage(convId);
} catch (e) {
console.warn("[SupportAgent.processBuffer] touchLastMessage failed:", e);
}

// Load history (last 20)
const history = await msgs.lastN(convId, 20);
// Load history (last 20). Si la lectura falla, el turno sigue con el
// mensaje que acabamos de guardar: ya está en D1 y no hay que insertarlo otra vez.
let history: { id?: string; role: string; content: string }[];
try {
history = await msgs.lastN(convId, 20);
} catch (e) {
console.error("[SupportAgent.processBuffer] no se pudo leer el historial:", e);
history = [{ id: userMsgId ?? undefined, role: "user", content: combined }];
}
const aiMessages: any[] = history.slice(0, -1).map((m) => ({
role: (m.role === "tool"
? "user"
Expand All @@ -243,6 +276,7 @@ export class SupportAgent extends Agent<Env, SupportAgentState> {
// Build the LAST user message multimodal-aware: if it carries an
// [IMAGE_URL: ...] marker AND we're on the Pro tier, attach the image.
const lastUserMsg = history[history.length - 1];
let suppressSuspectedBotPause = false;
if (lastUserMsg) {
const imgMatch = lastUserMsg.content.match(/\[IMAGE_URL: (.+?)\]/);
if (imgMatch && isPro(this.env)) {
Expand All @@ -255,7 +289,29 @@ export class SupportAgent extends Agent<Env, SupportAgentState> {
const cleanText = lastUserMsg.content
.replace(/\n?\[IMAGE_URL: .+?\]/, "")
.trim();
aiMessages.push(buildMultimodalUserMessage(cleanText, imageUrl));
// Zernio no sirve la foto sin Bearer. La bajamos aquí y el modelo
// recibe los bytes; una URL pública sigue siendo URL.
try {
const image = await describeImage(imageUrl, this.env);
aiMessages.push(buildMultimodalUserMessage(cleanText, image));
} catch (e) {
console.error("[SupportAgent] image fetch failed:", e);
// Se reescribe la fila que trae el [IMAGE_URL], no otra. Tiene que
// quedar lista antes del modelo para que pauseSuspectedBot la vea.
const failureText = textAfterImageFetchFailure(cleanText);
const markerRowId = lastUserMsg.id;
let rewritten = false;
if (markerRowId) {
try {
await msgs.updateContent(markerRowId, failureText);
rewritten = true;
} catch (writeErr) {
console.error("[SupportAgent] no se pudo marcar el fallo de la foto:", writeErr);
}
}
if (!rewritten) suppressSuspectedBotPause = true;
aiMessages.push({ role: "user", content: failureText });
}
} else {
aiMessages.push({ role: "user", content: lastUserMsg.content });
}
Expand All @@ -266,6 +322,9 @@ export class SupportAgent extends Agent<Env, SupportAgentState> {
env: this.env,
getConversationId: () => convId,
});
// La fila sigue diciendo "(imagen sin caption)": sin el aviso de fallo,
// pauseSuspectedBot pausaría 24 h. En este turno no se le ofrece.
if (suppressSuspectedBotPause) delete tools.pauseSuspectedBot;
const toolNames = Object.keys(tools);

// Resolve effective config (D1 settings overlaid on env defaults).
Expand Down
11 changes: 8 additions & 3 deletions src/db/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,19 @@ export class MessagesRepo {
return id;
}

async updateContent(id: string, content: string): Promise<void> {
await this.db.run("UPDATE messages SET content = ? WHERE id = ?", [content, id]);
}

async lastN(conversationId: string, n: number): Promise<Message[]> {
const rows = await this.db.all<Message>(
`SELECT * FROM (
SELECT * FROM messages
SELECT messages.*, messages.rowid AS insert_order
FROM messages
WHERE conversation_id = ?
ORDER BY created_at DESC
ORDER BY messages.created_at DESC, messages.rowid DESC
LIMIT ?
) ORDER BY created_at ASC`,
) ORDER BY created_at ASC, insert_order ASC`,
[conversationId, n],
);
return rows;
Expand Down
5 changes: 5 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ export interface Env {
WHATSAPP_VERIFY_TOKEN?: string; // handshake GET del webhook (si falta, usa META_VERIFY_TOKEN)
WHATSAPP_APP_SECRET?: string; // firma X-Hub-Signature-256 (si falta, usa META_APP_SECRET)
XAI_API_KEY?: string; // xAI (Grok) — proveedor LLM alterno (ver src/llm/provider.ts)
// Zernio (WhatsApp). El webhook trae attachments[].url apuntando a
// GET /v1/whatsapp/media/{id}, que exige Authorization: Bearer. La llave
// solo se manda si el host es zernio.com o el de ZERNIO_API_BASE.
ZERNIO_API_KEY?: string;
ZERNIO_API_BASE?: string; // opcional; default: cualquier host *.zernio.com

// ── Cal.com (agenda real para scheduleAppointment) ───────────────────────
// Con estas vars, el bot consulta disponibilidad real y reserva en Cal.com.
Expand Down
29 changes: 29 additions & 0 deletions src/media/boveda.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { Env } from "../env";
import { fetchInboundMedia, type ZernioEnv } from "./zernio";

export interface CapturedMedia {
bytes: Uint8Array;
contentType: string;
}

export class MediaFetchError extends Error {
constructor(readonly status: number) {
super(`media fetch failed: ${status}`);
this.name = "MediaFetchError";
}
}

/**
* Baja los bytes de un adjunto entrante (nota de voz, foto).
* Zernio exige Authorization; fetchInboundMedia la pone solo en su host.
*/
export async function captureIncomingMedia(url: string, env: ZernioEnv & Partial<Env>): Promise<CapturedMedia> {
const res = await fetchInboundMedia(url, env);
if (!res.ok) throw new MediaFetchError(res.status);
const bytes = new Uint8Array(await res.arrayBuffer());
const contentType = (res.headers.get("content-type") || "application/octet-stream")
.split(";")[0]
.trim()
.toLowerCase();
return { bytes, contentType: contentType || "application/octet-stream" };
}
44 changes: 44 additions & 0 deletions src/media/placeholders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Textos que el bot guarda cuando NO pudo leer el audio o la foto.
// No son palabras del cliente: un fallo de descarga (401 de Zernio, red, etc.)
// deja el mismo placeholder en cada intento. Si el anti-bot los cuenta como
// "el mismo mensaje repetido", 3 notas de voz pausan a una persona real.

export const AUDIO_NOT_UNDERSTOOD = "(no pude entender el audio)";
export const AUDIO_EMPTY = "(audio sin transcripción)";
export const IMAGE_NOT_SEEN = "(no pude ver la imagen)";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/** Lo que se guarda cuando la foto llega sin texto del cliente. No es un fallo. */
export const IMAGE_NO_CAPTION = "(imagen sin caption)";

const PLACEHOLDERS = new Set(
[AUDIO_NOT_UNDERSTOOD, AUDIO_EMPTY, IMAGE_NOT_SEEN].map((s) => s.toLowerCase()),
);

/**
* True cuando el texto guardado es solo avisos de fallo de media, no palabras
* del cliente. Varios audios en el mismo buffer quedan en líneas separadas
* con el mismo placeholder: eso también cuenta.
*/
export function isMediaFailurePlaceholder(text: string): boolean {
const stripped = text.replace(/\n?\[IMAGE_URL: .+?\]/gi, "").trim();
if (!stripped) return false;
const parts = stripped
.split(/\n+/)
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
return parts.length > 0 && parts.every((p) => PLACEHOLDERS.has(p));
}

/**
* Texto que queda guardado si la foto no se pudo bajar. Una foto sin texto
* del cliente pasa a ser solo el aviso de fallo. Si el cliente sí escribió
* algo, ese texto se conserva y el aviso va en otra línea: sigue contando
* para la detección de bots.
*/
export function textAfterImageFetchFailure(cleanText: string): string {
const caption = cleanText
.split(/\n+/)
.map((s) => s.trim())
.filter((s) => s && s.toLowerCase() !== IMAGE_NO_CAPTION.toLowerCase())
.join("\n");
return caption ? `${caption}\n${IMAGE_NOT_SEEN}` : IMAGE_NOT_SEEN;
}
13 changes: 9 additions & 4 deletions src/media/transcribe.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Env } from "../env";
import { captureIncomingMedia, MediaFetchError } from "./boveda";

export interface TranscriptionResult {
text: string;
Expand All @@ -9,13 +10,17 @@ export async function transcribeAudio(
audioUrl: string,
env: Env,
): Promise<TranscriptionResult> {
const res = await fetch(audioUrl);
if (!res.ok) throw new Error(`audio fetch failed: ${res.status}`);
const buffer = await res.arrayBuffer();
let bytes: Uint8Array;
try {
({ bytes } = await captureIncomingMedia(audioUrl, env));
} catch (e) {
if (e instanceof MediaFetchError) throw new Error(`audio fetch failed: ${e.status}`);
throw e;
}
// whisper-large-v3-turbo expects a base64-encoded string in `audio` (per the
// Cloudflare Workers AI docs), NOT a raw byte array. nodejs_compat is enabled
// (see wrangler.toml) so Buffer is available, matching the official example.
const base64 = Buffer.from(buffer).toString("base64");
const base64 = Buffer.from(bytes).toString("base64");
const result = await env.AI.run("@cf/openai/whisper-large-v3-turbo" as any, {
audio: base64,
} as any);
Expand Down
31 changes: 25 additions & 6 deletions src/media/vision.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,36 @@
import type { ModelMessage } from "ai";
import type { Env } from "../env";
import { captureIncomingMedia } from "./boveda";
import { isZernioMediaUrl } from "./zernio";

/** URL pública (el modelo la baja) o bytes ya descargados (Zernio, que exige Bearer). */
export type ModelImageInput = string | { bytes: Uint8Array; mediaType: string };

export function buildMultimodalUserMessage(
text: string | undefined,
imageUrl: string | undefined,
image?: ModelImageInput,
): ModelMessage {
if (!imageUrl) {
if (!image) {
return { role: "user", content: text ?? "" };
}
const imagePart =
typeof image === "string"
? { type: "image" as const, image: new URL(image) }
: { type: "image" as const, image: image.bytes, mediaType: image.mediaType };
return {
role: "user",
content: [
{ type: "image", image: new URL(imageUrl) },
...(text ? [{ type: "text" as const, text }] : []),
],
content: [imagePart, ...(text ? [{ type: "text" as const, text }] : [])],
};
}

/**
* Prepara la foto para el modelo. Las URLs de Zernio no son públicas: hay que
* bajar los bytes con el Bearer y pasarlos como imagen. Una URL de Telegram,
* Meta o el proxy firmado de WhatsApp Cloud se deja como URL.
*/
export async function describeImage(imageUrl: string, env: Env): Promise<ModelImageInput> {
if (!isZernioMediaUrl(imageUrl, env)) return imageUrl;
const captured = await captureIncomingMedia(imageUrl, env);
const mediaType = captured.contentType.startsWith("image/") ? captured.contentType : "image/jpeg";
return { bytes: captured.bytes, mediaType };
}
65 changes: 65 additions & 0 deletions src/media/zernio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { Env } from "../env";
import { egressFetch, sanitizeHeaderValue } from "../http/egress";

/**
* Hosts a los que SÍ se les puede mandar ZERNIO_API_KEY.
* Cualquier otro host (CDN de Telegram, Graph de Meta, un webhook ajeno)
* recibe el fetch sin Authorization: la llave no sale de Zernio.
*/
const ZERNIO_SUFFIX = "zernio.com";

export type ZernioEnv = Pick<Env, "ZERNIO_API_KEY" | "ZERNIO_API_BASE">;

export function isZernioMediaUrl(rawUrl: string, env: ZernioEnv): boolean {
let url: URL;
try {
url = new URL(rawUrl);
} catch {
return false;
}
// La llave solo viaja por HTTPS. Un http://zernio.com la filtraría en claro.
if (url.protocol !== "https:") return false;
const host = url.hostname.toLowerCase();
if (host === ZERNIO_SUFFIX || host.endsWith(`.${ZERNIO_SUFFIX}`)) return true;
const base = env.ZERNIO_API_BASE?.trim();
if (!base) return false;
try {
const baseUrl = new URL(base.includes("://") ? base : `https://${base}`);
return baseUrl.protocol === "https:" && host === baseUrl.hostname.toLowerCase();
} catch {
return false;
}
}

function authHeaders(url: string, env: ZernioEnv): Headers {
const headers = new Headers();
if (!isZernioMediaUrl(url, env)) return headers;
const key = sanitizeHeaderValue(env.ZERNIO_API_KEY ?? "");
if (!key) return headers;
headers.set("Authorization", `Bearer ${key}`);
return headers;
}

/**
* GET de un adjunto entrante. El Bearer de Zernio se añade solo si el host
* de ESTA url es Zernio. Un redirect a otro origen se sigue sin la llave
* (el endpoint de media responde 200 con el binario; el corte es por si acaso).
*/
export async function fetchInboundMedia(url: string, env: ZernioEnv): Promise<Response> {
const headers = authHeaders(url, env);
const first = await egressFetch(url, { headers, redirect: "manual" });
if (first.status < 300 || first.status >= 400) return first;
const loc = first.headers.get("location");
if (!loc) return first;
let next: URL;
try {
next = new URL(loc, url);
} catch {
return first;
}
const sameOrigin = next.origin === new URL(url).origin;
return egressFetch(next, {
headers: sameOrigin ? headers : new Headers(),
redirect: "follow",
});
}
4 changes: 4 additions & 0 deletions src/spam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// la ignora por completo. El caso abusivo-pero-variado (insultos, bots que
// varían el texto) lo cubre la tool snoozeUser, que decide el LLM.
import { Db } from "./db/client";
import { isMediaFailurePlaceholder } from "./media/placeholders";

export const SPAM_SNOOZE_MS = 60 * 60_000;

Expand All @@ -27,6 +28,9 @@ export async function isRepeatSpam(
conversationId: string,
text: string,
): Promise<boolean> {
// Un audio que no se pudo transcribir deja el mismo placeholder cada vez.
// No es spam ni un bot: es nuestro fallo de descarga.
if (isMediaFailurePlaceholder(text)) return false;
const norm = normalizeForSpam(text);
if (norm.length < 2) return false; // "ok"/"sí" sueltos no cuentan como spam
const rows = await db.all<{ content: string }>(
Expand Down
Loading
Loading