Spaces:
Running
Running
Download api/lib/chatbot-normalize.ts from ahmdelbaz28/AHMDRTAP: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/lib/chatbot-normalize.ts
- Command line
-
hf download hf://spaces/ahmdelbaz28/AHMDRTAP/api/lib/chatbot-normalize.ts
-
curl -L -o chatbot-normalize.ts https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/lib/chatbot-normalize.ts
15.8 kB
| /** | |
| * CHATBOT INPUT NORMALIZATION — pure, dependency-free module. | |
| * | |
| * Extracted from api/chatbot-router.ts (unit-testable without the router's | |
| * heavy import graph: no Hono, no DB, no provider code — types only). | |
| * | |
| * Security/size rules: | |
| * • Only data: URLs with an image mime are accepted (no remote URLs — the | |
| * server must never be tricked into fetching attacker-chosen resources). | |
| * • Per-image base64 cap + per-request image count cap keep the request | |
| * far below the shield's 1MB payload guard. | |
| * • ONLY the LAST user message may carry image parts — anything else is | |
| * flattened to plain text so text-only providers are never exposed to | |
| * image parts in history. | |
| * • LIVE SCREEN flag: an image part tagged `source: "screen_capture"` in | |
| * the LAST user message marks the frame as a live capture of the user's | |
| * real screen (`screenCapture: true`) — the caller arms the screen- | |
| * teacher prompt. Any other/unknown tag value is ignored (never trusted). | |
| */ | |
| import type { ChatApiMessage, ContentPart } from "./chatbot.js"; | |
| import type { ChatbotErrorCode } from "./chatbot-errors.js"; | |
| export const IMAGE_DATAURL_RE = /^data:image\/(jpeg|jpg|png|webp|gif);base64,/; | |
| export const MAX_IMAGE_PART_BASE64 = 450_000; // ~337KB binary per image | |
| export const MAX_IMAGES_PER_REQUEST = 2; | |
| // ── Shared content caps (module scope — consumed by the router too) ── | |
| // ✅ SECURITY FIX (audit run-1): cap per-message content (previously a | |
| // single 1MB request could ship ~250k tokens to paid providers). | |
| export const MAX_MESSAGE_CHARS = 8_000; | |
| export const MAX_TOTAL_CHARS = 60_000; | |
| // ── Arabic-script detection (anti-koshary audit fix: one shared copy) ── | |
| // Full Arabic Unicode ranges (base + supplement + extended-A/B + presentation | |
| // forms-A/B). Shared by the router's language mirror and the Telegram brain; | |
| // the client keeps its own copy (src/lib/chat-render.ts) — api/ never imports | |
| // from src/ (bundle-boundary rule), so cross-boundary sharing stays flagged. | |
| export const ARABIC_CHAR_RE = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/; | |
| // ── ✅ TOKEN OPTIMIZATION (v3.6.0) — SLIDING-WINDOW HISTORY TRIM ── | |
| // The client ships its last 20 messages VERBATIM; assistant replies on this | |
| // platform reach 8k chars each, so a 10-round conversation could carry | |
| // ~30-60k chars (~8-15k prompt tokens) of mostly-stale assistant prose — | |
| // re-billed on EVERY send and on EVERY cascade attempt. The trim keeps the | |
| // IMMEDIATE context verbatim (the last 2 assistant turns + the current | |
| // question) and clips OLDER turns to short excerpts; long-range continuity | |
| // is already covered by the rolling summary (chat-history.ts). | |
| // Quality contract: the last 2 assistant answers (the direct conversational | |
| // thread) and every user question are NEVER clipped below their normal caps | |
| // — older assistant text is context, not commitments. | |
| export const TRIM_RECENT_ASSISTANT_FULL = 2; | |
| export const TRIMMED_ASSISTANT_CHARS = 600; | |
| export const TRIMMED_USER_CHARS = 800; | |
| const ASSISTANT_CLIP_MARK = "… [رد سابق مختصر]"; | |
| const USER_CLIP_MARK = "… [رسالة سابقة مختصرة]"; | |
| /** | |
| * Clip OLD conversation turns to short excerpts, newest-first exemption: | |
| * • the last 2 assistant messages stay full; | |
| * • the LAST user message stays full (the current question); | |
| * • older user messages clip to TRIMMED_USER_CHARS; | |
| * • older assistant messages clip to TRIMMED_ASSISTANT_CHARS. | |
| * Pure, delta-free — operates on already-normalized messages; image parts | |
| * (last user message only) pass through untouched. | |
| */ | |
| export function trimHistoryForContext(messages: ChatApiMessage[]): ChatApiMessage[] { | |
| const lastAssistantIdx: number[] = []; | |
| const lastUserIdx = (() => { | |
| for (let i = messages.length - 1; i >= 0; i--) { | |
| if (messages[i]?.role === "user") return i; | |
| } | |
| return -1; | |
| })(); | |
| for (let i = messages.length - 1; i >= 0 && lastAssistantIdx.length < TRIM_RECENT_ASSISTANT_FULL; i--) { | |
| if (messages[i]?.role === "assistant") lastAssistantIdx.push(i); | |
| } | |
| const fullAssistant = new Set(lastAssistantIdx); | |
| const clipText = (text: string, cap: number, mark: string): string => | |
| text.length > cap ? `${text.slice(0, cap).trimEnd()}${mark}` : text; | |
| return messages.map((m, i) => { | |
| if (typeof m.content !== "string") return m; // image parts: last user message only — never touched | |
| if (m.role === "assistant") { | |
| if (fullAssistant.has(i)) return m; | |
| return { ...m, content: clipText(m.content, TRIMMED_ASSISTANT_CHARS, ASSISTANT_CLIP_MARK) }; | |
| } | |
| // user: only the LAST user message keeps full text | |
| if (i === lastUserIdx) return m; | |
| return { ...m, content: clipText(m.content, TRIMMED_USER_CHARS, USER_CLIP_MARK) }; | |
| }); | |
| } | |
| export interface NormalizedChatInput { | |
| messages: ChatApiMessage[]; | |
| /** Last user message carries image parts — must route to vision models. */ | |
| vision: boolean; | |
| imageCount: number; | |
| totalTextChars: number; | |
| /** Last user message image parts are tagged `source: "screen_capture"` — | |
| * a LIVE frame of the user's actual screen → arms the screen-teacher | |
| * prompt (grounded step-by-step guidance, zero guessing). */ | |
| screenCapture: boolean; | |
| } | |
| export type NormalizeFailure = { status: 400 | 413; en: string; ar: string; code: ChatbotErrorCode }; | |
| // ✅ SECURITY FIX (audit run-3, chat-text-control-chars-stripped): chat text | |
| // keeps C0/C1 control characters (screen context strips them) — the text is | |
| // PERSISTED (chatMessages, feedback snapshots) and re-served from GET /history, | |
| // so strip the same \p{Cc} class at normalization for parity (newlines are | |
| // preserved — they are NOT in \p{Cc}). | |
| function stripChatControlChars(raw: string): string { | |
| return raw.replace(/\p{Cc}/gu, ""); | |
| } | |
| // ── S3776 decomposition of normalizeChatInput (each helper stays ≤15) ── | |
| interface ParsedMessage { | |
| role: "user" | "assistant"; | |
| /** Text parts (plain-string content arrives as a single stripped part). */ | |
| textParts: string[]; | |
| imageUrls: string[]; | |
| /** Any image part of THIS message carried `source: "screen_capture"`. */ | |
| lastImageScreenTagged: boolean; | |
| } | |
| /** Guarded slice: null when the raw payload is not a non-empty array. */ | |
| function sliceRawMessages(raw: unknown): unknown[] | null { | |
| if (!Array.isArray(raw) || raw.length === 0) return null; | |
| return raw.slice(-50); | |
| } | |
| /** Index of the LAST user message in the sliced window (-1 when none). */ | |
| function lastUserMessageIndex(sliced: unknown[]): number { | |
| for (let i = sliced.length - 1; i >= 0; i--) { | |
| const m = sliced[i] as { role?: unknown } | null; | |
| if (m?.role === "user") return i; | |
| } | |
| return -1; | |
| } | |
| /** Classify one raw content part into its text/image contribution | |
| * (null = ignore: not an object, or not a text/image_url part). */ | |
| function partContribution(part: unknown): { text?: string; url?: string; screenTagged?: boolean } | null { | |
| if (!part || typeof part !== "object") return null; | |
| const p = part as { type?: unknown; text?: unknown; image_url?: { url?: unknown }; source?: unknown }; | |
| if (p.type === "text" && typeof p.text === "string") return { text: stripChatControlChars(p.text) }; | |
| if (p.type === "image_url" && typeof p.image_url?.url === "string") { | |
| return { url: p.image_url.url, screenTagged: p.source === "screen_capture" }; | |
| } | |
| return null; | |
| } | |
| /** Split a parts-array content into text parts and image URLs. */ | |
| function parseContentParts(content: unknown[]): { textParts: string[]; imageUrls: string[]; lastImageScreenTagged: boolean } { | |
| const textParts: string[] = []; | |
| const imageUrls: string[] = []; | |
| let lastImageScreenTagged = false; | |
| for (const part of content) { | |
| const contribution = partContribution(part); | |
| if (!contribution) continue; | |
| if (contribution.text !== undefined) textParts.push(contribution.text); | |
| if (contribution.url !== undefined) { | |
| imageUrls.push(contribution.url); | |
| // The client tags LIVE screen frames with `source: "screen_capture"`. | |
| // Unknown/absent tags are simply ignored — the flag is honored only | |
| // for the last user message below (never for flattened history). | |
| if (contribution.screenTagged) lastImageScreenTagged = true; | |
| } | |
| } | |
| return { textParts, imageUrls, lastImageScreenTagged }; | |
| } | |
| /** Parse one raw message: role + content split into text/image parts. | |
| * Returns null only for non-object entries (the caller skips them). */ | |
| function parseMessageContent(m: { role?: unknown; content?: unknown } | null): ParsedMessage | null { | |
| if (!m || typeof m !== "object") return null; | |
| const role = m.role === "assistant" ? "assistant" : "user"; | |
| const content = m.content; | |
| if (typeof content === "string") { | |
| return { role, textParts: [stripChatControlChars(content)], imageUrls: [], lastImageScreenTagged: false }; | |
| } | |
| if (!Array.isArray(content)) { | |
| return { role, textParts: [], imageUrls: [], lastImageScreenTagged: false }; | |
| } | |
| return { role, ...parseContentParts(content) }; | |
| } | |
| /** Failure to abort with when the last user message's images break a cap. */ | |
| function imageBatchFailure(imageUrls: string[]): NormalizeFailure | null { | |
| if (imageUrls.length > MAX_IMAGES_PER_REQUEST) { | |
| return { | |
| status: 400, | |
| code: "BAD_INPUT", | |
| en: `Too many images — max ${MAX_IMAGES_PER_REQUEST} per message`, | |
| ar: `صور كثيرة — الحد الأقصى ${MAX_IMAGES_PER_REQUEST} صورة لكل رسالة`, | |
| }; | |
| } | |
| for (const url of imageUrls) { | |
| if (!IMAGE_DATAURL_RE.test(url) || url.length > MAX_IMAGE_PART_BASE64) { | |
| return { | |
| status: 413, | |
| code: "TOO_LARGE", | |
| en: "Attached image is too large or in an unsupported format — try a smaller image", | |
| ar: "الصورة المرفقة كبيرة جداً أو بصيغة غير مدعومة — جرب صورة أصغر", | |
| }; | |
| } | |
| } | |
| return null; | |
| } | |
| /** Last user message with images → multimodal content parts. */ | |
| function buildImageMessageContent(textParts: string[], imageUrls: string[]): ContentPart[] { | |
| const text = textParts.join(" ").slice(0, MAX_MESSAGE_CHARS); | |
| return [ | |
| ...(text ? [{ type: "text" as const, text }] : []), | |
| ...imageUrls.map((url) => ({ type: "image_url" as const, image_url: { url } })), | |
| ]; | |
| } | |
| /** History (or stray) image message — flatten to plain text. */ | |
| function flattenImageMessage(textParts: string[], imageUrls: string[]): string { | |
| const text = textParts.join(" ").slice(0, MAX_MESSAGE_CHARS); | |
| const separator = text ? " " : ""; | |
| const note = imageUrls.length > 0 ? `${separator}[صورة مرفقة]` : ""; | |
| return text + note; | |
| } | |
| /** Validate the last user message's images and build its multimodal content. | |
| * `failure` aborts the request; otherwise `content` is pushed and the caller | |
| * adopts `screenCapture` (imageCount === parsed.imageUrls.length). */ | |
| function resolveLastUserImageContent( | |
| parsed: ParsedMessage, | |
| ): { failure: NormalizeFailure; content?: undefined; screenCapture?: undefined } | { failure: null; content: ContentPart[]; screenCapture: boolean } { | |
| const failure = imageBatchFailure(parsed.imageUrls); | |
| if (failure) return { failure }; | |
| return { | |
| failure: null, | |
| content: buildImageMessageContent(parsed.textParts, parsed.imageUrls), | |
| screenCapture: parsed.lastImageScreenTagged, | |
| }; | |
| } | |
| /** TRUE when a request has NO images and every message is blank text — | |
| * the wasted-provider-call guard (image-only questions stay valid). */ | |
| function conversationIsBlank(imageCount: number, messages: ChatApiMessage[]): boolean { | |
| if (imageCount !== 0) return false; | |
| return messages.every((m) => { | |
| const t = typeof m.content === "string" ? m.content : ""; | |
| return t.trim().length === 0; | |
| }); | |
| } | |
| /** Text length of one normalized message (string content, or the text parts | |
| * of the multimodal last user message). */ | |
| function messageTextChars(m: ChatApiMessage): number { | |
| if (typeof m.content === "string") return m.content.length; | |
| if (Array.isArray(m.content)) { | |
| return m.content.reduce((s, p) => s + partTextChars(p), 0); | |
| } | |
| return 0; | |
| } | |
| function partTextChars(p: unknown): number { | |
| return p && typeof p === "object" && typeof (p as { text?: unknown }).text === "string" | |
| ? ((p as { text: string }).text.length) | |
| : 0; | |
| } | |
| function countMessageTextChars(messages: ChatApiMessage[]): number { | |
| return messages.reduce((sum, m) => sum + messageTextChars(m), 0); | |
| } | |
| /** S3776 helper: absorb every parsed message, keeping images on the last | |
| * user turn only. Returns the collected state or the failure to surface. */ | |
| function collectNormalizedMessages( | |
| sliced: unknown[], | |
| lastUserIdx: number, | |
| ): { ok: true; messages: ChatApiMessage[]; imageCount: number; screenCapture: boolean } | { ok: false; failure: NormalizeFailure } { | |
| const messages: ChatApiMessage[] = []; | |
| let imageCount = 0; | |
| let screenCapture = false; | |
| for (let i = 0; i < sliced.length; i++) { | |
| const parsed = parseMessageContent(sliced[i] as { role?: unknown; content?: unknown } | null); | |
| if (!parsed) continue; | |
| const keepImages = i === lastUserIdx && parsed.imageUrls.length > 0; | |
| if (keepImages) { | |
| const resolved = resolveLastUserImageContent(parsed); | |
| if (resolved.failure) return { ok: false, failure: resolved.failure }; | |
| imageCount = parsed.imageUrls.length; | |
| if (resolved.screenCapture) screenCapture = true; | |
| messages.push({ role: parsed.role, content: resolved.content }); | |
| } else { | |
| messages.push({ role: parsed.role, content: flattenImageMessage(parsed.textParts, parsed.imageUrls) }); | |
| } | |
| } | |
| return { ok: true, messages, imageCount, screenCapture }; | |
| } | |
| export function normalizeChatInput(raw: unknown): { ok: true; data: NormalizedChatInput } | { ok: false; failure: NormalizeFailure } { | |
| const sliced = sliceRawMessages(raw); | |
| if (!sliced) { | |
| return { ok: false, failure: { status: 400, code: "BAD_REQUEST", en: "Messages array is required", ar: "Messages array is required" } }; | |
| } | |
| // Locate the last user message — the only one allowed to carry images. | |
| const lastUserIdx = lastUserMessageIndex(sliced); | |
| const collected = collectNormalizedMessages(sliced, lastUserIdx); | |
| if (!collected.ok) return collected; | |
| const { messages, imageCount, screenCapture } = collected; | |
| if (messages.length === 0) { | |
| return { ok: false, failure: { status: 400, code: "BAD_REQUEST", en: "Messages array is required", ar: "Messages array is required" } }; | |
| } | |
| // ✅ TOKEN OPTIMIZATION (v3.6.0): clip OLD turns before the blank check — | |
| // clipping never changes emptiness (empty clip = empty) so the ROOT-CURE | |
| // blank-conversation guard below keeps its exact semantics. | |
| const trimmedMessages = trimHistoryForContext(messages); | |
| // ✅ ROOT-CURE (2026-11-13, blank conversation burned a provider call): a | |
| // request whose every message is empty text (and no images) used to pass | |
| // normalization and DISPATCH a real provider call with nothing to answer — | |
| // a wasted call + a confusing 503 for a client bug. The direct-API caller | |
| // now gets the clean 400 it always deserved. (A blank message WITH an | |
| // attached image stays valid — image-only questions are a product flow.) | |
| if (conversationIsBlank(imageCount, messages)) { | |
| return { | |
| ok: false, | |
| failure: { | |
| status: 400, | |
| code: "BAD_REQUEST", | |
| en: "Message text is empty — write your question and send it again", | |
| ar: "نص الرسالة فارغ — اكتب سؤالك وأعد الإرسال", | |
| }, | |
| }; | |
| } | |
| return { ok: true, data: { messages: trimmedMessages, vision: imageCount > 0, imageCount, totalTextChars: countMessageTextChars(trimmedMessages), screenCapture } }; | |
| } | |