chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
export { markReadTool as whatsappMarkReadTool } from '@/tools/whatsapp/mark_read'
export { sendInteractiveTool as whatsappSendInteractiveTool } from '@/tools/whatsapp/send_interactive'
export { sendMediaTool as whatsappSendMediaTool } from '@/tools/whatsapp/send_media'
export { sendMessageTool as whatsappSendMessageTool } from '@/tools/whatsapp/send_message'
export { sendReactionTool as whatsappSendReactionTool } from '@/tools/whatsapp/send_reaction'
export { sendTemplateTool as whatsappSendTemplateTool } from '@/tools/whatsapp/send_template'
export * from '@/tools/whatsapp/types'
+76
View File
@@ -0,0 +1,76 @@
import type { ToolConfig } from '@/tools/types'
import type { WhatsAppMarkReadParams, WhatsAppMarkReadResponse } from '@/tools/whatsapp/types'
import { buildAuthHeaders, buildMessagesUrl, isRecord } from '@/tools/whatsapp/utils'
export const markReadTool: ToolConfig<WhatsAppMarkReadParams, WhatsAppMarkReadResponse> = {
id: 'whatsapp_mark_read',
name: 'WhatsApp Mark As Read',
description: 'Mark a received WhatsApp message as read so the sender sees blue checkmarks.',
version: '1.0.0',
params: {
messageId: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'ID (wamid) of the incoming message to mark as read',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
},
request: {
url: (params) => buildMessagesUrl(params.phoneNumberId),
method: 'POST',
headers: (params) => buildAuthHeaders(params.accessToken),
body: (params) => {
if (!params.messageId) {
throw new Error('Message ID is required but was not provided')
}
return {
messaging_product: 'whatsapp',
status: 'read',
message_id: params.messageId.trim(),
}
},
},
transformResponse: async (response: Response) => {
const responseText = await response.text()
const parsed = responseText ? (JSON.parse(responseText) as unknown) : {}
const data = isRecord(parsed) ? parsed : {}
const error = isRecord(data.error) ? data.error : undefined
if (!response.ok) {
const errorMessage =
(typeof error?.message === 'string' ? error.message : undefined) ||
(typeof error?.error_user_msg === 'string' ? error.error_user_msg : undefined) ||
`WhatsApp API error (${response.status})`
throw new Error(errorMessage)
}
return {
success: true,
output: {
success: data.success !== false,
},
}
},
outputs: {
success: {
type: 'boolean',
description: 'Whether the message was successfully marked as read',
},
},
}
+139
View File
@@ -0,0 +1,139 @@
import type { ToolConfig } from '@/tools/types'
import type { WhatsAppSendInteractiveParams, WhatsAppSendResponse } from '@/tools/whatsapp/types'
import {
buildAuthHeaders,
buildMessagesUrl,
transformWhatsAppSendResponse,
whatsappSendOutputs,
} from '@/tools/whatsapp/utils'
function coerceArray(value: unknown): unknown[] | undefined {
if (value == null || value === '') return undefined
const parsed = typeof value === 'string' ? (JSON.parse(value) as unknown) : value
if (!Array.isArray(parsed)) {
throw new Error('Interactive buttons and sections must be JSON arrays')
}
return parsed.length > 0 ? parsed : undefined
}
export const sendInteractiveTool: ToolConfig<WhatsAppSendInteractiveParams, WhatsAppSendResponse> =
{
id: 'whatsapp_send_interactive',
name: 'WhatsApp Send Interactive',
description: 'Send an interactive WhatsApp message with reply buttons or a selectable list.',
version: '1.0.0',
params: {
phoneNumber: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Recipient phone number with country code (e.g., +14155552671)',
},
bodyText: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Main body text of the interactive message',
},
headerText: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Optional plain-text header shown above the body',
},
footerText: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Optional footer text shown below the body',
},
buttons: {
type: 'json',
required: false,
visibility: 'user-or-llm',
description:
'Reply buttons array (max 3), each item: { "type": "reply", "reply": { "id": "...", "title": "..." } }. Provide buttons or sections.',
},
listButtonText: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Label for the menu button that opens the list (required when sending a list)',
},
sections: {
type: 'json',
required: false,
visibility: 'user-or-llm',
description:
'List sections array, each item: { "title": "...", "rows": [{ "id": "...", "title": "...", "description": "..." }] }. Provide sections or buttons.',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
},
request: {
url: (params) => buildMessagesUrl(params.phoneNumberId),
method: 'POST',
headers: (params) => buildAuthHeaders(params.accessToken),
body: (params) => {
if (!params.phoneNumber) {
throw new Error('Phone number is required but was not provided')
}
if (!params.bodyText) {
throw new Error('Body text is required but was not provided')
}
const buttons = coerceArray(params.buttons)
const sections = coerceArray(params.sections)
if (!buttons && !sections) {
throw new Error('Provide either buttons (reply buttons) or sections (list)')
}
if (buttons && sections) {
throw new Error('Provide either buttons or sections, not both')
}
const interactive: Record<string, unknown> = {
type: buttons ? 'button' : 'list',
body: { text: params.bodyText },
}
if (params.headerText) {
interactive.header = { type: 'text', text: params.headerText }
}
if (params.footerText) {
interactive.footer = { text: params.footerText }
}
if (buttons) {
interactive.action = { buttons }
} else {
const listButton = params.listButtonText?.trim()
if (!listButton) {
throw new Error('listButtonText is required when sending a list')
}
interactive.action = { button: listButton, sections }
}
return {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: params.phoneNumber.trim(),
type: 'interactive',
interactive,
}
},
},
transformResponse: transformWhatsAppSendResponse,
outputs: whatsappSendOutputs,
}
+117
View File
@@ -0,0 +1,117 @@
import type { ToolConfig } from '@/tools/types'
import type {
WhatsAppMediaType,
WhatsAppSendMediaParams,
WhatsAppSendResponse,
} from '@/tools/whatsapp/types'
import {
buildAuthHeaders,
buildMessagesUrl,
transformWhatsAppSendResponse,
whatsappSendOutputs,
} from '@/tools/whatsapp/utils'
const MEDIA_TYPES: readonly WhatsAppMediaType[] = ['image', 'document', 'video', 'audio']
const CAPTION_TYPES: ReadonlySet<WhatsAppMediaType> = new Set(['image', 'video', 'document'])
export const sendMediaTool: ToolConfig<WhatsAppSendMediaParams, WhatsAppSendResponse> = {
id: 'whatsapp_send_media',
name: 'WhatsApp Send Media',
description:
'Send an image, document, video, or audio message via a public link or an uploaded media ID.',
version: '1.0.0',
params: {
phoneNumber: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Recipient phone number with country code (e.g., +14155552671)',
},
mediaType: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Type of media to send: image, document, video, or audio',
},
mediaLink: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Public HTTPS URL of the media (provide this or mediaId)',
},
mediaId: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'ID of media previously uploaded to WhatsApp (provide this or mediaLink)',
},
caption: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Optional caption for image, video, or document media',
},
filename: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Optional file name shown to the recipient for document media',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
},
request: {
url: (params) => buildMessagesUrl(params.phoneNumberId),
method: 'POST',
headers: (params) => buildAuthHeaders(params.accessToken),
body: (params) => {
if (!params.phoneNumber) {
throw new Error('Phone number is required but was not provided')
}
const mediaType = params.mediaType?.trim() as WhatsAppMediaType
if (!MEDIA_TYPES.includes(mediaType)) {
throw new Error(`Media type must be one of: ${MEDIA_TYPES.join(', ')}`)
}
const link = params.mediaLink?.trim()
const id = params.mediaId?.trim()
if (!link && !id) {
throw new Error('Either mediaLink or mediaId is required')
}
const media: Record<string, string> = id ? { id } : { link: link as string }
if (params.caption && CAPTION_TYPES.has(mediaType)) {
media.caption = params.caption
}
if (params.filename && mediaType === 'document') {
media.filename = params.filename
}
return {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: params.phoneNumber.trim(),
type: mediaType,
[mediaType]: media,
}
},
},
transformResponse: transformWhatsAppSendResponse,
outputs: whatsappSendOutputs,
}
+180
View File
@@ -0,0 +1,180 @@
import type { ToolConfig } from '@/tools/types'
import type { WhatsAppResponse, WhatsAppSendMessageParams } from '@/tools/whatsapp/types'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
export const sendMessageTool: ToolConfig<WhatsAppSendMessageParams, WhatsAppResponse> = {
id: 'whatsapp_send_message',
name: 'WhatsApp Send Message',
description: 'Send a text message through the WhatsApp Cloud API.',
version: '1.0.0',
params: {
phoneNumber: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Recipient phone number with country code (e.g., +14155552671)',
},
message: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Plain text message content to send',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
previewUrl: {
type: 'boolean',
required: false,
visibility: 'user-or-llm',
description:
'Whether WhatsApp should try to render a link preview for the first URL in the message',
},
},
request: {
url: (params) => {
if (!params.phoneNumberId) {
throw new Error('WhatsApp Phone Number ID is required')
}
return `https://graph.facebook.com/v25.0/${params.phoneNumberId.trim()}/messages`
},
method: 'POST',
headers: (params) => {
if (!params.accessToken) {
throw new Error('WhatsApp Access Token is required')
}
return {
Authorization: `Bearer ${params.accessToken.trim()}`,
'Content-Type': 'application/json',
}
},
body: (params) => {
if (!params.phoneNumber) {
throw new Error('Phone number is required but was not provided')
}
if (!params.message) {
throw new Error('Message content is required but was not provided')
}
const text: Record<string, boolean | string> = {
body: params.message,
}
if (typeof params.previewUrl === 'boolean') {
text.preview_url = params.previewUrl
}
return {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: params.phoneNumber.trim(),
type: 'text',
text,
}
},
},
transformResponse: async (response: Response) => {
const responseText = await response.text()
const parsed = responseText ? (JSON.parse(responseText) as unknown) : {}
const data = isRecord(parsed) ? parsed : {}
const error = isRecord(data.error) ? data.error : undefined
if (!response.ok) {
const errorMessage =
(typeof error?.message === 'string' ? error.message : undefined) ||
(typeof error?.error_user_msg === 'string' ? error.error_user_msg : undefined) ||
(isRecord(error?.error_data) && typeof error.error_data.details === 'string'
? error.error_data.details
: undefined) ||
`WhatsApp API error (${response.status})`
throw new Error(errorMessage)
}
const contacts = Array.isArray(data.contacts)
? data.contacts.filter(isRecord).map((contact) => ({
input: typeof contact.input === 'string' ? contact.input : '',
wa_id: typeof contact.wa_id === 'string' ? contact.wa_id : null,
}))
: []
const firstMessage =
Array.isArray(data.messages) && isRecord(data.messages[0]) ? data.messages[0] : undefined
const messageId = typeof firstMessage?.id === 'string' ? firstMessage.id : undefined
const messageStatus =
typeof firstMessage?.message_status === 'string' ? firstMessage.message_status : undefined
if (!messageId) {
throw new Error('WhatsApp API response did not include a message ID')
}
return {
success: true,
output: {
success: true,
messageId,
messageStatus,
messagingProduct:
typeof data.messaging_product === 'string' ? data.messaging_product : undefined,
inputPhoneNumber: contacts[0]?.input ?? null,
whatsappUserId: contacts[0]?.wa_id ?? null,
contacts,
},
}
},
outputs: {
success: { type: 'boolean', description: 'WhatsApp message send success status' },
messageId: { type: 'string', description: 'Unique WhatsApp message identifier' },
messageStatus: {
type: 'string',
description: 'Initial delivery state returned by the API',
optional: true,
},
messagingProduct: {
type: 'string',
description: 'Messaging product returned by the API',
optional: true,
},
inputPhoneNumber: {
type: 'string',
description: 'Recipient phone number echoed back by WhatsApp',
optional: true,
},
whatsappUserId: {
type: 'string',
description: 'WhatsApp user ID resolved for the recipient',
optional: true,
},
contacts: {
type: 'array',
description: 'Recipient contact records returned by WhatsApp',
optional: true,
items: {
type: 'object',
properties: {
input: { type: 'string', description: 'Input phone number sent to the API' },
wa_id: {
type: 'string',
description: 'WhatsApp user ID associated with the recipient',
optional: true,
},
},
},
},
},
}
+78
View File
@@ -0,0 +1,78 @@
import type { ToolConfig } from '@/tools/types'
import type { WhatsAppSendReactionParams, WhatsAppSendResponse } from '@/tools/whatsapp/types'
import {
buildAuthHeaders,
buildMessagesUrl,
transformWhatsAppSendResponse,
whatsappSendOutputs,
} from '@/tools/whatsapp/utils'
export const sendReactionTool: ToolConfig<WhatsAppSendReactionParams, WhatsAppSendResponse> = {
id: 'whatsapp_send_reaction',
name: 'WhatsApp Send Reaction',
description:
'React to a WhatsApp message with an emoji. Send an empty emoji to remove an existing reaction.',
version: '1.0.0',
params: {
phoneNumber: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Recipient phone number with country code (e.g., +14155552671)',
},
messageId: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'ID (wamid) of the message to react to',
},
emoji: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Emoji to react with. Leave empty to remove an existing reaction.',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
},
request: {
url: (params) => buildMessagesUrl(params.phoneNumberId),
method: 'POST',
headers: (params) => buildAuthHeaders(params.accessToken),
body: (params) => {
if (!params.phoneNumber) {
throw new Error('Phone number is required but was not provided')
}
if (!params.messageId) {
throw new Error('Message ID is required but was not provided')
}
return {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: params.phoneNumber.trim(),
type: 'reaction',
reaction: {
message_id: params.messageId.trim(),
emoji: params.emoji ?? '',
},
}
},
},
transformResponse: transformWhatsAppSendResponse,
outputs: whatsappSendOutputs,
}
+103
View File
@@ -0,0 +1,103 @@
import type { ToolConfig } from '@/tools/types'
import type { WhatsAppSendResponse, WhatsAppSendTemplateParams } from '@/tools/whatsapp/types'
import {
buildAuthHeaders,
buildMessagesUrl,
transformWhatsAppSendResponse,
whatsappSendOutputs,
} from '@/tools/whatsapp/utils'
function coerceComponents(value: unknown): unknown[] | undefined {
if (value == null || value === '') return undefined
const parsed = typeof value === 'string' ? (JSON.parse(value) as unknown) : value
if (!Array.isArray(parsed)) {
throw new Error('Template components must be a JSON array')
}
return parsed
}
export const sendTemplateTool: ToolConfig<WhatsAppSendTemplateParams, WhatsAppSendResponse> = {
id: 'whatsapp_send_template',
name: 'WhatsApp Send Template',
description:
'Send a pre-approved WhatsApp template message with a language and optional variable components.',
version: '1.0.0',
params: {
phoneNumber: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Recipient phone number with country code (e.g., +14155552671)',
},
templateName: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Name of the approved message template',
},
languageCode: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Template language/locale code (e.g., en_US)',
},
components: {
type: 'json',
required: false,
visibility: 'user-or-llm',
description:
'Template components array with parameters for header/body/button variables, per the WhatsApp template message schema',
},
phoneNumberId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business Phone Number ID (from Meta Business Suite)',
},
accessToken: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'WhatsApp Business API Access Token (from Meta Developer Portal)',
},
},
request: {
url: (params) => buildMessagesUrl(params.phoneNumberId),
method: 'POST',
headers: (params) => buildAuthHeaders(params.accessToken),
body: (params) => {
if (!params.phoneNumber) {
throw new Error('Phone number is required but was not provided')
}
if (!params.templateName) {
throw new Error('Template name is required but was not provided')
}
if (!params.languageCode) {
throw new Error('Template language code is required but was not provided')
}
const components = coerceComponents(params.components)
const template: Record<string, unknown> = {
name: params.templateName.trim(),
language: { code: params.languageCode.trim() },
}
if (components && components.length > 0) {
template.components = components
}
return {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: params.phoneNumber.trim(),
type: 'template',
template,
}
},
},
transformResponse: transformWhatsAppSendResponse,
outputs: whatsappSendOutputs,
}
+90
View File
@@ -0,0 +1,90 @@
import type { ToolResponse } from '@/tools/types'
interface WhatsAppMessageContact {
input: string
wa_id?: string | null
}
interface WhatsAppSendOutput {
success: boolean
messageId?: string
messageStatus?: string
messagingProduct?: string
inputPhoneNumber?: string | null
whatsappUserId?: string | null
contacts?: WhatsAppMessageContact[]
error?: string
}
/** Shared response for every outbound `/messages` send operation. */
export interface WhatsAppSendResponse extends ToolResponse {
output: WhatsAppSendOutput
}
/** Legacy alias kept for the text send_message tool and the block output type. */
export interface WhatsAppResponse extends ToolResponse {
output: WhatsAppSendOutput
}
export interface WhatsAppSendMessageParams {
phoneNumber: string
message: string
phoneNumberId: string
accessToken: string
previewUrl?: boolean
}
export interface WhatsAppSendTemplateParams {
phoneNumber: string
templateName: string
languageCode: string
components?: unknown
phoneNumberId: string
accessToken: string
}
export type WhatsAppMediaType = 'image' | 'document' | 'video' | 'audio'
export interface WhatsAppSendMediaParams {
phoneNumber: string
mediaType: WhatsAppMediaType
mediaLink?: string
mediaId?: string
caption?: string
filename?: string
phoneNumberId: string
accessToken: string
}
export interface WhatsAppSendInteractiveParams {
phoneNumber: string
bodyText: string
headerText?: string
footerText?: string
buttons?: unknown
listButtonText?: string
sections?: unknown
phoneNumberId: string
accessToken: string
}
export interface WhatsAppSendReactionParams {
phoneNumber: string
messageId: string
emoji?: string
phoneNumberId: string
accessToken: string
}
export interface WhatsAppMarkReadParams {
messageId: string
phoneNumberId: string
accessToken: string
}
export interface WhatsAppMarkReadResponse extends ToolResponse {
output: {
success: boolean
error?: string
}
}
+135
View File
@@ -0,0 +1,135 @@
import type { WhatsAppSendResponse } from '@/tools/whatsapp/types'
/** WhatsApp Cloud API Graph version used by every outbound tool. */
export const WHATSAPP_GRAPH_VERSION = 'v25.0'
/** Build the messages endpoint for a given business phone number ID. */
export function buildMessagesUrl(phoneNumberId: string | undefined): string {
if (!phoneNumberId) {
throw new Error('WhatsApp Phone Number ID is required')
}
return `https://graph.facebook.com/${WHATSAPP_GRAPH_VERSION}/${phoneNumberId.trim()}/messages`
}
/** Build the shared Bearer auth headers for the WhatsApp Cloud API. */
export function buildAuthHeaders(accessToken: string | undefined): Record<string, string> {
if (!accessToken) {
throw new Error('WhatsApp Access Token is required')
}
return {
Authorization: `Bearer ${accessToken.trim()}`,
'Content-Type': 'application/json',
}
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
async function parseWhatsAppResponse(response: Response): Promise<Record<string, unknown>> {
const responseText = await response.text()
const parsed = responseText ? (JSON.parse(responseText) as unknown) : {}
return isRecord(parsed) ? parsed : {}
}
/** Extract a human-readable error message from a WhatsApp API error payload. */
function extractErrorMessage(data: Record<string, unknown>, status: number): string {
const error = isRecord(data.error) ? data.error : undefined
return (
(typeof error?.message === 'string' ? error.message : undefined) ||
(typeof error?.error_user_msg === 'string' ? error.error_user_msg : undefined) ||
(isRecord(error?.error_data) && typeof error.error_data.details === 'string'
? error.error_data.details
: undefined) ||
`WhatsApp API error (${status})`
)
}
/**
* Transform the shared send response shape returned by every outbound message
* operation (template, media, interactive, reaction) on `/messages`.
*/
export async function transformWhatsAppSendResponse(
response: Response
): Promise<WhatsAppSendResponse> {
const data = await parseWhatsAppResponse(response)
if (!response.ok) {
throw new Error(extractErrorMessage(data, response.status))
}
const contacts = Array.isArray(data.contacts)
? data.contacts.filter(isRecord).map((contact) => ({
input: typeof contact.input === 'string' ? contact.input : '',
wa_id: typeof contact.wa_id === 'string' ? contact.wa_id : null,
}))
: []
const firstMessage =
Array.isArray(data.messages) && isRecord(data.messages[0]) ? data.messages[0] : undefined
const messageId = typeof firstMessage?.id === 'string' ? firstMessage.id : undefined
const messageStatus =
typeof firstMessage?.message_status === 'string' ? firstMessage.message_status : undefined
if (!messageId) {
throw new Error('WhatsApp API response did not include a message ID')
}
return {
success: true,
output: {
success: true,
messageId,
messageStatus,
messagingProduct:
typeof data.messaging_product === 'string' ? data.messaging_product : undefined,
inputPhoneNumber: contacts[0]?.input ?? null,
whatsappUserId: contacts[0]?.wa_id ?? null,
contacts,
},
}
}
/**
* Shared output schema for every outbound send operation. Mirrors the
* `transformWhatsAppSendResponse` output so each tool stays consistent.
*/
export const whatsappSendOutputs = {
success: { type: 'boolean', description: 'WhatsApp message send success status' },
messageId: { type: 'string', description: 'Unique WhatsApp message identifier' },
messageStatus: {
type: 'string',
description: 'Initial delivery state returned by the API',
optional: true,
},
messagingProduct: {
type: 'string',
description: 'Messaging product returned by the API',
optional: true,
},
inputPhoneNumber: {
type: 'string',
description: 'Recipient phone number echoed back by WhatsApp',
optional: true,
},
whatsappUserId: {
type: 'string',
description: 'WhatsApp user ID resolved for the recipient',
optional: true,
},
contacts: {
type: 'array',
description: 'Recipient contact records returned by WhatsApp',
optional: true,
items: {
type: 'object',
properties: {
input: { type: 'string', description: 'Input phone number sent to the API' },
wa_id: {
type: 'string',
description: 'WhatsApp user ID associated with the recipient',
optional: true,
},
},
},
},
} as const