@12-apps/messaging 1.3.0 → 1.5.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/whatsapp/opt-out.ts","../src/whatsapp/parse.ts","../src/whatsapp/graph.ts","../src/whatsapp/media.ts","../src/whatsapp/signature.ts","../src/whatsapp/signup.ts","../src/whatsapp/index.ts"],"sourcesContent":["/**\n * The words that opt a contact out, by default: the Portuguese and English\n * stop words a WhatsApp user is told to send. A host replaces the list through\n * the adapter's config.\n */\nexport const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = [\"PARAR\", \"SAIR\", \"STOP\", \"CANCELAR\"];\n\n/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */\nfunction fold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n .toUpperCase();\n}\n\n/**\n * Is this text an opt-out? Only when the WHOLE message is one keyword —\n * case- and accent-insensitive, ignoring punctuation and emoji around it — so\n * \"parar\", \"PARAR.\" and \"Parar!\" opt out, and \"parar de enviar\" (a sentence,\n * maybe about something else) does not.\n */\nexport function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {\n const folded = fold(text);\n return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);\n}\n","import type {\n InboundContent,\n InboundMessageEvent,\n NormalizedEvent,\n OptOutEvent,\n ReceiptStatus,\n StatusEvent,\n} from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\n\n/**\n * The WhatsApp Cloud API webhook payload, read defensively: every field is\n * checked before it is trusted, an unknown shape is skipped rather than\n * thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).\n *\n * Shape: `{ object: \"whatsapp_business_account\", entry: [{ id, changes: [{\n * field, value: { metadata: { phone_number_id }, contacts, messages,\n * statuses, user_preferences } }] }] }`. Events come out in payload order.\n */\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */\nfunction when(value: unknown): Date | null {\n const seconds = typeof value === \"string\" || typeof value === \"number\" ? Number(value) : Number.NaN;\n return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;\n}\n\ninterface Change {\n value: Json;\n accountId: string;\n}\n\n/** Every `value` of every change, with the account it was delivered to. */\nfunction changes(payload: unknown): Change[] {\n if (!isObject(payload) || payload.object !== \"whatsapp_business_account\") return [];\n return list(payload.entry)\n .flatMap((entry) => list(entry.changes))\n .flatMap((change): Change[] => {\n const value = change.value;\n const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;\n return isObject(value) && accountId ? [{ value, accountId }] : [];\n });\n}\n\n/** One reader per message `type`; null when the type's object is missing or malformed. */\nconst CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {\n text: (message) => {\n const body = isObject(message.text) ? text(message.text.body) : null;\n return body ? { kind: \"TEXT\", text: body } : null;\n },\n interactive: (message) => {\n const interactive = isObject(message.interactive) ? message.interactive : {};\n const reply = interactive.button_reply ?? interactive.list_reply;\n const id = isObject(reply) ? text(reply.id) : null;\n return isObject(reply) && id ? { kind: \"INTERACTIVE\", replyId: id, title: text(reply.title) ?? \"\" } : null;\n },\n // A quick-reply button on a template message.\n button: (message) => {\n if (!isObject(message.button)) return null;\n const title = text(message.button.text) ?? \"\";\n return { kind: \"INTERACTIVE\", replyId: text(message.button.payload) ?? title, title };\n },\n audio: (message) => {\n const id = isObject(message.audio) ? text(message.audio.id) : null;\n return isObject(message.audio) && id ? { kind: \"AUDIO\", mediaId: id, mimeType: text(message.audio.mime_type) } : null;\n },\n};\n\n/** The content of one message, by its `type`; anything unread is OTHER. */\nfunction contentOf(message: Json): InboundContent {\n const type = text(message.type) ?? \"unknown\";\n return CONTENT_READERS[type]?.(message) ?? { kind: \"OTHER\", channelType: type };\n}\n\n/** The words a person typed or tapped, for the opt-out check. */\nfunction wordsOf(content: InboundContent): string | null {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"INTERACTIVE\") return content.title;\n return null;\n}\n\n/** The profile name Meta sends per sender, keyed by wa_id. */\nfunction contactNames(value: Json): Map<string, string> {\n const names = new Map<string, string>();\n for (const contact of list(value.contacts)) {\n const waId = text(contact.wa_id);\n const name = isObject(contact.profile) ? text(contact.profile.name) : null;\n if (waId && name) names.set(waId, name);\n }\n return names;\n}\n\nfunction messageEvent(\n message: Json,\n accountId: string,\n names: Map<string, string>,\n keywords: readonly string[],\n): InboundMessageEvent | null {\n const contactId = text(message.from);\n const externalId = text(message.id);\n const sentAt = when(message.timestamp);\n if (!contactId || !externalId || !sentAt) return null;\n const content = contentOf(message);\n const words = wordsOf(content);\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: names.get(contactId) ?? null,\n externalId,\n sentAt,\n content,\n optOut: words !== null && isOptOutText(words, keywords),\n };\n}\n\nfunction messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {\n const names = contactNames(value);\n return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);\n}\n\nconst RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {\n sent: \"SENT\",\n delivered: \"DELIVERED\",\n read: \"READ\",\n failed: \"FAILED\",\n};\n\n/** The first error of a failed status, as `code: title`. */\nfunction errorOf(status: Json): string | null {\n const [first] = list(status.errors);\n if (!first) return null;\n const code = first.code === undefined ? \"\" : String(first.code);\n const title = text(first.title) ?? text(first.message) ?? \"\";\n return [code, title].filter(Boolean).join(\": \") || null;\n}\n\nfunction statusEvents(value: Json, accountId: string): StatusEvent[] {\n const out: StatusEvent[] = [];\n for (const status of list(value.statuses)) {\n const externalId = text(status.id);\n const receipt = RECEIPTS[text(status.status) ?? \"\"];\n const at = when(status.timestamp);\n if (!externalId || !receipt || !at) continue;\n out.push({\n type: \"status\",\n accountId,\n externalId,\n status: receipt,\n at,\n contactId: text(status.recipient_id),\n error: receipt === \"FAILED\" ? errorOf(status) : null,\n callbackData: text(status.biz_opaque_callback_data),\n });\n }\n return out;\n}\n\n/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */\nfunction preferenceEvents(value: Json, accountId: string): OptOutEvent[] {\n const out: OptOutEvent[] = [];\n for (const preference of list(value.user_preferences)) {\n const contactId = text(preference.wa_id);\n const at = when(preference.timestamp);\n if (contactId && at && text(preference.value)?.toLowerCase() === \"stop\") {\n out.push({ type: \"opt_out\", accountId, contactId, at });\n }\n }\n return out;\n}\n\n/**\n * Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound\n * messages (with the opt-out keyword check), delivery receipts, and Meta's\n * own opt-out signal.\n */\nexport function parseWhatsAppPayload(\n payload: unknown,\n options: { optOutKeywords?: readonly string[] } = {},\n): NormalizedEvent[] {\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n const out: NormalizedEvent[] = [];\n for (const { value, accountId } of changes(payload)) {\n out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));\n }\n return out;\n}\n\n/**\n * Only the delivery receipts of a WhatsApp webhook payload — for a host that\n * tracks receipts of messages it sends some other way (a platform\n * notification number) without mounting the connector.\n */\nexport function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {\n return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));\n}\n","import { ChannelSendFailure } from \"../core/channel\";\nimport type { OutboundContent } from \"../core/types\";\n\n/**\n * The only way the adapter reaches Meta: an injected fetch. The global\n * `fetch` satisfies it; a test answers it with a recording fake.\n *\n * A JSON call reads `text()` only. A media download also asks for\n * `redirect: \"manual\"` (a 3xx comes back as itself, never followed) and reads\n * the binary body through `body` (a stream, read up to the size cap) or, when\n * there is none, `arrayBuffer()`. All three are optional so a text-only fake\n * still satisfies the port.\n */\nexport type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;\n\nexport interface FetchInit {\n method: string;\n headers: Record<string, string>;\n body?: string;\n /** `manual` for a media download: a redirect is answered, never followed. */\n redirect?: \"manual\" | \"follow\" | \"error\";\n /** Aborts the call at a media download's deadline. */\n signal?: AbortSignal;\n}\n\nexport interface FetchResponse {\n status: number;\n text(): Promise<string>;\n arrayBuffer?(): Promise<ArrayBuffer>;\n /** The body as a stream; read chunk by chunk so an oversized one is cut off early. */\n body?: { getReader(): FetchBodyReader; cancel?(reason?: unknown): Promise<void> } | null;\n headers?: { get(name: string): string | null };\n}\n\nexport interface FetchBodyReader {\n read(): Promise<{ done: boolean; value?: Uint8Array }>;\n cancel(reason?: unknown): Promise<void>;\n}\n\n/**\n * The hosts Meta serves WhatsApp media from: the URL a media lookup returns is\n * `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the\n * CDN families behind it. `*.` matches any subdomain (not the bare domain).\n */\nexport const DEFAULT_META_MEDIA_HOSTS: readonly string[] = [\"lookaside.fbsbx.com\", \"*.fbcdn.net\", \"*.whatsapp.net\"];\n\n/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */\nexport interface GraphConfig {\n fetch: FetchPort;\n /** `https://graph.facebook.com` — no trailing slash needed. */\n baseUrl: string;\n /** `v23.0` — the Graph API version every call is pinned to. */\n apiVersion: string;\n /**\n * The hosts a media URL may point at; any other is refused before the token\n * is sent to it. Exact names, or `*.domain` for its subdomains. Default\n * {@link DEFAULT_META_MEDIA_HOSTS}.\n */\n mediaHosts?: readonly string[];\n}\n\n/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */\nexport class GraphError extends ChannelSendFailure {\n readonly status: number;\n constructor(status: number, code: string, message: string) {\n super(code, message);\n this.name = \"GraphError\";\n this.status = status;\n }\n}\n\ntype Json = Record<string, unknown>;\n\ninterface GraphCall {\n method: \"GET\" | \"POST\";\n path: string;\n token?: string;\n query?: Record<string, string>;\n body?: unknown;\n redirect?: FetchInit[\"redirect\"];\n signal?: AbortSignal;\n}\n\n/** Drops trailing \"/\" characters in one linear pass (a regex here backtracks quadratically on library input). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return end === value.length ? value : value.slice(0, end);\n}\n\n/** The URL and the request init of one call. The token travels in a header, never in the URL. */\nfunction requestOf(graph: GraphConfig, call: GraphCall) {\n const base = trimTrailingSlashes(graph.baseUrl);\n const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (call.token) headers.authorization = `Bearer ${call.token}`;\n if (call.body !== undefined) headers[\"content-type\"] = \"application/json\";\n return {\n url: `${base}/${graph.apiVersion}/${call.path}${query}`,\n init: {\n method: call.method,\n headers,\n ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),\n ...(call.redirect ? { redirect: call.redirect } : {}),\n ...(call.signal ? { signal: call.signal } : {}),\n } satisfies FetchInit,\n };\n}\n\n/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */\nfunction objectOf(raw: string): Json {\n try {\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};\n } catch {\n return {};\n }\n}\n\n/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */\nfunction graphErrorOf(status: number, json: Json): GraphError {\n const error = typeof json.error === \"object\" && json.error !== null ? (json.error as Json) : {};\n const code = error.code === undefined ? `HTTP_${status}` : String(error.code);\n const message = typeof error.message === \"string\" ? error.message : `Graph answered ${status}`;\n return new GraphError(status, code, message.slice(0, 300));\n}\n\n/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */\nexport async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {\n const { url, init } = requestOf(graph, call);\n const response = await graph.fetch(url, init);\n const json = objectOf(await response.text());\n if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);\n return json;\n}\n\n/** The Cloud API body for one outbound message. */\nexport function messageBody(to: string, content: OutboundContent): Json {\n const base = { messaging_product: \"whatsapp\", recipient_type: \"individual\", to };\n if (content.kind === \"TEXT\") return { ...base, type: \"text\", text: { body: content.text, preview_url: false } };\n if (content.kind === \"BUTTONS\") {\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"button\",\n body: { text: content.text },\n action: { buttons: content.buttons.map((button) => ({ type: \"reply\", reply: { id: button.id, title: button.title } })) },\n },\n };\n }\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"list\",\n body: { text: content.text },\n action: {\n button: content.buttonLabel,\n sections: content.sections.map((section) => ({\n ...(section.title ? { title: section.title } : {}),\n rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),\n })),\n },\n },\n };\n}\n\n/** Send one message from a phone number; resolves to its wamid. */\nexport async function sendWhatsAppMessage(\n graph: GraphConfig,\n input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },\n): Promise<{ externalId: string }> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.phoneNumberId)}/messages`,\n token: input.token,\n body: messageBody(input.to, input.content),\n });\n const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];\n const id = first && typeof first.id === \"string\" ? first.id : null;\n if (!id) throw new GraphError(200, \"NO_MESSAGE_ID\", \"Graph accepted the message but returned no id\");\n return { externalId: id };\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, isPositiveSafeInteger, type ChannelMedia } from \"../core/channel\";\nimport { DEFAULT_META_MEDIA_HOSTS, graphRequest, type FetchResponse, type GraphConfig } from \"./graph\";\n\n/**\n * A WhatsApp media download, the Cloud API way: `GET /{version}/{media-id}`\n * with the business token answers `{ url, mime_type, file_size }`, and a\n * `GET` of that URL with the same token answers the bytes.\n *\n * The token travels in the Authorization header only, and only to a Meta\n * media host over https: the URL comes from Meta, but it is still checked\n * against the configured hosts before the token is sent to it, and a redirect\n * is refused rather than followed to wherever it points. The size is capped\n * twice — the declared `file_size` before the download, the bytes actually\n * read during it — the whole download has a deadline, and the media lives\n * only in the returned memory.\n */\n\nconst OCTET_STREAM = \"application/octet-stream\";\n\n/** Does `host` match one allowlist entry: an exact name, or `*.domain` for its subdomains. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n // \"*.fbcdn.net\" matches \"x.fbcdn.net\" through its \".fbcdn.net\" suffix, never \"fbcdn.net\" or \"evilfbcdn.net\".\n return pattern.startsWith(\"*.\") ? host.endsWith(pattern.slice(1)) : host === pattern;\n });\n}\n\n/** The media URL Meta returned, checked: https, no userinfo, an allowed host. */\nfunction checkedMediaUrl(raw: unknown, allowed: readonly string[]): string {\n if (typeof raw !== \"string\" || raw === \"\") throw new ChannelMediaFailure(\"NO_MEDIA_URL\", \"Graph returned no media url\");\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new ChannelMediaFailure(\"MEDIA_URL_INVALID\", \"Graph returned a media url that does not parse\");\n }\n if (url.protocol !== \"https:\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url is not https\");\n if (url.username || url.password) throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url carries credentials\");\n if (url.port !== \"\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url names an explicit port\");\n if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {\n throw new ChannelMediaFailure(\"MEDIA_HOST_REFUSED\", `the media host ${url.hostname} is not a Meta media host`);\n }\n return url.toString();\n}\n\nconst tooLarge = (size: number, maxBytes: number) =>\n new ChannelMediaFailure(\"TOO_LARGE\", `the media is ${size} bytes, over the ${maxBytes}-byte cap`);\n\n/** A declared size over the cap refuses the download before it starts. */\nfunction checkDeclaredSize(declared: unknown, maxBytes: number): void {\n const size = typeof declared === \"number\" ? declared : typeof declared === \"string\" ? Number(declared) : NaN;\n if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);\n}\n\n/** Concatenate the chunks read so far. */\nfunction joined(chunks: Uint8Array[], total: number): Uint8Array {\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/** The download's deadline: one abort signal for both calls, and a race for every read. */\ninterface Deadline {\n signal: AbortSignal;\n /** `promise`, or a `TIMEOUT` failure once the deadline passes — whichever comes first. */\n race<T>(promise: Promise<T>): Promise<T>;\n clear(): void;\n}\n\nconst timedOut = (timeoutMs: number) =>\n new ChannelMediaFailure(\"TIMEOUT\", `the media download did not finish within ${timeoutMs} ms`);\n\nfunction deadlineOf(timeoutMs: number): Deadline {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(timedOut(timeoutMs));\n }, timeoutMs);\n });\n // The race below observes it; this only keeps an unobserved expiry from being reported unhandled.\n expired.catch(() => undefined);\n return {\n signal: controller.signal,\n race: async (promise) => {\n try {\n return await Promise.race([promise, expired]);\n } catch (error) {\n // A port that honours the signal rejects with its own abort error: it is the deadline all the same.\n throw controller.signal.aborted ? timedOut(timeoutMs) : error;\n }\n },\n clear: () => clearTimeout(timer),\n };\n}\n\n/** Release a body that will not be read; never throws. */\nfunction discardBody(response: FetchResponse): void {\n try {\n void Promise.resolve(response.body?.cancel?.()).catch(() => undefined);\n } catch {\n // A body that cannot even be cancelled is left to the garbage collector.\n }\n}\n\n/** Read a stream, cancelling it the moment it passes the cap or the deadline. */\nasync function readStreamCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const reader = response.body!.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await deadline.race(reader.read());\n if (done) break;\n if (!value) continue;\n total += value.length;\n if (total > maxBytes) throw tooLarge(total, maxBytes);\n chunks.push(value);\n }\n } catch (error) {\n void reader.cancel().catch(() => undefined);\n throw error;\n }\n return joined(chunks, total);\n}\n\n/** The body's bytes, never more than `maxBytes` of them — whatever the headers declared. */\nasync function readBodyCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const declared = response.headers?.get(\"content-length\");\n if (declared) {\n try {\n checkDeclaredSize(declared, maxBytes);\n } catch (error) {\n discardBody(response);\n throw error;\n }\n }\n if (response.body && typeof response.body.getReader === \"function\") return readStreamCapped(response, maxBytes, deadline);\n if (!response.arrayBuffer) throw new ChannelMediaFailure(\"NO_BINARY_BODY\", \"the fetch port cannot read a binary body\");\n // Only for a port with no stream: it reads the WHOLE body before the cap can be checked.\n const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));\n if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);\n return bytes;\n}\n\n/** GET the media URL with the token in a header; a redirect or a non-2xx is refused, its body discarded. */\nasync function downloadFrom(graph: GraphConfig, url: string, token: string, deadline: Deadline): Promise<FetchResponse> {\n const response = await deadline.race(\n graph.fetch(url, {\n method: \"GET\",\n headers: { authorization: `Bearer ${token}`, accept: \"*/*\" },\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n if (response.status >= 200 && response.status < 300) return response;\n discardBody(response);\n if (response.status >= 300 && response.status < 400) {\n throw new ChannelMediaFailure(\"REDIRECT_REFUSED\", `the media download answered ${response.status}; redirects are not followed`);\n }\n throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);\n}\n\n/** A cap or deadline that would not bound anything (NaN, Infinity, 0, negative, fractional) is refused. */\nfunction checkLimits(maxBytes: number, timeoutMs: number): void {\n if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {\n throw new ChannelMediaFailure(\"BAD_OPTIONS\", \"maxBytes and timeoutMs must be positive safe integers\");\n }\n}\n\n/** Download one WhatsApp media object into memory. */\nexport async function downloadWhatsAppMedia(\n graph: GraphConfig,\n input: { token: string; mediaId: string; maxBytes: number; timeoutMs?: number },\n): Promise<ChannelMedia> {\n const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;\n checkLimits(input.maxBytes, timeoutMs);\n const deadline = deadlineOf(timeoutMs);\n try {\n const meta = await deadline.race(\n graphRequest(graph, {\n method: \"GET\",\n path: encodeURIComponent(input.mediaId),\n token: input.token,\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);\n checkDeclaredSize(meta.file_size, input.maxBytes);\n const response = await downloadFrom(graph, url, input.token, deadline);\n const bytes = await readBodyCapped(response, input.maxBytes, deadline);\n const declaredType = typeof meta.mime_type === \"string\" && meta.mime_type ? meta.mime_type : null;\n const mimeType = declaredType ?? response.headers?.get(\"content-type\") ?? OCTET_STREAM;\n return { bytes, mimeType, size: bytes.length };\n } finally {\n deadline.clear();\n }\n}\n","import { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Meta's webhook proofs, as standalone functions: the connector's WhatsApp\n * adapter uses them, and so can any other WhatsApp webhook a host runs (a\n * platform notification number's receipts), without mounting the connector.\n */\n\n/** The header Meta signs every webhook POST with. */\nexport const META_SIGNATURE_HEADER = \"x-hub-signature-256\";\n\nconst SIGNATURE = /^sha256=([0-9a-f]{64})$/i;\n\n/**\n * Does `signatureHeader` prove `rawBody` was signed with `appSecret`?\n *\n * HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized\n * JSON body never matches; hand the bytes, not a decoded string, where the\n * framework gives them), compared in constant time. Fails CLOSED: an empty\n * secret, a missing header, a header in any other shape, or a digest of the\n * wrong length is `false` — never an exception, never `true`.\n */\nexport function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {\n if (!appSecret || !signatureHeader) return false;\n const match = SIGNATURE.exec(signatureHeader.trim());\n if (!match) return false;\n const expected = createHmac(\"sha256\", appSecret).update(rawBody).digest();\n const given = Buffer.from(match[1]!, \"hex\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n\n/** What the subscription handshake answers. */\nexport type MetaHandshake = { ok: true; challenge: string } | { ok: false };\n\n/**\n * Meta's `GET` subscription handshake: `hub.mode=subscribe`, the\n * `hub.verify_token` configured on the app, and a `hub.challenge` to echo.\n * The token is compared in constant time; an empty configured token refuses\n * every handshake.\n */\nexport function verifyMetaSubscription(\n query: Readonly<Record<string, string | undefined>>,\n verifyToken: string,\n): MetaHandshake {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (!verifyToken || mode !== \"subscribe\" || !token || !challenge) return { ok: false };\n // Digests of equal length, so the comparison leaks neither content nor length.\n const digest = (value: string) => createHash(\"sha256\").update(value, \"utf8\").digest();\n return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };\n}\n","import { GraphError, graphRequest, type GraphConfig } from \"./graph\";\n\n/**\n * Embedded Signup, server half. The browser half (Meta's SDK popup) hands the\n * host a short-lived `code`; these three calls turn it into a connection:\n *\n * 1. {@link exchangeSignupCode} — the code for a business token;\n * 2. {@link readSignupAccounts} — which WhatsApp Business Accounts the token\n * was granted, and each one's phone numbers (id + display number);\n * 3. {@link subscribeAppToWaba} — subscribe the app to the chosen account's\n * webhooks, so its messages reach the connector.\n *\n * Then the host calls `engine.connect(...)` with the phone number id, the\n * display number and the token, which the engine seals. None of these\n * functions logs or returns anything but what is named.\n */\n\ntype Json = Record<string, unknown>;\n\n/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */\nexport interface MetaAppCredentials {\n appId: string;\n appSecret: string;\n}\n\n/** Exchange Embedded Signup's code for a business integration token. */\nexport async function exchangeSignupCode(\n graph: GraphConfig,\n input: MetaAppCredentials & { code: string; redirectUri?: string },\n): Promise<{ accessToken: string }> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: \"oauth/access_token\",\n query: {\n client_id: input.appId,\n client_secret: input.appSecret,\n code: input.code,\n ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),\n },\n });\n if (typeof json.access_token !== \"string\" || json.access_token.length === 0) {\n throw new GraphError(200, \"NO_ACCESS_TOKEN\", \"Graph answered the code exchange without a token\");\n }\n return { accessToken: json.access_token };\n}\n\n/** One phone number of a WhatsApp Business Account. */\nexport interface SignupPhoneNumber {\n /** The phone_number_id: the connection's external account id. */\n id: string;\n /** What a person reads (`+55 11 98765-4321`): the connection's display address. */\n displayPhoneNumber: string;\n verifiedName: string | null;\n}\n\nexport interface SignupAccount {\n /** The WABA id: the connection's external parent id. */\n wabaId: string;\n phoneNumbers: SignupPhoneNumber[];\n}\n\n/**\n * The WhatsApp Business Accounts the token was granted (read from the token's\n * own granular scopes, with the app's token), and each one's phone numbers.\n */\nexport async function readSignupAccounts(\n graph: GraphConfig,\n input: MetaAppCredentials & { accessToken: string },\n): Promise<SignupAccount[]> {\n const debug = await graphRequest(graph, {\n method: \"GET\",\n path: \"debug_token\",\n query: { input_token: input.accessToken },\n token: `${input.appId}|${input.appSecret}`,\n });\n const data = typeof debug.data === \"object\" && debug.data !== null ? (debug.data as Json) : {};\n const scopes = Array.isArray(data.granular_scopes) ? (data.granular_scopes as Json[]) : [];\n const wabaIds = new Set(\n scopes\n .filter((scope) => scope.scope === \"whatsapp_business_management\" && Array.isArray(scope.target_ids))\n .flatMap((scope) => (scope.target_ids as unknown[]).filter((id): id is string => typeof id === \"string\")),\n );\n const accounts: SignupAccount[] = [];\n for (const wabaId of wabaIds) {\n accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });\n }\n return accounts;\n}\n\nasync function readPhoneNumbers(graph: GraphConfig, wabaId: string, accessToken: string): Promise<SignupPhoneNumber[]> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: `${encodeURIComponent(wabaId)}/phone_numbers`,\n query: { fields: \"id,display_phone_number,verified_name\" },\n token: accessToken,\n });\n const rows = Array.isArray(json.data) ? (json.data as Json[]) : [];\n return rows\n .filter((row) => typeof row.id === \"string\" && typeof row.display_phone_number === \"string\")\n .map((row) => ({\n id: row.id as string,\n displayPhoneNumber: row.display_phone_number as string,\n verifiedName: typeof row.verified_name === \"string\" ? row.verified_name : null,\n }));\n}\n\n/** Subscribe the app to a WABA's webhooks. Resolves when Meta answers `success: true`. */\nexport async function subscribeAppToWaba(graph: GraphConfig, input: { wabaId: string; accessToken: string }): Promise<void> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,\n token: input.accessToken,\n });\n if (json.success !== true) throw new GraphError(200, \"NOT_SUBSCRIBED\", \"Graph did not confirm the subscription\");\n}\n","/**\n * `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.\n *\n * `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces\n * are exported on their own too: the signature check and the receipt parser\n * serve any WhatsApp webhook (a platform notification number), and the\n * Embedded Signup helpers serve the host's connect flow.\n *\n * `@12-apps/notifications` has its own WhatsApp transport, for one-way\n * notification messages. It is deliberately NOT reused here: this adapter\n * carries a conversation (inbound, the service window, opt-out, receipts),\n * which that transport has no model for.\n */\n\nimport { serviceWindowPolicy, type ChannelAdapter } from \"../core/channel\";\nimport { parseWhatsAppPayload } from \"./parse\";\nimport { sendWhatsAppMessage, type GraphConfig } from \"./graph\";\nimport { downloadWhatsAppMedia } from \"./media\";\nimport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from \"./signature\";\n\n/** The channel key every WhatsApp row carries. */\nexport const WHATSAPP_CHANNEL = \"whatsapp\";\n\n/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */\nexport const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;\n\nexport interface WhatsAppAdapterConfig {\n /** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */\n appSecret: string;\n /** The token configured on the app's webhook subscription. Empty refuses every handshake. */\n verifyToken: string;\n /** The Graph API: fetch, base URL and version. */\n graph: GraphConfig;\n /** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */\n optOutKeywords?: readonly string[];\n}\n\n/** The WhatsApp Cloud adapter. */\nexport function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {\n return {\n kind: WHATSAPP_CHANNEL,\n handshake: (query) => verifyMetaSubscription(query, config.verifyToken),\n verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),\n parse: (rawBody) =>\n parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {\n ...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),\n }),\n send: ({ credential, accountId, to, content }) =>\n sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),\n fetchMedia: ({ credential, mediaId, maxBytes, timeoutMs }) =>\n downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }),\n policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),\n };\n}\n\nexport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from \"./signature\";\nexport { parseWhatsAppPayload, parseWhatsAppStatuses } from \"./parse\";\nexport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\nexport {\n DEFAULT_META_MEDIA_HOSTS,\n GraphError,\n graphRequest,\n messageBody,\n sendWhatsAppMessage,\n type FetchBodyReader,\n type FetchInit,\n type FetchPort,\n type FetchResponse,\n type GraphConfig,\n} from \"./graph\";\nexport { downloadWhatsAppMedia } from \"./media\";\nexport {\n exchangeSignupCode,\n readSignupAccounts,\n subscribeAppToWaba,\n type MetaAppCredentials,\n type SignupAccount,\n type SignupPhoneNumber,\n} from \"./signup\";\n"],"mappings":";;;;;;;;;;;;AAKO,IAAM,2BAA8C,CAAC,SAAS,QAAQ,QAAQ,UAAU;AAG/F,SAAS,KAAKA,OAAsB;AAClC,SAAOA,MACJ,UAAU,KAAK,EACf,QAAQ,WAAW,EAAE,EACrB,QAAQ,qCAAqC,EAAE,EAC/C,YAAY;AACjB;AANS;AAcF,SAAS,aAAaA,OAAc,WAA8B,0BAAmC;AAC1G,QAAM,SAAS,KAAKA,KAAI;AACxB,SAAO,OAAO,SAAS,KAAK,SAAS,KAAK,CAAC,YAAY,KAAK,OAAO,MAAM,MAAM;AACjF;AAHgB;;;ACAhB,IAAM,WAAW,wBAAC,UAAkC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,GAAtG;AACjB,IAAM,OAAO,wBAAC,UAA4B,MAAM,QAAQ,KAAK,IAAI,MAAM,OAAO,QAAQ,IAAI,CAAC,GAA9E;AACb,IAAM,OAAO,wBAAC,UAAmC,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,MAA5F;AAGb,SAAS,KAAK,OAA6B;AACzC,QAAM,UAAU,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI,OAAO;AAChG,SAAO,OAAO,SAAS,OAAO,KAAK,UAAU,IAAI,IAAI,KAAK,UAAU,GAAI,IAAI;AAC9E;AAHS;AAWT,SAAS,QAAQ,SAA4B;AAC3C,MAAI,CAAC,SAAS,OAAO,KAAK,QAAQ,WAAW,4BAA6B,QAAO,CAAC;AAClF,SAAO,KAAK,QAAQ,KAAK,EACtB,QAAQ,CAAC,UAAU,KAAK,MAAM,OAAO,CAAC,EACtC,QAAQ,CAAC,WAAqB;AAC7B,UAAM,QAAQ,OAAO;AACrB,UAAM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AAO,YAAY,SAAS,UAAU,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC,EAAG,CAAC,GADrH;AAAA,IAEZ,QAAQ,oBAAoB,0BAA0B;AAAA,EACxD;AACF;AAfgB;","names":["text"]}
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The encoded runs an inbound message may hide an instruction in: long
3
+ * base64, hex, URL-encoded escapes of letters, and Unicode tag characters
4
+ * (invisible ASCII). Each run is decoded only when the result reads as text,
5
+ * so a payment code, a hash or a tracking id (which decode to bytes, not
6
+ * words) yields nothing.
7
+ */
8
+ type EncodingKind = "base64" | "hex" | "url" | "unicode-tags";
9
+ /** One encoded run found in a message and the text it decodes to. */
10
+ interface DecodedRun {
11
+ readonly encoding: EncodingKind;
12
+ /** The run as it appears in the message. */
13
+ readonly source: string;
14
+ /** What it decodes to. Scanned by the screen like the message itself. */
15
+ readonly text: string;
16
+ }
17
+
18
+ /**
19
+ * `normalizeInbound` — the one view of an untrusted message every later step
20
+ * reads. It removes what renders as nothing (zero-width, bidi and control
21
+ * characters, Unicode tags), applies NFKC (full-width and styled letters
22
+ * become plain ones), folds Cyrillic and Greek look-alikes inside words that
23
+ * are spoofing Latin, and decodes obvious encoded runs into extra views the
24
+ * screen also scans. Pure: no I/O, no clock, no randomness.
25
+ */
26
+
27
+ interface NormalizedInbound {
28
+ /** The message exactly as received. */
29
+ readonly original: string;
30
+ /** Invisibles stripped, NFKC, look-alikes folded, line breaks unified. What an agent may be shown. */
31
+ readonly text: string;
32
+ /** `text` lower-cased, accents removed, whitespace collapsed. What the rules match. */
33
+ readonly folded: string;
34
+ /** Encoded runs that decode to text, at any depth up to two. */
35
+ readonly decoded: readonly DecodedRun[];
36
+ /** Invisible characters removed that have no innocent reading (emoji joiners are not counted). */
37
+ readonly invisibles: number;
38
+ /** Words written with look-alike letters from another script, or styled letters. */
39
+ readonly lookAlikes: number;
40
+ }
41
+ /** Lower case, no accents, one space between words: the text the rules read. */
42
+ declare function foldForMatching(text: string): string;
43
+ /** Normalize one untrusted inbound message. Never throws. */
44
+ declare function normalizeInbound(text: string): NormalizedInbound;
45
+
46
+ /** The shapes of the screen's rules; the lists themselves are in `rules*.ts`. */
47
+ type InboundRisk = "low" | "medium" | "high";
48
+ /** A rule that matches the message's words. */
49
+ interface PatternRule {
50
+ readonly id: string;
51
+ readonly kind: "pattern";
52
+ readonly weight: number;
53
+ readonly description: string;
54
+ readonly patterns: readonly RegExp[];
55
+ /** Needles for the letters-and-digits-only view. Keep them long (12+): short ones match across words. */
56
+ readonly compact?: readonly string[];
57
+ /**
58
+ * A signal customers also give (a link, a password, "a partir de agora",
59
+ * dismissing their own earlier message). When every rule a message trips is
60
+ * weak, its risk is capped at `DEFAULT_WEAK_CAP`: weak signals alone never
61
+ * withhold a message, however many add up.
62
+ */
63
+ readonly weak?: boolean;
64
+ }
65
+ /** A rule on a measured property of the message rather than its words. */
66
+ interface SignalRule {
67
+ readonly id: string;
68
+ readonly kind: "length" | "burst" | "encoded" | "invisible" | "look-alike";
69
+ readonly weight: number;
70
+ readonly description: string;
71
+ /** Trips at this value or above: characters, recent messages, decoded runs, characters, words. */
72
+ readonly atLeast: number;
73
+ /**
74
+ * A signal customers also give (a link, a password, "a partir de agora",
75
+ * dismissing their own earlier message). When every rule a message trips is
76
+ * weak, its risk is capped at `DEFAULT_WEAK_CAP`: weak signals alone never
77
+ * withhold a message, however many add up.
78
+ */
79
+ readonly weak?: boolean;
80
+ }
81
+ type InboundRule = PatternRule | SignalRule;
82
+ interface ScreenThresholds {
83
+ /** A score at or above this is `medium`. */
84
+ readonly medium: number;
85
+ /** A score at or above this is `high`: the text never reaches a model. */
86
+ readonly high: number;
87
+ }
88
+ declare const DEFAULT_THRESHOLDS: ScreenThresholds;
89
+ /** The highest risk a message reaches when only `weak` rules tripped. */
90
+ declare const DEFAULT_WEAK_CAP: InboundRisk;
91
+ /**
92
+ * How many characters of the folded text (and of each decoded run) the
93
+ * pattern rules read. Longer input already trips the length rules
94
+ * (`extreme-length` alone with `excessive-length` is `high`), so the tail adds
95
+ * nothing but time. A host that replaces the rule list keeps the length rules
96
+ * (or raises this limit): the tail past it is never scanned.
97
+ */
98
+ declare const DEFAULT_SCAN_LIMIT = 8000;
99
+
100
+ /**
101
+ * The screen's rules, as data. Each rule is a named entry with a weight; the
102
+ * screen sums the weights of the rules a message trips and compares the sum
103
+ * with `DEFAULT_THRESHOLDS`. A host overrides either by passing its own list
104
+ * (`screenInbound(text, { rules: [...DEFAULT_INBOUND_RULES, mine] })`).
105
+ *
106
+ * Patterns are written against the FOLDED view (lower case, no accents, one
107
+ * space between words), so they are plain ASCII and match "instruções",
108
+ * "INSTRUCOES" and "instrucoes" alike. The screen also runs them over the
109
+ * same text with every run of punctuation, markup or emoji read as one space,
110
+ * and matches `compact` needles against it with everything but letters and
111
+ * digits removed, which is how a phrase split letter by letter is still found.
112
+ */
113
+
114
+ /** The default rule list, in the order reasons are reported. */
115
+ declare const DEFAULT_INBOUND_RULES: readonly InboundRule[];
116
+
117
+ /**
118
+ * `screenInbound` — the deterministic risk screen. It normalizes the message,
119
+ * runs every rule over the folded text, its leetspeak reading, its
120
+ * letters-only reading and every decoded run, and sums the weights of the
121
+ * rules that tripped. Pure and synchronous: the same text and options always
122
+ * give the same answer.
123
+ */
124
+
125
+ interface ScreenOptions {
126
+ /** Replaces the rule list. Extend with `[...DEFAULT_INBOUND_RULES, mine]`. */
127
+ readonly rules?: readonly InboundRule[];
128
+ readonly thresholds?: ScreenThresholds;
129
+ /** The highest risk when only `weak` rules tripped. Default `DEFAULT_WEAK_CAP`; `"high"` turns the cap off. */
130
+ readonly weakCap?: InboundRisk;
131
+ /** How many messages this sender sent recently, this one included. The caller picks the window. */
132
+ readonly recentFromSender?: number;
133
+ /** Characters of the folded text (and of each decoded run) the pattern rules read. Default `DEFAULT_SCAN_LIMIT`. */
134
+ readonly scanLimit?: number;
135
+ }
136
+ interface ScreenResult {
137
+ readonly risk: InboundRisk;
138
+ /** The ids of the rules that tripped; `<id>:<encoding>` when only a decoded run tripped it. */
139
+ readonly reasons: readonly string[];
140
+ readonly score: number;
141
+ readonly normalized: NormalizedInbound;
142
+ }
143
+ /** `risk`, lowered to `cap` when every tripped rule is weak. */
144
+ declare function capWeak(risk: InboundRisk, tripped: readonly InboundRule[], cap: InboundRisk): InboundRisk;
145
+ declare function riskOf(score: number, thresholds: ScreenThresholds): InboundRisk;
146
+ /** Screen one untrusted inbound message. */
147
+ declare function screenInbound(text: string, opts?: ScreenOptions): ScreenResult;
148
+
149
+ /**
150
+ * `wrapForAgent` — what a model is allowed to read of a batch of untrusted
151
+ * messages. A `low` or `medium` message is quoted as data between two lines
152
+ * carrying a per-call random delimiter, under one fixed rule line that says
153
+ * so. A `high` message is never shown: only who sent it, when, how long it
154
+ * was and why it was withheld. The sender's handle is chosen by the sender,
155
+ * so it is screened too: one that trips any rule, or carries characters the
156
+ * header cannot hold, is replaced by an opaque `sender-<n>`.
157
+ */
158
+
159
+ interface InboundForAgent {
160
+ readonly id: string;
161
+ readonly senderHandle: string;
162
+ readonly time: Date | string;
163
+ readonly text: string;
164
+ /** A screen already run on this same `text` (another text is refused). Omitted, the message is screened here. */
165
+ readonly screen?: ScreenResult;
166
+ /** Passed to the screen when it runs here. */
167
+ readonly recentFromSender?: number;
168
+ }
169
+ interface WrapOptions {
170
+ /** A fixed delimiter, for tests. Omitted, a fresh crypto-random one is drawn per call. */
171
+ readonly delimiter?: string;
172
+ /** Rules and thresholds for messages screened here. */
173
+ readonly screen?: Omit<ScreenOptions, "recentFromSender">;
174
+ }
175
+ type WrappedEntry = {
176
+ readonly kind: "data";
177
+ readonly id: string;
178
+ /** The handle as received, or `sender-<n>` when it was withheld. */
179
+ readonly senderHandle: string;
180
+ readonly senderWithheld: boolean;
181
+ readonly time: string;
182
+ readonly risk: Exclude<InboundRisk, "high">;
183
+ readonly text: string;
184
+ } | {
185
+ readonly kind: "withheld";
186
+ readonly id: string;
187
+ readonly senderHandle: string;
188
+ readonly senderWithheld: boolean;
189
+ readonly time: string;
190
+ readonly length: number;
191
+ readonly reasons: readonly string[];
192
+ };
193
+ interface WrappedBatch {
194
+ readonly delimiter: string;
195
+ /** The prompt section: the rule line, then each entry. */
196
+ readonly prompt: string;
197
+ readonly entries: readonly WrappedEntry[];
198
+ }
199
+ declare class DelimiterCollisionError extends Error {
200
+ readonly messageId: string;
201
+ constructor(messageId: string);
202
+ }
203
+ /** The rule line. Fixed text: nothing a sender wrote is ever part of it. */
204
+ declare function wrapRuleLine(delimiter: string): string;
205
+ /** A fresh delimiter: 128 bits from the platform's CSPRNG. */
206
+ declare function randomDelimiter(): string;
207
+ /**
208
+ * Wrap a batch for one model call. Throws `DelimiterCollisionError` when a
209
+ * message that would be shown contains the delimiter, and a `TypeError` for a
210
+ * delimiter that is not 16-128 characters of `[A-Za-z0-9_-]` or for a given
211
+ * screen that was run on other text.
212
+ */
213
+ declare function wrapForAgent(messages: readonly InboundForAgent[], opts?: WrapOptions): WrappedBatch;
214
+
215
+ /**
216
+ * `parseClassification` — the only shape a classifying agent's answer may
217
+ * take. Anything else (bad JSON, a missing or extra field, a value outside
218
+ * its set, a summary over 200 characters or carrying contact data) comes back
219
+ * as a typed error the caller reports and drops; nothing the agent wrote
220
+ * outside the schema reaches a person or a tool.
221
+ */
222
+ declare const CLASSIFICATION_CATEGORIES: readonly ["duvida", "reclamacao", "lead", "elogio", "spam", "suspeita"];
223
+ declare const CLASSIFICATION_URGENCIES: readonly ["hoje", "normal"];
224
+ declare const SUMMARY_MAX_LENGTH = 200;
225
+ type ClassificationCategory = (typeof CLASSIFICATION_CATEGORIES)[number];
226
+ type ClassificationUrgency = (typeof CLASSIFICATION_URGENCIES)[number];
227
+ interface Classification {
228
+ readonly id: string;
229
+ readonly category: ClassificationCategory;
230
+ readonly urgency: ClassificationUrgency;
231
+ readonly summary: string;
232
+ readonly needs_human: boolean;
233
+ }
234
+ type ClassificationErrorCode = "invalid-json" | "not-an-object" | "unknown-field" | "missing-field" | "invalid-field" | "unknown-id";
235
+ interface ClassificationError {
236
+ readonly code: ClassificationErrorCode;
237
+ readonly field?: string;
238
+ readonly message: string;
239
+ }
240
+ type ClassificationResult = {
241
+ readonly ok: true;
242
+ readonly value: Classification;
243
+ } | {
244
+ readonly ok: false;
245
+ readonly error: ClassificationError;
246
+ };
247
+ interface ParseClassificationOptions {
248
+ /** The ids that were sent to the agent. An answer about any other id is refused. */
249
+ readonly ids?: Iterable<string>;
250
+ }
251
+ /** Validate one classification, given as a JSON string or an already-parsed value. */
252
+ declare function parseClassification(input: unknown, opts?: ParseClassificationOptions): ClassificationResult;
253
+
254
+ export { CLASSIFICATION_CATEGORIES, CLASSIFICATION_URGENCIES, type Classification, type ClassificationCategory, type ClassificationError, type ClassificationErrorCode, type ClassificationResult, type ClassificationUrgency, DEFAULT_INBOUND_RULES, DEFAULT_SCAN_LIMIT, DEFAULT_THRESHOLDS, DEFAULT_WEAK_CAP, type DecodedRun, DelimiterCollisionError, type EncodingKind, type InboundForAgent, type InboundRisk, type InboundRule, type NormalizedInbound, type ParseClassificationOptions, type PatternRule, SUMMARY_MAX_LENGTH, type ScreenOptions, type ScreenResult, type ScreenThresholds, type SignalRule, type WrapOptions, type WrappedBatch, type WrappedEntry, capWeak, foldForMatching, normalizeInbound, parseClassification, randomDelimiter, riskOf, screenInbound, wrapForAgent, wrapRuleLine };