@zervonexx/baileys 0.0.0-stage → 5.0.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.
- package/LICENSE +23 -0
- package/README.md +4113 -3
- package/WAProto/WAProtoCompile.js +323 -0
- package/WAProto/fetcher.js +68 -0
- package/WAProto/index.js +96 -0
- package/WAProto/parser.js +334 -0
- package/lib/Builders/AIRich.js +674 -0
- package/lib/Builders/auto.js +50 -0
- package/lib/Builders/base.js +145 -0
- package/lib/Builders/builders.js +589 -0
- package/lib/Builders/index.js +4 -0
- package/lib/Defaults/index.js +248 -0
- package/lib/Signal/index.js +2 -0
- package/lib/Signal/libsignal.js +527 -0
- package/lib/Signal/lid-mapping.js +283 -0
- package/lib/Socket/Client/index.js +2 -0
- package/lib/Socket/Client/types.js +10 -0
- package/lib/Socket/Client/websocket.js +84 -0
- package/lib/Socket/business.js +152 -0
- package/lib/Socket/chats.js +855 -0
- package/lib/Socket/communities.js +147 -0
- package/lib/Socket/groups.js +294 -0
- package/lib/Socket/index.js +15 -0
- package/lib/Socket/messages-recv.js +994 -0
- package/lib/Socket/messages-send.js +723 -0
- package/lib/Socket/mex.js +34 -0
- package/lib/Socket/newsletter.js +784 -0
- package/lib/Socket/registration.js +155 -0
- package/lib/Socket/socket.js +798 -0
- package/lib/Socket/spam-report.js +144 -0
- package/lib/Socket/username.js +82 -0
- package/lib/Socket/zervonex-handler.js +58 -0
- package/lib/Store/index.js +6 -0
- package/lib/Store/make-cache-manager-store.js +80 -0
- package/lib/Store/make-in-memory-store.js +426 -0
- package/lib/Store/make-ordered-dictionary.js +82 -0
- package/lib/Store/object-repository.js +31 -0
- package/lib/Store/reporting-info-store.js +38 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +8 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +15 -0
- package/lib/Types/Newsletter.js +100 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +26 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +30 -0
- package/lib/Utils/auth-utils.js +159 -0
- package/lib/Utils/baileys-event-stream.js +33 -0
- package/lib/Utils/bot-capabilities.js +41 -0
- package/lib/Utils/bot-planning-replay.js +44 -0
- package/lib/Utils/browser-utils.js +30 -0
- package/lib/Utils/business.js +75 -0
- package/lib/Utils/chat-utils.js +317 -0
- package/lib/Utils/companion-reg-client-utils.js +20 -0
- package/lib/Utils/consumer-application.js +38 -0
- package/lib/Utils/crypto.js +53 -0
- package/lib/Utils/cstoken.js +15 -0
- package/lib/Utils/decode-wa-message.js +200 -0
- package/lib/Utils/event-buffer.js +273 -0
- package/lib/Utils/extras.js +186 -0
- package/lib/Utils/generics.js +195 -0
- package/lib/Utils/history.js +51 -0
- package/lib/Utils/identity-change-handler.js +19 -0
- package/lib/Utils/index.js +40 -0
- package/lib/Utils/link-preview.js +51 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/lt-hash.js +3 -0
- package/lib/Utils/make-mutex.js +16 -0
- package/lib/Utils/message-composer.js +62 -0
- package/lib/Utils/message-retry-manager.js +48 -0
- package/lib/Utils/messages-media.js +502 -0
- package/lib/Utils/messages.js +943 -0
- package/lib/Utils/meta-ai-msmsg.js +122 -0
- package/lib/Utils/meta-compositing.js +75 -0
- package/lib/Utils/modern-messages.js +235 -0
- package/lib/Utils/native-flow.js +81 -0
- package/lib/Utils/noise-handler.js +161 -0
- package/lib/Utils/pre-key-manager.js +76 -0
- package/lib/Utils/process-message.js +401 -0
- package/lib/Utils/reporting-utils.js +171 -0
- package/lib/Utils/signal.js +167 -0
- package/lib/Utils/spam-report-utils.js +166 -0
- package/lib/Utils/sync-action-utils.js +33 -0
- package/lib/Utils/tc-token-utils.js +154 -0
- package/lib/Utils/use-keyv-auth-state.js +200 -0
- package/lib/Utils/use-multi-file-auth-state.js +84 -0
- package/lib/Utils/validate-connection.js +172 -0
- package/lib/WABinary/constants.js +1321 -0
- package/lib/WABinary/decode.js +152 -0
- package/lib/WABinary/encode.js +140 -0
- package/lib/WABinary/generic-utils.js +203 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/jid-utils.js +235 -0
- package/lib/WABinary/types.js +4 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +150 -0
- package/lib/WAM/index.js +3 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
- package/lib/WAUSync/Protocols/index.js +12 -0
- package/lib/WAUSync/USyncQuery.js +88 -0
- package/lib/WAUSync/USyncUser.js +20 -0
- package/lib/WAUSync/index.js +3 -0
- package/lib/index.js +67 -0
- package/package.json +191 -5
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
import crypto from 'crypto'
|
|
2
|
+
import { proto } from '../../WAProto/index.js'
|
|
3
|
+
import {
|
|
4
|
+
generateMessageIDV2, generateVerificationMetadata, waitAllPromises, extractIE, tokenizeCode, generateWAMessageFromContent, generateWAMessage,
|
|
5
|
+
makeWhatsAppFlowButton, metaTyping, sendMetaComposited, PlanningStepStatus, buildSteps, replayPlanning, replayPlanningOnly, buildReasoningSteps, buildSearchSteps,
|
|
6
|
+
mixedSteps, buildBotRichResponse, BotCapabilityType, RichSubMessageType, generateTableContent, generateListContent, generateCodeBlockContent,
|
|
7
|
+
generateLatexContent, captureUnifiedResponse, generateUnifiedResponseContent, normalizeToBuffer, prepareWAMessageMedia, isHttpUrl
|
|
8
|
+
} from '../Utils/index.js'
|
|
9
|
+
import { isJidGroup, isJidMetaAI, jidNormalizedUser, getBizBinaryNode } from '../WABinary/index.js'
|
|
10
|
+
import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
|
|
11
|
+
import { randomBytes } from 'crypto'
|
|
12
|
+
|
|
13
|
+
const DEFAULT_BOT_JID = '867051314767696@bot'
|
|
14
|
+
const META_AI_BOT_JID = '867051314767696@bot'
|
|
15
|
+
const STATUS_JID = 'status@broadcast'
|
|
16
|
+
const BIZ_BOT_SUPPORT = '{"version":1,"is_ai_message":true,"should_upload_client_logs":false,"should_show_system_message":false,"ticket_id":"7004947587700716","citation_items":[],"ticket_locale":"us"}'
|
|
17
|
+
|
|
18
|
+
const mkSection = vm => ({ __typename: 'GenAIUnifiedResponseSection', view_model: vm })
|
|
19
|
+
const single = p => mkSection({ __typename: 'GenAISingleLayoutViewModel', primitive: p })
|
|
20
|
+
const vstack = ps => mkSection({ __typename: 'GenAIVStackLayoutViewModel', primitives: ps })
|
|
21
|
+
const hscroll = ps => mkSection({ __typename: 'GenAIHScrollLayoutViewModel', primitives: ps })
|
|
22
|
+
const grid = ps => mkSection({ __typename: 'GenAIGridLayoutViewModel', primitives: ps })
|
|
23
|
+
const actionRow = ps => ({ view_model: { __typename: 'GenAIActionRowLayoutViewModel', primitives: ps } })
|
|
24
|
+
const addonAction = (type, ps, alignment = 'END') => mkSection({ __typename: 'GenAIAddonActionLayoutViewModel', addon_action_type: type, addon_action_alignment: alignment, primitives: ps })
|
|
25
|
+
|
|
26
|
+
const mkMarkdown = (text, entities = []) => { const { text: t, inline_entities } = extractIE(text, entities); return { __typename: 'GenAIMarkdownTextUXPrimitive', text: t, inline_entities } }
|
|
27
|
+
const mkCode = (content, language = '', unified_codeBlock = []) => ({ __typename: 'GenAICodeUXPrimitive', language, code_blocks: unified_codeBlock.length ? unified_codeBlock : [{ content }] })
|
|
28
|
+
|
|
29
|
+
const MAX_TABLE_ROWS = 5000, MAX_TABLE_COLUMNS = 200, MAX_TABLE_CELLS = 100_000
|
|
30
|
+
const mkTable = (rows, title = '') => {
|
|
31
|
+
if (!Array.isArray(rows) || rows.length === 0) throw new TypeError('mkTable requires a non-empty rows array')
|
|
32
|
+
if (rows.length > MAX_TABLE_ROWS) throw new RangeError(`mkTable: too many rows (${rows.length} > ${MAX_TABLE_ROWS})`)
|
|
33
|
+
const firstRow = Array.isArray(rows[0]) ? rows[0] : (rows[0].cells ?? rows[0].items ?? [])
|
|
34
|
+
if (firstRow.length > MAX_TABLE_COLUMNS) throw new RangeError(`mkTable: too many columns (${firstRow.length} > ${MAX_TABLE_COLUMNS})`)
|
|
35
|
+
if (rows.length * firstRow.length > MAX_TABLE_CELLS) throw new RangeError(`mkTable: too many cells (${rows.length * firstRow.length} > ${MAX_TABLE_CELLS})`)
|
|
36
|
+
const normalized = Array.isArray(rows[0])
|
|
37
|
+
? rows.map((r, i) => ({ is_header: i === 0, cells: r.map(c => (typeof c === 'string' ? c : String(c))), markdown_cells: r.map(c => ({ text: typeof c === 'string' ? c : String(c) })) }))
|
|
38
|
+
: rows.map(r => ({ is_header: !!r.is_header, cells: (r.cells ?? r.items ?? []).map(c => (typeof c === 'string' ? c : String(c))), markdown_cells: (r.cells ?? r.items ?? []).map(c => ({ text: typeof c === 'string' ? c : String(c) })) }))
|
|
39
|
+
return { __typename: 'GenATableUXPrimitive', title, rows: normalized }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const mkImage = (input, expiration) => {
|
|
43
|
+
const img = typeof input === 'string' ? { url: input } : input
|
|
44
|
+
const exp = expiration ?? String(Date.now() + 30 * 24 * 60 * 60 * 1000)
|
|
45
|
+
const first = (...vals) => vals.find(v => v != null && String(v).length > 0)
|
|
46
|
+
const previewUrl = first(img.previewUrl, img.preview_url, img.imagePreviewUrl, img.url) ?? ''
|
|
47
|
+
const fullUrl = first(img.highResUrl, img.high_res_url, img.imageHighResUrl, img.fullUrl, img.full_url, img.url, previewUrl)
|
|
48
|
+
const darkPreview = first(img.darkModePreviewUrl, img.dark_mode_preview_url, previewUrl)
|
|
49
|
+
const darkFull = first(img.darkModeHighResUrl, img.dark_mode_high_res_url, darkPreview)
|
|
50
|
+
const mime = img.mimeType ?? img.mime_type ?? (/\.png$/i.test(img.url ?? '') ? 'image/png' : 'image/jpeg')
|
|
51
|
+
const w = Number(img.width ?? 600), h = Number(img.height ?? 400)
|
|
52
|
+
const media = (url, mw, mh) => ({ url, url_fallback: url, mime_type: mime, expiration_timestamp_ms: exp, width: mw, height: mh })
|
|
53
|
+
return { __typename: 'GenAIImagePrimitive', preview_image: media(previewUrl, w, h), full_image: media(fullUrl, w, h), dark_mode_preview_image: media(darkPreview, w, h), dark_mode_full_image: media(darkFull, w, h), asset_query_status: 'FETCHED' }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const mkVideo = url => ({ __typename: 'GenAIVideoPrimitive', media: { __typename: 'GenAIMediaItem', mime_type: 'video/mp4', url } })
|
|
57
|
+
const mkReel = ({ creator, avatar_url, thumbnail_url, reels_url, title, likes_count, shares_count, view_count, reel_source, is_verified }) => ({ __typename: 'GenAIReelPrimitive', creator: creator ?? '', avatar_url: avatar_url ?? '', thumbnail_url: thumbnail_url ?? '', reels_url: reels_url ?? '', reels_title: title ?? '', likes_count: likes_count ?? 0, shares_count: shares_count ?? 0, view_count: view_count ?? 0, reel_source: reel_source ?? 'IG', is_verified: !!is_verified })
|
|
58
|
+
const mkPost = d => ({ __typename: 'GenAIPostPrimitive', title: d.title ?? '', username: d.username ?? '', subtitle: d.subtitle ?? '', thumbnail_url: d.thumbnail_url ?? '', post_url: d.post_url ?? d.url ?? '', post_caption: d.post_caption ?? d.caption ?? '', post_type: d.post_type ?? 'photo', source_app: d.source_app ?? 'instagram', likes_count: d.likes_count ?? 0, comments_count: d.comments_count ?? 0, shares_count: d.shares_count ?? 0, is_verified: d.is_verified ?? false, is_carousel: d.is_carousel ?? false, orientation: d.orientation ?? 'portrait', profile_picture_url: d.profile_picture_url ?? null, footer_label: d.footer_label ?? null, footer_icon: d.footer_icon ?? null, additional_images: d.additional_images ?? [] })
|
|
59
|
+
const mkProduct = d => ({ __typename: 'GenAIProductItemCardPrimitive', title: d.title ?? '', brand: d.brand ?? '', price: d.price ?? '', sale_price: d.sale_price ?? null, product_url: d.product_url ?? d.url ?? '', image: { url: d.image_url ?? d.image ?? '' }, additional_images: [] })
|
|
60
|
+
const mkSearchResult = d => ({ __typename: 'GenAISearchResultPrimitive', source_url: d.url ?? d.source_url ?? '', source_display_name: d.title ?? d.source_display_name ?? '', source_type: d.source_type ?? 'web', source_subtitle: d.subtitle ?? d.source_subtitle ?? '', favicon: d.favicon ?? null })
|
|
61
|
+
const mkMap = ({ latitude, longitude, name = '', address = '' }) => ({ __typename: 'GenAIMapPrimitive', latitude, longitude, name, address })
|
|
62
|
+
|
|
63
|
+
const _mp4Duration = (buf, silent = true) => {
|
|
64
|
+
try { if (!Buffer.isBuffer(buf) || buf.length < 8) { if (silent) return 0; throw new Error('Invalid buffer') }; let o = 0; while (o < buf.length - 8) { const sz = buf.readUInt32BE(o); if (sz < 8 || o + sz > buf.length) { if (silent) return 0; throw new Error('Bad atom') }; if (buf.toString('ascii', o + 4, o + 8) === 'moov') { let m = o + 8; const me = o + sz; while (m < me - 8) { const cs = buf.readUInt32BE(m); if (cs < 8 || m + cs > me) break; if (buf.toString('ascii', m + 4, m + 8) === 'mvhd') { const v = buf.readUInt8(m + 8); if (v === 0) { const ts = buf.readUInt32BE(m + 20); const dur = buf.readUInt32BE(m + 24); return ts ? dur / ts : 0 }; if (v === 1) { const ts = buf.readUInt32BE(m + 32); const dur = Number(buf.readBigUInt64BE(m + 36)); return ts ? dur / ts : 0 } }; m += cs } }; o += sz }; return 0 }
|
|
65
|
+
catch { return 0 }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const _mp4Preview = async (buf, time, silent = true) => {
|
|
69
|
+
const fail = e => { if (!silent) throw e; return null }; if (!Buffer.isBuffer(buf) || !buf.length) return fail(new Error('Empty buffer'))
|
|
70
|
+
try {
|
|
71
|
+
const { Readable, PassThrough } = await import('stream'); const { default: ffmpeg } = await import('fluent-ffmpeg'); const src = new Readable({ read() { } }); src.push(buf); src.push(null); const out = new PassThrough(); const chunks = []; out.on('data', c => chunks.push(c)); const t = time ?? Math.max(0.5, Math.min(_mp4Duration(buf) * 0.3, 10)); await new Promise((res, rej) => { out.on('end', res); out.on('error', rej); ffmpeg(src).outputOptions([`-ss ${t}`, '-vframes 1', '-vcodec png', '-f image2pipe']).on('error', rej).pipe(out, { end: true }) }); const b = Buffer.concat(chunks); return b.length ? b.toString('base64') : fail(new Error('Empty output'))
|
|
72
|
+
} catch (e) { return fail(e) }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const mkRichMap = ({ centerLatitude, centerLongitude, latitudeDelta, longitudeDelta, annotations = [], showInfoList = false }) => {
|
|
76
|
+
if (centerLatitude == null || centerLongitude == null) throw new TypeError('addRichMap requires centerLatitude and centerLongitude')
|
|
77
|
+
const submessage = { messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_MAP, mapMetadata: { centerLatitude, centerLongitude, ...(latitudeDelta != null ? { latitudeDelta } : {}), ...(longitudeDelta != null ? { longitudeDelta } : {}), showInfoList: !!showInfoList, annotations: annotations.map((a, i) => ({ annotationNumber: a.annotationNumber ?? i + 1, latitude: a.latitude, longitude: a.longitude, title: a.title ?? '', body: a.body ?? '' })) } }
|
|
78
|
+
const displayLat = annotations[0]?.latitude ?? centerLatitude, displayLng = annotations[0]?.longitude ?? centerLongitude
|
|
79
|
+
return { submessage, section: single({ __typename: 'GenAIMapPrimitive', latitude: displayLat, longitude: displayLng, name: annotations[0]?.title ?? '', address: annotations[0]?.body ?? '' }) }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const mkRichMenu = ({ header = {}, body = {}, footer = {} }) => {
|
|
83
|
+
const sections = []
|
|
84
|
+
if (header?.title) sections.push(single({ __typename: 'FOATextPrimitive', text: '# ' + header.title }))
|
|
85
|
+
if (header?.image?.url) sections.push(single(header.image.inline ? mkInlineImage(header.image.url) : mkImage(header.image)))
|
|
86
|
+
if (header?.disclaimer) sections.push(single(mkMarkdown(header.disclaimerText || ' ')))
|
|
87
|
+
const cards = Array.isArray(body?.cards) ? body.cards : []
|
|
88
|
+
const buttons = Array.isArray(body?.buttons) ? body.buttons : []
|
|
89
|
+
if (cards.length) sections.push({ view_model: { primitives: cards.map(card => mkWidget(Array.isArray(card?.buttons) ? card.buttons : [], card?.title || '')), __typename: body.carousel ? 'GenAIHScrollLayoutViewModel' : 'GenAIActionRowLayoutViewModel' } })
|
|
90
|
+
else if (buttons.length) sections.push(single(mkWidget(buttons, body.title || '')))
|
|
91
|
+
if (footer?.text || footer?.url) sections.push({ view_model: { primitives: [mkFooterAction({ text: footer.text, url: footer.url })], __typename: 'GenAIActionRowLayoutViewModel' } })
|
|
92
|
+
return sections
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const mkDynamic = ({ url, type = 'GIF', version, loopCount } = {}) => {
|
|
96
|
+
if (!url) throw new TypeError('addDynamic requires a url')
|
|
97
|
+
const dynType = String(type).toUpperCase() === 'IMAGE' ? proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE : proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF
|
|
98
|
+
const submessage = { messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_DYNAMIC, dynamicMetadata: { type: dynType, url, ...(version != null ? { version } : {}), ...(loopCount != null ? { loopCount } : {}) } }
|
|
99
|
+
const mimeType = dynType === proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE ? 'image/jpeg' : 'image/gif'
|
|
100
|
+
return { submessage, section: single({ __typename: 'GenAIDynamicMediaPrimitive', url, mime_type: mimeType, ...(loopCount != null ? { loop_count: loopCount } : {}) }) }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const mkWidget = (ctas, title = '') => ({ __typename: 'GenAI3PExtWidgetPrimitive', header: { __typename: 'GenAI3PExtWidgetStandardHeader', title }, body: { __typename: 'GenAI3PExtCalendarEventList', ctas: ctas.map(c => ({ __typename: 'GenAI3PExtWidgetCTA', label: c.label, state: 'PENDING', kind: c.kind ?? 'OTHER', tool_call_id: c.tool_call_id ?? c.id ?? crypto.randomBytes(8).toString('hex'), toast: { __typename: 'GenAI3PExtWidgetToast', label: c.toast ?? '' } })), sections: [] } })
|
|
104
|
+
const mkFooterAction = d => ({ __typename: 'GenAIFooterActionPrimitive', cta_text: d.cta_text ?? d.text ?? '', cta_type: d.cta_type ?? 'OPEN_URL', cta_url: d.cta_url ?? d.url ?? '' })
|
|
105
|
+
|
|
106
|
+
const mkSocialProfile = ({ username = '', platform = 'GENERIC', title = '', subtitle = '', imageUrl = '', entityId, entityUrl, entityType, fullName = '', isVerified = false, resultText = 'See results' }) => {
|
|
107
|
+
if (!username || typeof username !== 'string') throw new TypeError('addSocialProfile requires a username')
|
|
108
|
+
const normalizedPlatform = String(platform).toUpperCase()
|
|
109
|
+
const profileUrl = entityUrl ?? (username ? `https://www.${platform.toLowerCase()}.com/${encodeURIComponent(username)}` : '')
|
|
110
|
+
const resolvedType = entityType ?? (normalizedPlatform === 'INSTAGRAM' ? 'IG_PROFILE' : 'SOCIAL_PROFILE')
|
|
111
|
+
const image = imageUrl ? { url: imageUrl, mime_type: 'image/png' } : undefined
|
|
112
|
+
return [
|
|
113
|
+
{ view_model: { primitives: [{ __typename: 'GenAICompactEntityPrimitive', title, subtitle, ...(image ? { image } : {}), entity_id: String(entityId ?? username ?? ''), entity_url: profileUrl, entity_type: 'WEBSITE', action_type: 'OPEN_URL', is_verified: !!isVerified }], __typename: 'GenAIActionRowLayoutViewModel' } },
|
|
114
|
+
{ view_model: { primitives: [{ type: 'HORIZONTAL_LINE', __typename: 'GenAIDividerPrimitive' }], __typename: 'GenAIVStackLayoutViewModel' } },
|
|
115
|
+
{ view_model: { primitives: [{ __typename: 'GenAISpacerPrimitive' }, { __typename: 'GenAIMarkdownTextUXPrimitive', text: `# {{social_entity_1}}${resultText}\0{{/social_entity_1}} `, inline_entities: [{ key: 'social_entity_1', metadata: { __typename: 'GenAISocialEntityItem', entity_id: String(entityId ?? username ?? ''), entity_name: username, entity_full_name: fullName, platform: normalizedPlatform, entity_picture_url: imageUrl, entity_url: profileUrl, entity_type: resolvedType, is_verified: !!isVerified } }] }, { __typename: 'GenAISpacerPrimitive' }], __typename: 'GenAIActionRowLayoutViewModel' } }
|
|
116
|
+
]
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const mkInlineImage = (url, alignment = 'center') => ({ __typename: 'GenAIInlineImageUXPrimitive', image: { __typename: 'GenAIMediaItem', mime_type: 'image/jpeg', url }, alignment })
|
|
120
|
+
const mkInlineLink = (links = []) => { let text = ''; const entities = []; links.forEach((link, i) => { const key = `INLINE_HYPERLINK_${i}`; const display = link.text || link.displayName || link.url || ''; text += `{{${key}}}${display}{{/${key}}}`; entities.push({ key, metadata: { display_name: display, is_trusted: link.isTrusted !== false, url: link.url || '', __typename: 'GenAIInlineLinkItem' } }) }); return { __typename: 'GenAIMarkdownTextUXPrimitive', text, inline_entities: entities } }
|
|
121
|
+
const mkMeta = text => ({ __typename: 'GenAIMetadataTextPrimitive', text })
|
|
122
|
+
const mkFOA = text => ({ __typename: 'FOATextPrimitive', text })
|
|
123
|
+
const mkTip = text => ({ __typename: 'GenAITipUXPrimitive', text })
|
|
124
|
+
const mkDivider = (type = 'HORIZONTAL_LINE') => ({ __typename: 'GenAIDividerPrimitive', divider_type: type })
|
|
125
|
+
const mkSpacer = (spacing = 2) => ({ __typename: 'GenAISpacerPrimitive', spacing })
|
|
126
|
+
const mkThinking = (title, icon = 'THINKING') => ({ __typename: 'GenAIBotThinkingStatusPrimitive', title, icon })
|
|
127
|
+
const mkProgress = (title, inProgress = true) => ({ __typename: 'GenAIBotProgressStatusPrimitive', title, is_in_progress: inProgress, icon: null, meta_search_apps: null, target_secondary_screen_id: null, target_secondary_screen_tab_id: null })
|
|
128
|
+
const mkTask = ({ taskId, title, subtitle = '', status = 'PENDING' }) => ({ __typename: 'GenAITaskPrimitive', task_id: taskId, title, subtitle, status })
|
|
129
|
+
const mkLatex = ({ expression, imageUrl, width = 400, height = 200, fontHeight = 83.333, padding = 15 }) => ({ __typename: 'GenAITextInlineEntity', key: `latex_${crypto.randomUUID().slice(0, 8)}`, metadata: { __typename: 'GenAILatexItem', latex_expression: expression, font_height: fontHeight, padding, latex_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url: imageUrl, url_fallback: imageUrl, width, height, expiration_timestamp_ms: Date.now() + 86400000 } } })
|
|
130
|
+
const mkLabel = (text, variant = 'POSITIVE', backgroundColor = '#FF0000FF', textColor = '#000000FF') => ({ __typename: 'GenAILabelPrimitive', text: String(text), variant, background_color_override: backgroundColor, text_color_override: textColor })
|
|
131
|
+
const mkPill = prompt_text => ({ __typename: 'GenAIFollowUpSuggestionPillPrimitive', prompt_text })
|
|
132
|
+
const mkHtml = (html, trustedSources = []) => ({ __typename: 'FOAHtmlPrimitiveDemoDONOTUSE', trusted_sources: trustedSources, payload: String(html).trim() })
|
|
133
|
+
const mkRichHtml = (html, url = '', trustedSources = []) => ({ __typename: 'GenAIaeacdsnwHtmlPrimitive', payload: String(html).trim(), url, trusted_sources: trustedSources })
|
|
134
|
+
|
|
135
|
+
// validates proofs exist before attaching — never fabricate provenance
|
|
136
|
+
export const hasVerifiableProofs = v => Array.isArray(v?.proofs) && v.proofs.length > 0
|
|
137
|
+
|
|
138
|
+
export const wrapToBotForwardedMessage = (richResponseMessage, verificationMetadata) => ({
|
|
139
|
+
messageContextInfo: { botMetadata: { pluginMetadata: {}, ...(hasVerifiableProofs(verificationMetadata) ? { verificationMetadata } : {}), botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
|
|
140
|
+
botForwardedMessage: { message: { richResponseMessage } }
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
export const attachBotVerificationProofs = (envelope, verificationMetadata) => {
|
|
144
|
+
if (!envelope || !hasVerifiableProofs(verificationMetadata)) return envelope
|
|
145
|
+
const botMetadata = envelope?.messageContextInfo?.botMetadata
|
|
146
|
+
if (!botMetadata || botMetadata.verificationMetadata) return envelope
|
|
147
|
+
botMetadata.verificationMetadata = verificationMetadata
|
|
148
|
+
return envelope
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// only ships previewMedia when all required crypto fields are present — drops incomplete descriptors
|
|
152
|
+
const normalizePreviewMedia = media => {
|
|
153
|
+
if (!media || typeof media !== 'object') return null
|
|
154
|
+
const { fileSha256, mediaKey, fileEncSha256, directPath, mimetype, mediaKeyTimestamp } = media
|
|
155
|
+
if (!fileSha256 || !mediaKey || !fileEncSha256 || !directPath) return null
|
|
156
|
+
return { fileSha256, mediaKey, fileEncSha256, directPath, mediaKeyTimestamp: mediaKeyTimestamp ?? Math.floor(Date.now() / 1000), mimetype: mimetype || 'image/jpeg' }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const buildAdditionalBotMetadata = (submessages) => {
|
|
160
|
+
const sources = [], mediaDetailsMetadataList = []
|
|
161
|
+
for (const sub of submessages) {
|
|
162
|
+
if (sub?.contentItemsMetadata?.itemsMetadata) {
|
|
163
|
+
for (const item of sub.contentItemsMetadata.itemsMetadata) {
|
|
164
|
+
const r = item?.reelItem ?? item ?? {}
|
|
165
|
+
sources.push({ provider: 0, thumbnailCdnUrl: r.thumbnailUrl ?? r.thumbnail_url ?? '', sourceProviderUrl: r.videoUrl ?? r.reels_url ?? r.url ?? '', sourceQuery: '', faviconCdnUrl: r.profileIconUrl ?? r.avatar_url ?? '', citationNumber: sources.length + 1, sourceTitle: r.title ?? r.reels_title ?? r.creator ?? '' })
|
|
166
|
+
const previewMedia = normalizePreviewMedia(r.previewMedia)
|
|
167
|
+
if (previewMedia) mediaDetailsMetadataList.push({ id: r.mediaId ?? r.previewMedia?.mediaId ?? crypto.randomBytes(32).toString('hex'), previewMedia })
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (sub?.latexMetadata?.expressions) {
|
|
171
|
+
for (const expr of sub.latexMetadata.expressions) {
|
|
172
|
+
const previewMedia = normalizePreviewMedia(expr?.previewMedia)
|
|
173
|
+
if (previewMedia) mediaDetailsMetadataList.push({ id: expr.mediaId ?? expr.previewMedia?.mediaId ?? crypto.randomBytes(32).toString('hex'), previewMedia })
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return { sources, mediaDetailsMetadataList }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export const buildImaginePrimitive = ({ mediaType = 'video', url = '', thumbnail, mimeType, fileLength = 0, duration = 0, status = 'GENERATING', estimatedMs, imagineType } = {}) => {
|
|
181
|
+
const type = String(mediaType).toLowerCase() === 'image' ? 'IMAGE' : 'ANIMATE'
|
|
182
|
+
const prim = { __typename: 'GenAIImaginePrimitive', media: { url: url ?? '', mime_type: mimeType ?? (type === 'IMAGE' ? 'image/jpeg' : 'video/mp4'), file_length: fileLength ?? 0, duration: duration ?? 0 }, imagine_type: imagineType ?? type, status: { status: String(status).toUpperCase() } }
|
|
183
|
+
if (estimatedMs != null) prim.status.estimated_completion_time = Math.floor((Date.now() + Number(estimatedMs)) / 1000)
|
|
184
|
+
if (thumbnail) prim.thumbnail = { raw_media: thumbnail }
|
|
185
|
+
return prim
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export const prepareRichGenerationMessage = ({ text = '', mediaType = 'video', url = '', thumbnail, mimeType, fileLength = 0, duration = 0, status = 'GENERATING', estimatedMs, itemId = `imagine_${crypto.randomUUID()}`, responseId = crypto.randomUUID(), verificationMetadata } = {}) => {
|
|
189
|
+
const sections = []
|
|
190
|
+
if (text) sections.push({ view_model: { primitive: { text: String(text), inline_entities: [], __typename: 'GenAIMarkdownTextUXPrimitive' }, __typename: 'GenAISingleLayoutViewModel' } })
|
|
191
|
+
sections.push({ view_model: { primitive: buildImaginePrimitive({ mediaType, url, thumbnail, mimeType, fileLength, duration, status, estimatedMs }), __typename: 'GenAISingleLayoutViewModel', id: itemId } })
|
|
192
|
+
const submessages = text ? [{ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: String(text) }] : []
|
|
193
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages, unifiedResponse: { data: Buffer.from(unifiedData) }, originalRecipientMetadata: { data: Buffer.from(unifiedData) } })
|
|
194
|
+
const message = wrapToBotForwardedMessage(richResponseMessage, verificationMetadata)
|
|
195
|
+
message.messageContextInfo.botMetadata.botResponseId = responseId
|
|
196
|
+
return { message, responseId, itemId }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export class AIRich {
|
|
200
|
+
#client; #nodes = []; #idIndex = {}; #title = ''; #footer = ''; #botJid = DEFAULT_BOT_JID
|
|
201
|
+
#responseId = null; #dynamic = true; #signedVerificationMetadata = null
|
|
202
|
+
#contextInfoExtra = {}; #embeddedScreens = []; #suggestedPrompts = null
|
|
203
|
+
#botSources = null; #pttTranscript = null
|
|
204
|
+
#footerSections = []; #responseMeta = {}; #botMetadataExtra = {}
|
|
205
|
+
|
|
206
|
+
constructor(client, opts = {}) {
|
|
207
|
+
if (!client) throw new Error('Socket client is required')
|
|
208
|
+
this.#client = client
|
|
209
|
+
if (opts.botJid) this.#botJid = opts.botJid
|
|
210
|
+
if (opts.dynamic !== undefined) this.#dynamic = opts.dynamic
|
|
211
|
+
if (opts.responseId) { this.#responseId = opts.responseId; this.#dynamic = false }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
#push(section, submessage = null, id = null) { const nodeId = id ?? `node_${this.#nodes.length}`; this.#nodes.push({ id: nodeId, section, submessage }); this.#idIndex[nodeId] = this.#nodes.length - 1; return this }
|
|
215
|
+
#replace(id, section, submessage = null) { const idx = this.#idIndex[id]; if (idx === undefined) throw new Error(`Node id "${id}" not found`); this.#nodes[idx] = { id, section, submessage }; return this }
|
|
216
|
+
#insertAt(pos, section, submessage = null, id = null) { const nodeId = id ?? `node_${this.#nodes.length}`; this.#nodes.splice(pos, 0, { id: nodeId, section, submessage }); this.#idIndex = {}; this.#nodes.forEach((n, i) => { this.#idIndex[n.id] = i }); return this }
|
|
217
|
+
#add(section, submessage, opts = {}) { if (opts.replace) return this.#replace(opts.replace, section, submessage); if (opts.insertAt !== undefined) return this.#insertAt(opts.insertAt, section, submessage, opts.id); return this.#push(section, submessage, opts.id) }
|
|
218
|
+
|
|
219
|
+
async #uploadMedia(input, mediaType = 'image') { if (typeof input === 'string' && isHttpUrl(input)) return input; const buf = await normalizeToBuffer(input); if (!buf) throw new TypeError('Could not resolve input to buffer'); const result = await prepareWAMessageMedia({ [mediaType]: buf }, { upload: this.#client.waUploadToServer, logger: this.#client.logger }); const msg = result[`${mediaType}Message`]; return msg?.url ?? msg?.directPath }
|
|
220
|
+
|
|
221
|
+
setTitle(title) { this.#title = title; return this }
|
|
222
|
+
setFooter(footer) { this.#footer = footer; return this }
|
|
223
|
+
setBotJid(jid) { this.#botJid = jid; return this }
|
|
224
|
+
setResponseId(id) { this.#responseId = id; this.#dynamic = false; return this }
|
|
225
|
+
setContextInfo(ci) { this.#contextInfoExtra = ci; return this }
|
|
226
|
+
setResponseMeta(meta) { if (!meta || typeof meta !== 'object') throw new TypeError('responseMeta must be a plain object'); this.#responseMeta = { ...this.#responseMeta, ...meta }; return this }
|
|
227
|
+
setBotMetadata(extra) { if (!extra || typeof extra !== 'object') throw new TypeError('botMetadata must be a plain object'); this.#botMetadataExtra = { ...this.#botMetadataExtra, ...extra }; return this }
|
|
228
|
+
addFooterSection(section) { if (!section || typeof section !== 'object') throw new TypeError('footer section must be a plain object'); this.#footerSections.push(section); return this }
|
|
229
|
+
clearFooterSections() { this.#footerSections = []; return this }
|
|
230
|
+
|
|
231
|
+
addText(text, opts = {}) { const { text: t, inline_entities } = extractIE(text); return this.#add(single(mkMarkdown(t, inline_entities)), null, opts) }
|
|
232
|
+
addCode(language, content, opts = {}) { const { codeBlocks, unified_codeBlock } = tokenizeCode(content, language); const submessage = { messageType: RichSubMessageType.AI_RICH_RESPONSE_CODE, codeMetadata: { codeLanguage: language, codeBlocks } }; return this.#add(single(mkCode(content, language, unified_codeBlock)), submessage, opts) }
|
|
233
|
+
addTable(rows, title = '', opts = {}) { return this.#add(single(mkTable(rows, title)), null, opts) }
|
|
234
|
+
addImage(input, opts = {}) { const resolved = this.#uploadMedia(input, 'image').then(url => single(mkImage(url))); return this.#add(resolved, null, opts) }
|
|
235
|
+
addVideo(url, { autoFill = false, mimeType = 'video/mp4', ...opts } = {}) {
|
|
236
|
+
const resolved = this.#uploadMedia(url, 'video').then(async finalUrl => { if (!autoFill) return single(mkVideo(finalUrl)); const buf = await normalizeToBuffer(finalUrl).catch(() => null); const duration = buf ? _mp4Duration(buf) : 0; const thumbnail = buf ? await _mp4Preview(buf, null, true) : null; return single({ __typename: 'GenAIImaginePrimitive', imagine_type: 'ANIMATE', status: { status: 'READY' }, media: { url: finalUrl, mime_type: mimeType, file_length: buf?.length ?? 0, duration }, thumbnail: thumbnail ? { raw_media: thumbnail } : undefined }) }); return this.#add(resolved, null, opts)
|
|
237
|
+
}
|
|
238
|
+
addGrid(items, opts = {}) { if (!Array.isArray(items) || items.length < 2) throw new Error('addGrid requires at least 2 items'); return this.#add(grid(items.map(i => mkImage(i))), null, opts) }
|
|
239
|
+
|
|
240
|
+
addVideoGrid(videos, opts = {}) {
|
|
241
|
+
if (!Array.isArray(videos) || videos.length < 2) throw new Error('addVideoGrid requires at least 2 videos')
|
|
242
|
+
const prims = videos.map((v, i) => {
|
|
243
|
+
const item = typeof v === 'string' ? {} : v
|
|
244
|
+
const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? '')
|
|
245
|
+
if (!url) throw new Error(`VideoGrid item ${i}: video requires a URL`)
|
|
246
|
+
return { __typename: 'GenAIVideoPrimitive', reels_url: url, reels_title: item.title, thumbnail_url: item.thumbnailUrl ?? item.thumbnail, creator: item.creator, avatar_url: item.avatarUrl, likes_count: item.likes, comments_count: item.comments, shares_count: item.shares, is_verified: item.isVerified, video_delivery_response: { progressive_urls: (item.progressiveUrls ?? []).map(u => ({ progressive_url: u, __typename: 'GenAIProgressiveUrlResponse' })), dash_manifests: (item.dashManifests ?? []).map(m => ({ manifest_xml: m, __typename: 'GenAIDashManifestResponse' })), __typename: 'GenAIVideoDeliveryResponse' } }
|
|
247
|
+
})
|
|
248
|
+
return this.#add(grid(prims), null, opts)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
addReels(reels, opts = {}) { const prims = reels.map(mkReel); return this.#add(prims.length === 1 ? single(prims[0]) : hscroll(prims), null, opts) }
|
|
252
|
+
addImagine(input = {}, opts = {}) { return this.#add(single(buildImaginePrimitive(input)), null, opts) }
|
|
253
|
+
addInlineImage(url, alignment = 'center', opts = {}) { return this.#add(single(mkInlineImage(url, alignment)), null, opts) }
|
|
254
|
+
addHtml(html, trustedSources = [], opts = {}) { return this.#add(single(mkHtml(html, trustedSources)), null, opts) }
|
|
255
|
+
|
|
256
|
+
addRichHtml(tabs, title = 'Preview', opts = {}) {
|
|
257
|
+
const tabItems = typeof tabs === 'string' ? [{ title: 'HTML', html: tabs }] : Array.isArray(tabs) ? tabs : [tabs]
|
|
258
|
+
const embeddedTabs = tabItems.map((tab, i) => ({ id: tab.id ?? `tab_${i}`, tab_header: tab.title ?? tab.tab_header ?? `HTML ${i + 1}`, sections: [{ __typename: 'GenAIUnifiedResponseSection', view_model: { __typename: 'GenAISingleLayoutViewModel', primitive: mkRichHtml(tab.html ?? '', tab.url ?? '', tab.trustedSources ?? []) } }], step_entries: [] }))
|
|
259
|
+
this.#embeddedScreens.push({ title, content: [{ __typename: 'FOAIDNixelButtonSheets', tabs: embeddedTabs }] })
|
|
260
|
+
return this.#add(single(mkMarkdown(`> ${title}`)), null, opts)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
addPost(data, opts = {}) { return this.#add(single(mkPost(data)), null, opts) }
|
|
264
|
+
addProduct(data, opts = {}) { return this.#add(single(mkProduct(data)), null, opts) }
|
|
265
|
+
addSource(sources, opts = {}) { const prims = sources.map(mkSearchResult); return this.#add(prims.length === 1 ? single(prims[0]) : vstack(prims), null, opts) }
|
|
266
|
+
addMap(locations, opts = {}) { const prims = locations.map(mkMap); return this.#add(prims.length === 1 ? single(prims[0]) : vstack(prims), null, opts) }
|
|
267
|
+
addWidget(ctas, title = '', opts = {}) { return this.#add(single(mkWidget(ctas, title)), null, opts) }
|
|
268
|
+
addFooterAction(data, opts = {}) { return this.#add(single(mkFooterAction(data)), null, opts) }
|
|
269
|
+
addSocialProfile(data, opts = {}) { const sections = mkSocialProfile(data); for (const s of sections) this.#push(s, null, opts.id ? `${opts.id}_${this.#nodes.length}` : null); return this }
|
|
270
|
+
addInstagramProfile(data, opts = {}) { return this.addSocialProfile({ platform: 'INSTAGRAM', entityType: 'IG_PROFILE', entityUrl: data.entityUrl ?? (data.username ? `https://www.instagram.com/${encodeURIComponent(data.username)}` : ''), ...data }, opts) }
|
|
271
|
+
addCopyAction(text, label, alignment = 'END', opts = {}) { return this.#add(addonAction('COPY_TO_CLIPBOARD', [mkMarkdown(String(label ?? text))], alignment), null, opts) }
|
|
272
|
+
addAddonAction(type, primitives, alignment = 'END', opts = {}) { return this.#add(addonAction(type, primitives, alignment), null, opts) }
|
|
273
|
+
addMetadata(text, opts = {}) { return this.#add(single(mkMeta(text)), null, opts) }
|
|
274
|
+
addFOAText(text, opts = {}) { return this.#add(single(mkFOA(text)), null, opts) }
|
|
275
|
+
addTip(text, opts = {}) { return this.#add(single(mkTip(text)), null, opts) }
|
|
276
|
+
addDivider(type = 'HORIZONTAL_LINE', opts = {}) { return this.#add(single(mkDivider(type)), null, opts) }
|
|
277
|
+
addSpacer(spacing = 2, opts = {}) { return this.#add(single(mkSpacer(spacing)), null, opts) }
|
|
278
|
+
addThinkingStatus(title, icon = 'THINKING', opts = {}) { return this.#add(single(mkThinking(title, icon)), null, opts) }
|
|
279
|
+
addProgressStatus(title, inProgress = true, opts = {}) { return this.#add(single(mkProgress(title, inProgress)), null, opts) }
|
|
280
|
+
addTask(data, opts = {}) { return this.#add(single(mkTask(data)), null, opts) }
|
|
281
|
+
addLatex(data, opts = {}) { const entity = mkLatex(data); const prim = mkMarkdown(`{{${entity.key}}}.{{/${entity.key}}}`, [entity]); return this.#add(single(prim), null, opts) }
|
|
282
|
+
addSuggest(prompts, scroll = false, opts = {}) { const prims = prompts.map(p => mkPill(typeof p === 'string' ? p : (p.text ?? p))); return this.#add(scroll ? hscroll(prims) : actionRow(prims), null, opts) }
|
|
283
|
+
addRichMap(mapOpts, opts = {}) { const { submessage, section } = mkRichMap(mapOpts); return this.#add(section, submessage, opts) }
|
|
284
|
+
addRichMenu(menuOpts, opts = {}) { const sections = mkRichMenu(menuOpts); sections.forEach(s => this.#push(s, null, null)); return this }
|
|
285
|
+
addDynamic(dynOpts, opts = {}) { const { submessage, section } = mkDynamic(dynOpts); return this.#add(section, submessage, opts) }
|
|
286
|
+
addLabel(text, variant = 'POSITIVE', opts = {}) { return this.#add(single(mkLabel(text, opts.backgroundColor, opts.textColor)), null, opts) }
|
|
287
|
+
addInlineLinks(links, opts = {}) { return this.#add(single(mkInlineLink(links)), null, opts) }
|
|
288
|
+
addSection(section, opts = {}) { return this.#add(section, null, opts) }
|
|
289
|
+
addEmbeddedScreen(screen) { this.#embeddedScreens.push(screen); return this }
|
|
290
|
+
// push raw sections + submessages directly — escape hatch for new primitives not yet wrapped
|
|
291
|
+
addRawSections(sections, submessages = []) { sections.forEach((s, i) => this.#push(s, submessages[i] ?? null)); return this }
|
|
292
|
+
|
|
293
|
+
addSuggestPrompts(suggestions, opts = {}) {
|
|
294
|
+
if (!Array.isArray(suggestions) || !suggestions.length) throw new Error('addSuggestPrompts requires at least one suggestion')
|
|
295
|
+
this.#suggestedPrompts = { suggestedPrompts: suggestions.map(String), ...(opts.selectedPromptIndex != null ? { selectedPromptIndex: opts.selectedPromptIndex } : {}), ...(opts.selectedPromptId != null ? { selectedPromptId: String(opts.selectedPromptId) } : {}) }
|
|
296
|
+
return this.#add(actionRow(suggestions.map(s => mkPill(s))), null, opts)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
addSources(sources, opts = {}) {
|
|
300
|
+
if (!Array.isArray(sources) || !sources.length) throw new Error('addSources requires at least one source')
|
|
301
|
+
this.#botSources = sources.map((s, i) => ({ provider: s.provider ?? 0, thumbnailCdnUrl: s.thumbnailCdnUrl ?? s.thumbnail ?? '', sourceProviderUrl: s.sourceProviderUrl ?? s.url ?? '', sourceQuery: s.sourceQuery ?? s.query ?? '', faviconCdnUrl: s.faviconCdnUrl ?? s.favicon ?? '', citationNumber: s.citationNumber ?? i + 1, sourceTitle: s.sourceTitle ?? s.title ?? '' }))
|
|
302
|
+
const prims = sources.map(mkSearchResult)
|
|
303
|
+
return this.#add(prims.length === 1 ? single(prims[0]) : vstack(prims), null, opts)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
addVerticalAlbum(items, opts = {}) {
|
|
307
|
+
if (!Array.isArray(items) || items.length < 2) throw new Error('addVerticalAlbum requires at least 2 items')
|
|
308
|
+
const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
|
|
309
|
+
const primitives = items.map((item, i) => {
|
|
310
|
+
const kind = item?.type || (item?.video ? 'video' : 'image')
|
|
311
|
+
if (kind === 'video') {
|
|
312
|
+
const v = item.video || item.data || item
|
|
313
|
+
return buildImaginePrimitive({ mediaType: 'video', url: typeof v === 'string' ? v : (v?.url || ''), mimeType: v?.mimeType ?? v?.mime_type ?? 'video/mp4', fileLength: v?.fileLength || 0, duration: v?.duration || 0, status: 'READY' })
|
|
314
|
+
}
|
|
315
|
+
const img = typeof (item?.image || item) === 'string' ? { url: item?.image || item } : (item?.image || item || {})
|
|
316
|
+
const url = img?.imageHighResUrl ?? img?.highResUrl ?? img?.fullUrl ?? img?.imagePreviewUrl ?? img?.previewUrl ?? img?.url ?? ''
|
|
317
|
+
if (!url) throw new Error(`VerticalAlbum item ${i}: image requires a URL`)
|
|
318
|
+
return { __typename: 'GenAIImagePrimitive', preview_image: { url, url_fallback: url, mime_type: img.mimeType || 'image/jpeg', expiration_timestamp_ms: expiration, width: img.width || 600, height: img.height || 400 }, full_image: { url, url_fallback: url, mime_type: img.mimeType || 'image/jpeg', expiration_timestamp_ms: expiration, width: img.width || 600, height: img.height || 400 }, dark_mode_preview_image: { url, url_fallback: url, mime_type: img.mimeType || 'image/jpeg', expiration_timestamp_ms: expiration, width: img.width || 600, height: img.height || 400 }, dark_mode_full_image: { url, url_fallback: url, mime_type: img.mimeType || 'image/jpeg', expiration_timestamp_ms: expiration, width: img.width || 600, height: img.height || 400 }, asset_query_status: 'FETCHED', display_mode: 'FULL_WIDTH', full_width: true }
|
|
319
|
+
})
|
|
320
|
+
return this.#add({ view_model: { primitives, display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIVStackLayoutViewModel' } }, null, opts)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
addPttTranscript(transcript, opts = {}) {
|
|
324
|
+
if (!transcript) throw new Error('addPttTranscript requires a transcript string')
|
|
325
|
+
this.#pttTranscript = String(transcript)
|
|
326
|
+
return this.#add(single(mkMeta(`🎤 _${transcript}_`)), null, opts)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ─── Node introspection & mutation ────────────────────────────────────────
|
|
330
|
+
hasId(id) { return typeof id === 'string' && id in this.#idIndex }
|
|
331
|
+
getIds() { return this.#nodes.map(n => n.id) }
|
|
332
|
+
peek(id) { const idx = this.#idIndex[id]; return idx !== undefined ? { ...this.#nodes[idx] } : null }
|
|
333
|
+
assignId(index, newId) {
|
|
334
|
+
if (!Number.isInteger(index) || index < 0 || index >= this.#nodes.length) throw new RangeError(`Node index ${index} is out of range`)
|
|
335
|
+
if (newId in this.#idIndex) throw new Error(`Id "${newId}" already exists`)
|
|
336
|
+
const node = this.#nodes[index]
|
|
337
|
+
delete this.#idIndex[node.id]
|
|
338
|
+
node.id = newId
|
|
339
|
+
this.#idIndex[newId] = index
|
|
340
|
+
return this
|
|
341
|
+
}
|
|
342
|
+
delete(id) {
|
|
343
|
+
const idx = this.#idIndex[id]
|
|
344
|
+
if (idx === undefined) throw new Error(`Node id "${id}" not found`)
|
|
345
|
+
this.#nodes.splice(idx, 1)
|
|
346
|
+
this.#idIndex = {}
|
|
347
|
+
this.#nodes.forEach((n, i) => { this.#idIndex[n.id] = i })
|
|
348
|
+
return this
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
loadFrom(msg) {
|
|
352
|
+
const rich = msg?.botForwardedMessage?.message?.richResponseMessage ?? msg?.richResponseMessage
|
|
353
|
+
if (!rich) throw new Error('Not an AIRich message')
|
|
354
|
+
const mci = msg?.messageContextInfo
|
|
355
|
+
if (mci?.botMetadata?.messageDisclaimerText) this.#title = mci.botMetadata.messageDisclaimerText
|
|
356
|
+
if (mci?.botMetadata?.verificationMetadata) this.#signedVerificationMetadata = mci.botMetadata.verificationMetadata
|
|
357
|
+
if (rich.unifiedResponse?.data) {
|
|
358
|
+
try {
|
|
359
|
+
const parsed = JSON.parse(Buffer.isBuffer(rich.unifiedResponse.data) ? rich.unifiedResponse.data.toString() : Buffer.from(rich.unifiedResponse.data, 'base64').toString())
|
|
360
|
+
; (parsed.sections ?? []).forEach((s, i) => { const sub = rich.submessages?.[i] ?? null; this.#nodes.push({ id: `loaded_${i}`, section: s, submessage: sub }); this.#idIndex[`loaded_${i}`] = i })
|
|
361
|
+
} catch { }
|
|
362
|
+
}
|
|
363
|
+
return this
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async build(jid, opts = {}) {
|
|
367
|
+
const { botJid = this.#botJid, messageId = generateMessageIDV2(), quoted, quotedParticipant } = opts
|
|
368
|
+
const resolved = await waitAllPromises(this.#nodes)
|
|
369
|
+
const sections = resolved.map(n => n.section)
|
|
370
|
+
const submessages = resolved.map(n => n.submessage).filter(Boolean)
|
|
371
|
+
const embeddedScreens = await waitAllPromises(this.#embeddedScreens)
|
|
372
|
+
const responseId = this.#dynamic ? crypto.randomUUID() : (this.#responseId ?? crypto.randomUUID())
|
|
373
|
+
const footerSections = await waitAllPromises(this.#footerSections)
|
|
374
|
+
const unifiedData = JSON.stringify({ response_id: responseId, ...this.#responseMeta, sections, ...(footerSections.length ? { footer_sections: footerSections } : {}), ...(embeddedScreens.length ? { embedded_screens: embeddedScreens } : {}) })
|
|
375
|
+
const contextInfo = { isForwarded: true, forwardOrigin: 4, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, participant: '13135550002@s.whatsapp.net', remoteJid: 'status@broadcast', quotedMessage: { protocolMessage: { type: 25 } }, ...this.#contextInfoExtra, ...(quoted ? { quotedMessage: quoted.message, stanzaId: quoted.key?.id, participant: quotedParticipant ?? quoted.key?.participant ?? quoted.key?.remoteJid, remoteJid: quoted.key?.remoteJid } : {}) }
|
|
376
|
+
const verification = this.#signedVerificationMetadata ?? generateVerificationMetadata()
|
|
377
|
+
const { sources, mediaDetailsMetadataList } = buildAdditionalBotMetadata(submessages)
|
|
378
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages, unifiedResponse: { data: Buffer.from(unifiedData) }, originalRecipientMetadata: { data: Buffer.from(unifiedData) }, contextInfo })
|
|
379
|
+
const message = wrapToBotForwardedMessage(richResponseMessage, verification)
|
|
380
|
+
const botMeta = message.messageContextInfo.botMetadata
|
|
381
|
+
botMeta.botResponseId = responseId
|
|
382
|
+
botMeta.deviceListMetadata = {}
|
|
383
|
+
botMeta.deviceListMetadataVersion = 2
|
|
384
|
+
botMeta.supportPayload = BIZ_BOT_SUPPORT
|
|
385
|
+
if (this.#title) botMeta.messageDisclaimerText = this.#title
|
|
386
|
+
if (sources.length || this.#botSources?.length) botMeta.richResponseSourcesMetadata = { sources: this.#botSources ?? sources }
|
|
387
|
+
if (mediaDetailsMetadataList.length) botMeta.unifiedResponseMutation = { mediaDetailsMetadataList }
|
|
388
|
+
if (this.#suggestedPrompts) botMeta.suggestedPromptMetadata = this.#suggestedPrompts
|
|
389
|
+
if (this.#pttTranscript) botMeta.pttPromptMetadata = { transcript: this.#pttTranscript }
|
|
390
|
+
if (Object.keys(this.#botMetadataExtra).length) Object.assign(botMeta, this.#botMetadataExtra)
|
|
391
|
+
botMeta.capabilities = { richResponseUnifiedResponse: true, richResponseEmbeddedScreens: true, richResponseInlineLinksEnabled: true, richResponseUrBloksEnabled: true, richResponseUrImagine: true, richResponseUrReasoning: true }
|
|
392
|
+
return await generateWAMessageFromContent(jid, message, { userJid: this.#client.user?.id, messageId })
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async send(jid, opts = {}) {
|
|
396
|
+
const { additionalNodes = [], ...buildOpts } = opts
|
|
397
|
+
const msg = await this.build(jid, buildOpts)
|
|
398
|
+
const bizNode = getBizBinaryNode(msg.message)
|
|
399
|
+
const relayFn = this.#client.relayRichMessage ?? this.#client.relayMessage
|
|
400
|
+
await relayFn(jid, msg, {
|
|
401
|
+
...opts,
|
|
402
|
+
additionalNodes: [...(bizNode ? [bizNode] : []), ...(opts.additionalNodes ?? [])]
|
|
403
|
+
})
|
|
404
|
+
return msg
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async sendEdit(jid, targetId, opts = {}) {
|
|
408
|
+
if (!targetId) throw new Error('targetId is required for sendEdit')
|
|
409
|
+
const msg = await this.build(jid, opts)
|
|
410
|
+
const editMsg = { protocolMessage: { key: { remoteJid: jid, fromMe: true, id: targetId }, type: 14, editedMessage: msg.message } }
|
|
411
|
+
const waMsg = await generateWAMessageFromContent(jid, editMsg, { userJid: this.#client.user?.id })
|
|
412
|
+
await this.#client.relayMessage(jid, waMsg.message, { messageId: waMsg.key.id })
|
|
413
|
+
return waMsg
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function aiRichFromObject(client, jid, data, opts = {}) {
|
|
418
|
+
const { _r, ...sendOpts } = opts
|
|
419
|
+
const r = _r ?? new AIRich(client, { botJid: data.botJid })
|
|
420
|
+
const isChild = !!_r
|
|
421
|
+
if (!isChild && (data.title ?? data.disclaimerText)) r.setTitle(data.title ?? data.disclaimerText)
|
|
422
|
+
if (data.parts) {
|
|
423
|
+
for (const p of data.parts) {
|
|
424
|
+
const code = Array.isArray(p.code) ? p.code.map(c => c.codeContent ?? c.content ?? '').join('\n') : p.code
|
|
425
|
+
const table = Array.isArray(p.table) ? p.table.map(r => Array.isArray(r) ? r : (r.items ?? r.cells ?? [])) : p.table
|
|
426
|
+
aiRichFromObject(client, jid, { ...p, ...(code ? { code } : {}), ...(table ? { table } : {}) }, { ...sendOpts, _r: r })
|
|
427
|
+
}
|
|
428
|
+
return isChild ? r : r.send(jid, sendOpts)
|
|
429
|
+
}
|
|
430
|
+
if (data.texts) data.texts.forEach(t => r.addText(t))
|
|
431
|
+
else if (data.text) r.addText(data.text)
|
|
432
|
+
if (data.codes) data.codes.forEach(c => r.addCode(c.language ?? data.language ?? '', c.code ?? c.content))
|
|
433
|
+
else if (data.code) { const c = typeof data.code === 'string' ? data.code : (data.code.code ?? data.code.content); const lang = typeof data.code === 'string' ? (data.language ?? '') : (data.code.language ?? data.language ?? ''); r.addCode(lang, c) }
|
|
434
|
+
if (data.table) r.addTable(data.table, data.tableTitle)
|
|
435
|
+
else if (data.headers && data.rows) r.addTable([data.headers, ...data.rows], data.tableTitle)
|
|
436
|
+
if (data.images) data.images.forEach(img => r.addImage(img.url ?? img))
|
|
437
|
+
if (data.image) r.addImage(data.image.url ?? data.image)
|
|
438
|
+
if (data.grid) r.addGrid(data.grid)
|
|
439
|
+
if (data.videoGrid) r.addVideoGrid(data.videoGrid)
|
|
440
|
+
if (data.reels) r.addReels(data.reels)
|
|
441
|
+
if (data.imagine) r.addImagine(typeof data.imagine === 'object' ? data.imagine : { url: data.imagine })
|
|
442
|
+
if (data.sources) r.addSource(data.sources)
|
|
443
|
+
if (data.richMapSources) r.addSources(data.richMapSources)
|
|
444
|
+
else if (data.botSources) r.addSources(data.botSources)
|
|
445
|
+
if (data.richMap) r.addRichMap(data.richMap)
|
|
446
|
+
if (data.dynamic) r.addDynamic(data.dynamic)
|
|
447
|
+
if (data.suggestPrompts) r.addSuggestPrompts(Array.isArray(data.suggestPrompts) ? data.suggestPrompts : data.suggestPrompts.suggestions, data.suggestPrompts)
|
|
448
|
+
if (data.pttTranscript) r.addPttTranscript(data.pttTranscript)
|
|
449
|
+
if (data.instagramProfile) r.addInstagramProfile(data.instagramProfile)
|
|
450
|
+
if (data.latex) { if (data.latexText) r.addText(data.latexText); (Array.isArray(data.latex) ? data.latex : [data.latex]).forEach(l => r.addLatex({ expression: l.expression ?? l.latexExpression ?? '', imageUrl: l.url ?? l.imageUrl ?? '', width: l.width ?? 400, height: l.height ?? 200 })) }
|
|
451
|
+
if (data.html) r.addHtml(data.html, data.trustedSources)
|
|
452
|
+
if (data.richHtml) r.addRichHtml(data.richHtml, data.richHtmlTitle)
|
|
453
|
+
if (data.copyText) r.addCopyAction(data.copyText, data.copyLabel, data.copyAlignment)
|
|
454
|
+
if (data.social) r.addSocialProfile(data.social)
|
|
455
|
+
if (data.suggest) r.addSuggest(data.suggest)
|
|
456
|
+
if (data.tip) r.addTip(data.tip)
|
|
457
|
+
if (data.metadata ?? data.meta) r.addMetadata(data.metadata ?? data.meta)
|
|
458
|
+
if (data.footer) r.addFOAText(data.footer)
|
|
459
|
+
if (data.rawSections) r.addRawSections(data.rawSections, data.rawSubmessages)
|
|
460
|
+
return isChild ? r : r.send(jid, sendOpts)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const stripDevice = jid => String(jid || '').replace(/:\d+$/, '')
|
|
464
|
+
|
|
465
|
+
const collectMetaAIBotJids = async (sock, jid, botUser) => {
|
|
466
|
+
const candidates = new Set([botUser])
|
|
467
|
+
if (!isJidGroup(jid)) return candidates
|
|
468
|
+
const botNumber = jidNormalizedUser(botUser).split('@')[0]
|
|
469
|
+
try {
|
|
470
|
+
const meta = await sock.groupMetadata(jid)
|
|
471
|
+
for (const p of meta.participants || []) {
|
|
472
|
+
const idNum = jidNormalizedUser(p.id).split('@')[0]
|
|
473
|
+
const pnNum = p.phoneNumber ? jidNormalizedUser(p.phoneNumber).split('@')[0] : undefined
|
|
474
|
+
if (pnNum === botNumber || idNum === botNumber || isJidMetaAI(p.id)) candidates.add(p.id)
|
|
475
|
+
}
|
|
476
|
+
} catch { }
|
|
477
|
+
return candidates
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const isMetaAIResponse = (msg, chatJid, promptId, botJids) => {
|
|
481
|
+
if (!msg?.key || msg.key.fromMe || msg.key.remoteJid !== chatJid) return false
|
|
482
|
+
const sender = stripDevice(msg.key.participant || msg.key.remoteJid)
|
|
483
|
+
if (isJidMetaAI(sender)) return true
|
|
484
|
+
for (const b of botJids) if (jidNormalizedUser(stripDevice(b)) === jidNormalizedUser(sender)) return true
|
|
485
|
+
if (promptId) { const inner = msg.message ? Object.values(msg.message)[0] : undefined; const stanzaId = inner?.contextInfo?.stanzaId || msg.message?.contextInfo?.stanzaId; if (stanzaId === promptId) return true }
|
|
486
|
+
return false
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const q = quoted => quoted ? { quoted } : {}
|
|
490
|
+
|
|
491
|
+
// ─── attachAIRich ─────────────────────────────────────────────────────────────
|
|
492
|
+
// Attaches all AIRich, meta, bot, and relay methods to result, then returns the
|
|
493
|
+
// fuzzy-proxy-wrapped result. This is the only export zervonex-handler.js needs.
|
|
494
|
+
export function attachAIRich(result, config) {
|
|
495
|
+
const sock = result
|
|
496
|
+
|
|
497
|
+
const relayRichMessage = async (jid, fullMsg, options = {}) => {
|
|
498
|
+
const relayOpts = { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, ...(options.relayOptions || {}) }
|
|
499
|
+
await sock.relayMessage(jid, fullMsg.message, relayOpts)
|
|
500
|
+
const hasRich = !!fullMsg.message?.botForwardedMessage?.message?.richResponseMessage || !!fullMsg.message?.interactiveMessage?.bloksWidget
|
|
501
|
+
const shouldEdit = options.bypassDownload !== false && (options.forceRichEdit || hasRich)
|
|
502
|
+
if (shouldEdit) {
|
|
503
|
+
try {
|
|
504
|
+
const editContent = proto.Message.fromObject({ botForwardedMessage: { message: { protocolMessage: { key: { remoteJid: jid, fromMe: true, id: fullMsg.key.id }, type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT, editedMessage: fullMsg.message } } } })
|
|
505
|
+
const editMsg = await generateWAMessageFromContent(jid, editContent, { userJid: sock.user?.id, messageId: generateMessageIDV2(sock.user?.id || jid) })
|
|
506
|
+
await sock.relayMessage(jid, editMsg.message, { ...relayOpts, messageId: editMsg.key.id })
|
|
507
|
+
} catch { /* card already arrived, just behind download prompt */ }
|
|
508
|
+
}
|
|
509
|
+
return fullMsg
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
result.relayRichMessage = relayRichMessage
|
|
513
|
+
result.airich = opts => new AIRich(result, opts)
|
|
514
|
+
|
|
515
|
+
result.captureAiRich = msg => {
|
|
516
|
+
const rich = msg?.botForwardedMessage?.message?.richResponseMessage ?? msg?.richResponseMessage
|
|
517
|
+
if (!rich?.unifiedResponse?.data) return null
|
|
518
|
+
return { submessages: rich.submessages ?? [], sections: JSON.parse(Buffer.isBuffer(rich.unifiedResponse.data) ? rich.unifiedResponse.data.toString() : Buffer.from(rich.unifiedResponse.data, 'base64').toString()), contextInfo: rich.contextInfo ?? {}, messageType: rich.messageType ?? proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD }
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
result.relayAiRich = (jid, captured, opts = {}) => {
|
|
522
|
+
const r = new AIRich(result)
|
|
523
|
+
if (captured.sections?.response_id) r.setResponseId(captured.sections.response_id)
|
|
524
|
+
return r.loadFrom({ botForwardedMessage: { message: { richResponseMessage: { submessages: captured.submessages, unifiedResponse: { data: Buffer.from(JSON.stringify(captured.sections)) }, contextInfo: captured.contextInfo, messageType: captured.messageType } } } }).send(jid, opts)
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
result.sendRichFromObject = (jid, data, opts = {}) => aiRichFromObject(result, jid, data, opts)
|
|
528
|
+
result.sendRichMessage = (jid, data, quoted, opts = {}) => result.sendMessage(jid, { aiRich: data }, { ...q(quoted), ...opts })
|
|
529
|
+
result.sendCodeBlock = (jid, code, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { code, language: opts.language ?? 'javascript', title: opts.title } }, q(quoted))
|
|
530
|
+
result.sendCodeBlockV2 = (jid, code, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { text: opts.text, code, language: opts.language ?? '', title: opts.title } }, q(quoted))
|
|
531
|
+
result.sendTable = (jid, title, headers, rows, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title, table: [headers, ...rows] } }, q(quoted))
|
|
532
|
+
result.sendTableV2 = (jid, tableArray, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { text: opts.text, title: opts.headerText, table: tableArray } }, q(quoted))
|
|
533
|
+
result.sendList = (jid, title, items, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title, table: [['Key', 'Value'], ...items] } }, q(quoted))
|
|
534
|
+
result.sendLink = (jid, text, links, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title: opts.headerText, text, sources: links.map(url => ({ url, title: url, subtitle: new URL(url).hostname })) } }, q(quoted))
|
|
535
|
+
result.sendLinkV2 = (jid, text, links, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title: opts.headerText, text, sources: links } }, q(quoted))
|
|
536
|
+
result.sendLatex = (jid, expressions, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { text: opts.text, title: opts.headerText, latex: expressions } }, q(quoted))
|
|
537
|
+
result.sendRichTable = async (jid, title, headers, rows, quoted, opts = {}) => { const { message, messageId } = generateTableContent(title, headers, rows, quoted, opts); return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts) }
|
|
538
|
+
result.sendRichList = async (jid, title, items, quoted, opts = {}) => { const { message, messageId } = generateListContent(title, items, quoted, opts); return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts) }
|
|
539
|
+
result.sendRichCode = async (jid, code, quoted, opts = {}) => { const { message, messageId } = generateCodeBlockContent(code, quoted, opts); return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts) }
|
|
540
|
+
result.sendRichLatex = async (jid, quoted, opts = {}) => { const { message, messageId } = generateLatexContent(quoted, { expressions: [], ...opts }); return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts) }
|
|
541
|
+
result.sendRichLabel = (jid, text, options = {}) => { const r = new AIRich(result); r.addLabel(text, options.variant, options); return r.send(jid, options) }
|
|
542
|
+
result.sendInlineLinks = (jid, links, options = {}) => { const r = new AIRich(result); r.addInlineLinks(links); return r.send(jid, options) }
|
|
543
|
+
result.sendVerticalAlbum = (jid, items, options = {}) => { const r = new AIRich(result); r.addVerticalAlbum(items); return r.send(jid, options) }
|
|
544
|
+
result.sendRichLatexImage = async (jid, opts = {}) => {
|
|
545
|
+
const { text, expressions = [], headerText, footer } = opts
|
|
546
|
+
const rendered = expressions.map(expr => { const latex = expr.latexExpression || expr.expression || expr; const url = `https://latex.codecogs.com/png.latex?${encodeURIComponent(latex).replace(/'/g, '%27')}`; return { latexExpression: latex, url, width: expr.width || 400, height: expr.height || 100 } })
|
|
547
|
+
const { message, messageId } = generateLatexContent(null, { text, expressions: rendered, headerText, footer })
|
|
548
|
+
return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts)
|
|
549
|
+
}
|
|
550
|
+
result.captureAndResendRichResponse = async (jid, metaAiMsg, quoted, opts = {}) => {
|
|
551
|
+
const captured = captureUnifiedResponse(metaAiMsg)
|
|
552
|
+
if (!captured) throw new Error('captureAndResendRichResponse: no unifiedResponse data in message')
|
|
553
|
+
const { message, messageId } = generateUnifiedResponseContent(quoted, captured)
|
|
554
|
+
return relayRichMessage(jid, await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || messageId }), opts)
|
|
555
|
+
}
|
|
556
|
+
result.sendBotPlanning = async (jid, content = {}, opts = {}) => {
|
|
557
|
+
const { text = 'Execution plan', steps = [], queryPlan = true, botJid = META_AI_BOT_JID } = content
|
|
558
|
+
const submessages = [{ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: text }, ...steps.map(s => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: typeof s === 'string' ? s : `${s.title || s.name || 'Step'}${s.body ? `: ${s.body}` : ''}` }))]
|
|
559
|
+
const wrapped = buildBotRichResponse({ botJid, submessages, capabilities: [BotCapabilityType.AGENTIC_PLANNING, ...(queryPlan ? [BotCapabilityType.QUERY_PLAN] : [])] })
|
|
560
|
+
const full = await generateWAMessageFromContent(jid, wrapped, { userJid: sock.user?.id, messageId: opts.messageId || generateMessageIDV2(sock.user?.id) })
|
|
561
|
+
return relayRichMessage(jid, full, opts)
|
|
562
|
+
}
|
|
563
|
+
result.sendBotPlan = async (jid, content = {}, opts = {}) => {
|
|
564
|
+
const { text = 'Execution plan', title = 'Execution plan', steps = [], estimatedCompletionTime, botJid = META_AI_BOT_JID } = content
|
|
565
|
+
if (!Array.isArray(steps) || steps.length === 0) throw new Error('sendBotPlan requires at least one step')
|
|
566
|
+
const statusEnum = proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.PlanningStepStatus
|
|
567
|
+
const normalizedSteps = steps.map((s, i) => ({ statusTitle: String(s.title || s.name || `Step ${i + 1}`), statusBody: String(s.body || s.description || ''), status: s.status === 'executing' ? statusEnum.EXECUTING : (s.status === 'finished' || s.status === 'completed') ? statusEnum.FINISHED : statusEnum.PLANNED, isReasoning: s.isReasoning === true, isEnhancedSearch: s.isEnhancedSearch === true }))
|
|
568
|
+
const wrapped = { messageContextInfo: { botMetadata: { capabilityMetadata: { capabilities: [proto.BotCapabilityMetadata.BotCapabilityType.AGENTIC_PLANNING, proto.BotCapabilityMetadata.BotCapabilityType.QUERY_PLAN] }, progressIndicatorMetadata: { progressDescription: title, stepsMetadata: normalizedSteps, ...(estimatedCompletionTime ? { estimatedCompletionTime } : {}) } } }, botForwardedMessage: { message: { richResponseMessage: { messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages: [{ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: text }], contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } } } } }
|
|
569
|
+
const full = await generateWAMessageFromContent(jid, wrapped, { userJid: sock.user?.id, messageId: opts.messageId || generateMessageIDV2(sock.user?.id) })
|
|
570
|
+
await sock.relayMessage(jid, full.message, { messageId: full.key.id })
|
|
571
|
+
return full
|
|
572
|
+
}
|
|
573
|
+
result.replayPlanning = (jid, steps, finalContent, opts) => replayPlanning(result, jid, steps, finalContent, opts)
|
|
574
|
+
result.replayPlanningOnly = (jid, steps, opts) => replayPlanningOnly(result, jid, steps, opts)
|
|
575
|
+
result.metaTyping = (jid, opts) => metaTyping(result, jid, opts)
|
|
576
|
+
result.sendMetaComposited = (jid, content, opts) => sendMetaComposited(result, jid, content, opts)
|
|
577
|
+
result.buildReasoningSteps = buildReasoningSteps
|
|
578
|
+
result.buildSearchSteps = buildSearchSteps
|
|
579
|
+
result.mixedSteps = mixedSteps
|
|
580
|
+
result.buildSteps = buildSteps
|
|
581
|
+
result.PlanningStepStatus = PlanningStepStatus
|
|
582
|
+
result.sendMetaAI = async (a, b, c = {}) => {
|
|
583
|
+
let text, opts = c, yourJid
|
|
584
|
+
if (typeof b === 'string') { text = b; yourJid = a } else { text = a; opts = b || {}; yourJid = opts.yourJid || '' }
|
|
585
|
+
const jid = opts.jid || META_AI_BOT_JID
|
|
586
|
+
const threadId = opts.threadId || generateMessageIDV2(yourJid)
|
|
587
|
+
const now = Date.now()
|
|
588
|
+
const senderKeyHash = opts.senderKeyHash || randomBytes(8).toString('base64')
|
|
589
|
+
const message = {
|
|
590
|
+
extendedTextMessage: proto.Message.ExtendedTextMessage.fromObject({ text, previewType: 'NONE', contextInfo: proto.ContextInfo.fromObject({ botMessageSharingInfo: { botEntryPointOrigin: 'FAVICON', forwardScore: 0 } }), inviteLinkGroupTypeV2: 'DEFAULT' }),
|
|
591
|
+
messageContextInfo: proto.MessageContextInfo.fromObject({ deviceListMetadata: { senderKeyHash, senderTimestamp: opts.senderTimestamp || String(Math.floor(now / 1000)) }, deviceListMetadataVersion: 2, messageSecret: opts.messageSecret || randomBytes(32), botMetadata: { botModeSelectionMetadata: { overrideMode: [0] }, botThreadInfo: { serverInfo: { title: text.substring(0, 50) }, clientInfo: { type: 'DEFAULT' } }, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA, ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {}) }, threadId: [{ threadType: 'AI_THREAD', threadKey: { remoteJid: '0002@s.whatsapp.net', fromMe: true, id: threadId } }] })
|
|
592
|
+
}
|
|
593
|
+
const msgId = generateMessageIDV2(yourJid)
|
|
594
|
+
await sock.relayMessage(jid, message, { messageId: msgId, ...(opts.quoted ? { quoted: opts.quoted } : {}) })
|
|
595
|
+
return msgId
|
|
596
|
+
}
|
|
597
|
+
result.aiPrompt = async (jid, prompt, options = {}) => {
|
|
598
|
+
const { timeout = 60_000, onPartial, botUser = META_AI_BOT_JID, mentions = [], ...sendOpts } = options
|
|
599
|
+
if (!jid || typeof prompt !== 'string' || !prompt.trim()) throw new Error('aiPrompt requires a chat JID and a non-empty prompt')
|
|
600
|
+
const botJids = await collectMetaAIBotJids(result, jid, botUser)
|
|
601
|
+
const allMentions = [...new Set([...mentions, ...botJids])]
|
|
602
|
+
return new Promise((resolve, reject) => {
|
|
603
|
+
let promptId, settled = false
|
|
604
|
+
const cleanup = () => { clearTimeout(timer); sock.ev.off('messages.upsert', onUpsert); if (onPartial) sock.ev.off('messages.update', onUpdate) }
|
|
605
|
+
const settle = (fn, val) => { if (settled) return; settled = true; cleanup(); fn(val) }
|
|
606
|
+
const timer = setTimeout(() => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms in ${jid}`)), timeout)
|
|
607
|
+
const onUpsert = ({ messages }) => { for (const msg of messages) if (isMetaAIResponse(msg, jid, promptId, botJids)) { settle(resolve, msg); return } }
|
|
608
|
+
const onUpdate = ({ updates }) => { if (!onPartial) return; for (const u of updates) { if (!u.key || u.key.fromMe || u.key.remoteJid !== jid) continue; const sender = jidNormalizedUser(stripDevice(u.key.participant || u.key.remoteJid)); const isBot = isJidMetaAI(sender) || [...botJids].some(b => jidNormalizedUser(stripDevice(b)) === sender); if (isBot && u.message) onPartial(u.message, u.key) } }
|
|
609
|
+
sock.ev.on('messages.upsert', onUpsert)
|
|
610
|
+
if (onPartial) sock.ev.on('messages.update', onUpdate)
|
|
611
|
+
; (async () => {
|
|
612
|
+
try {
|
|
613
|
+
const content = { text: prompt, ...(isJidGroup(jid) ? { mentions: allMentions } : {}), ...sendOpts }
|
|
614
|
+
const full = await generateWAMessage(jid, content, { userJid: sock.user?.id, messageId: sendOpts.messageId || generateMessageIDV2(sock.user?.id) })
|
|
615
|
+
await sock.relayMessage(jid, full.message, { messageId: full.key.id })
|
|
616
|
+
if (config.emitOwnEvents) process.nextTick(() => sock.ev.emit('messages.upsert', { messages: [full], type: 'append' }))
|
|
617
|
+
promptId = full.key.id
|
|
618
|
+
} catch (err) { settle(reject, err) }
|
|
619
|
+
})()
|
|
620
|
+
})
|
|
621
|
+
}
|
|
622
|
+
result.sendAsMimic = async (jid, content, mimicJid, options = {}) => {
|
|
623
|
+
if (!options.admin && !options.mimicPermission) throw new Error('sendAsMimic requires admin: true')
|
|
624
|
+
const msgId = generateMessageIDV2(sock.user?.id)
|
|
625
|
+
const full = await generateWAMessageFromContent(jid, content, { userJid: sock.user?.id, ...options })
|
|
626
|
+
full.key = { remoteJid: jid, fromMe: false, id: msgId, participant: mimicJid }
|
|
627
|
+
await sock.relayMessage(jid, full.message, { messageId: msgId, ...(options.additionalAttributes ? { additionalAttributes: options.additionalAttributes } : {}) })
|
|
628
|
+
return full
|
|
629
|
+
}
|
|
630
|
+
result.sendStatus = async (content, options = {}) => {
|
|
631
|
+
const provided = options.statusJidList || content?.statusJidList || sock.statusJidList || []
|
|
632
|
+
if (!provided.length) throw new Error('sendStatus requires statusJidList')
|
|
633
|
+
return result.sendMessage(STATUS_JID, { ...content, status: true }, { ...options, broadcast: true, statusJidList: provided })
|
|
634
|
+
}
|
|
635
|
+
result.sendBotToolResult = async (jid, content = {}, opts = {}) => {
|
|
636
|
+
const { text = 'Tool result', toolCallId = `tool-${Date.now()}`, resolutionData, resolutionDataSerialized, botJid = META_AI_BOT_JID } = content
|
|
637
|
+
const wrapped = buildBotRichResponse({ text, botJid, capabilities: [BotCapabilityType.AGENTIC_PLANNING, BotCapabilityType.QUERY_PLAN], botMetadata: { resolvedToolCallMetadata: { toolCallId, resolutionDataSerialized: resolutionDataSerialized ?? JSON.stringify(resolutionData ?? {}) } } })
|
|
638
|
+
const full = await generateWAMessageFromContent(jid, wrapped, { userJid: sock.user?.id, messageId: opts.messageId || generateMessageIDV2(sock.user?.id) })
|
|
639
|
+
return relayRichMessage(jid, full, opts)
|
|
640
|
+
}
|
|
641
|
+
result.sendWhatsAppFlow = async (jid, flow, options = {}) => {
|
|
642
|
+
const { text, footer, image, caption, ...flowOpts } = flow || {}
|
|
643
|
+
const btn = makeWhatsAppFlowButton(flowOpts)
|
|
644
|
+
const content = image ? { image, caption: caption || text || flowOpts.cta } : { text: text || flowOpts.cta || '' }
|
|
645
|
+
return result.sendMessage(jid, { ...content, ...(footer ? { footer } : {}), nativeFlow: [btn] }, options)
|
|
646
|
+
}
|
|
647
|
+
result.sendRichMap = (jid, mapOpts, options = {}) => { const r = new AIRich(result); r.addRichMap(mapOpts); return r.send(jid, options) }
|
|
648
|
+
result.sendDynamic = (jid, dynOpts, options = {}) => { const r = new AIRich(result); r.addDynamic(dynOpts); return r.send(jid, options) }
|
|
649
|
+
result.sendBotPromptSuggestions = (jid, content = {}, options = {}) => { const { text, suggestions = [] } = content; const r = new AIRich(result); if (text) r.addText(text); r.addSuggestPrompts(suggestions, content); return r.send(jid, options) }
|
|
650
|
+
result.sendBotSources = (jid, content = {}, options = {}) => { const { text, sources = [] } = content; const r = new AIRich(result); if (text) r.addText(text); r.addSources(sources); return r.send(jid, options) }
|
|
651
|
+
result.sendBotPttTranscript = (jid, content = {}, options = {}) => { const { text, transcript } = content; const r = new AIRich(result); if (text) r.addText(text); r.addPttTranscript(transcript); return r.send(jid, options) }
|
|
652
|
+
result.sendInstagramProfile = (jid, data, options = {}) => { const r = new AIRich(result); r.addInstagramProfile(data); return r.send(jid, options) }
|
|
653
|
+
result.sendRichGeneration = async (jid, opts = {}) => { const { message, responseId, itemId } = prepareRichGenerationMessage(opts); const full = await generateWAMessageFromContent(jid, message, { userJid: sock.user?.id, messageId: opts.messageId || generateMessageIDV2(sock.user?.id) }); await sock.relayMessage(jid, full.message, { messageId: full.key.id }); return { msg: full, responseId, itemId } }
|
|
654
|
+
result.sendUnifiedResponse = (jid, sections, submessages = [], options = {}) => { const r = new AIRich(result); r.addRawSections(sections, submessages); return r.send(jid, options) }
|
|
655
|
+
result.sendRichButtonGrid = async (jid, grid, options = {}) => {
|
|
656
|
+
const { text, footer, cards = [] } = grid || {}
|
|
657
|
+
if (!Array.isArray(cards) || cards.length === 0) throw new Error('sendRichButtonGrid expects at least one card')
|
|
658
|
+
return result.sendMessage(jid, { ...(text ? { text } : {}), ...(footer ? { footer } : {}), cards }, options)
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const normalize = s => s.toLowerCase().replace(/[^a-z]/g, '')
|
|
662
|
+
const knownKeys = Object.keys(result).filter(k => typeof result[k] === 'function')
|
|
663
|
+
const normalizedMap = new Map(knownKeys.map(k => [normalize(k), k]))
|
|
664
|
+
|
|
665
|
+
return new Proxy(result, {
|
|
666
|
+
get(target, prop, receiver) {
|
|
667
|
+
if (prop in target) return Reflect.get(target, prop, receiver)
|
|
668
|
+
if (typeof prop !== 'string') return undefined
|
|
669
|
+
const match = normalizedMap.get(normalize(prop))
|
|
670
|
+
if (match) { target.logger?.warn?.(`[ZervonexHandler] Unknown method "${prop}" — did you mean "${match}"? Calling it.`); return target[match] }
|
|
671
|
+
return undefined
|
|
672
|
+
}
|
|
673
|
+
})
|
|
674
|
+
}
|