@botozap/sdk 0.9.0 → 0.11.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/dist/index.d.ts CHANGED
@@ -1,33 +1,68 @@
1
1
  /** Status de uma mensagem no envio. A API pode evoluir os valores. */
2
2
  type MessageStatus = "sent" | "delivered" | "read" | "failed" | string;
3
+ /** Canal de uma mensagem/Conta de canal. Valores novos podem surgir. */
4
+ type MessageChannel = "whatsapp" | "instagram" | (string & {});
3
5
  /**
4
6
  * Retorno de POST /v1/messages. Esta rota responde o objeto DIRETO (sem o
5
7
  * envelope `{ data }`), por isso o método `messages.send` devolve `SendResult`
6
8
  * cru. Todas as OUTRAS rotas de item vêm embrulhadas em `{ data }` (helper `ok`).
9
+ *
10
+ * No WhatsApp o identificador da Meta é `wamid`. Fora dele (Instagram) `wamid`
11
+ * vem `null` e o identificador do canal é `external_id` (o `mid` da Meta),
12
+ * acompanhado de `channel`. Ramifique por `channel`/`external_id`, não pela
13
+ * presença de `wamid`.
7
14
  */
8
15
  interface SendResult {
16
+ /** UUID interno da Mensagem; `null` quando a gravação best-effort falhou (ou a reação não tem alvo no histórico). */
9
17
  id: string | null;
10
- wamid: string;
18
+ /** ID da mensagem no WhatsApp; `null` fora do WhatsApp. */
19
+ wamid: string | null;
20
+ /** Identificador da mensagem no canal (o `mid` no Instagram). Ausente em respostas do WhatsApp. */
21
+ external_id?: string | null;
22
+ /** Canal do envio. Ausente em respostas do WhatsApp (o canal implícito). */
23
+ channel?: MessageChannel;
11
24
  to: string;
12
25
  /** Destinatário efetivamente usado após normalização de telefone/BSUID. */
13
26
  sent_to?: string;
14
27
  status: MessageStatus;
15
28
  /** Presente apenas quando a chave é do ambiente sandbox. */
16
29
  sandbox?: boolean;
17
- /** Só em `type: "reaction"`: alvo e ação (`react`/`unreact`). */
18
- type?: "reaction";
30
+ /** Avisos não bloqueantes (ex.: consentimento do Contato). */
31
+ warnings?: {
32
+ code: string;
33
+ message: string;
34
+ }[];
35
+ /**
36
+ * Tipo do envio. WhatsApp: só em `"reaction"`. Instagram: `"text"` ou o tipo
37
+ * da mídia; ausente em reação.
38
+ */
39
+ type?: "reaction" | "text" | "image" | "video" | "audio" | "document" | (string & {});
40
+ /** Só em reação: alvo e ação (`react`/`unreact`). */
19
41
  reaction?: SendReactionResult;
20
42
  }
21
43
  /** Eco de `POST /v1/messages` com `type: "reaction"`. */
22
44
  interface SendReactionResult {
23
- /** UUID interno da mensagem alvo. */
45
+ /** WhatsApp: UUID interno da mensagem alvo. Instagram: o `mid` do alvo. */
24
46
  message_id: string;
25
- /** wamid da mensagem alvo. */
26
- wamid: string;
47
+ /** wamid da mensagem alvo (só no WhatsApp). */
48
+ wamid?: string;
27
49
  /** `""` quando a reação foi retirada. */
28
50
  emoji: string;
29
51
  action: "react" | "unreact";
30
52
  }
53
+ /**
54
+ * Opção de resposta (quick reply) de um direct do Instagram. `text` (padrão)
55
+ * exige `title` (até 20 caracteres) e aceita `payload` (até 1000; sem ele volta
56
+ * o próprio título). `user_phone_number`/`user_email` são preenchidos pelo
57
+ * Instagram com o dado de quem tocou: não mande `title` nem `payload`.
58
+ */
59
+ type QuickReply = {
60
+ content_type?: "text";
61
+ title: string;
62
+ payload?: string;
63
+ } | {
64
+ content_type: "user_phone_number" | "user_email";
65
+ };
31
66
  /** Componente de template do WhatsApp (header, body, button…). */
32
67
  interface TemplatePayload {
33
68
  name: string;
@@ -91,8 +126,34 @@ interface Customer {
91
126
  * Valores novos podem surgir.
92
127
  */
93
128
  type MessageSource = "api" | "app" | "history" | "broadcast" | (string & {});
129
+ /** Marca de edição gravada em `content.edited` (hoje, mensagens do Instagram). */
130
+ interface MessageEdit {
131
+ /** Quantas vezes a mensagem foi editada. */
132
+ count: number;
133
+ /** Quando foi a última edição (ISO 8601). */
134
+ at: string;
135
+ }
136
+ /**
137
+ * Conteúdo de uma Mensagem. A forma varia por tipo e canal; o SDK só tipa os
138
+ * campos transversais.
139
+ */
140
+ interface MessageContent {
141
+ /** Texto (forma do Instagram); no WhatsApp o texto vem em `text.body`. */
142
+ body?: string;
143
+ /** Presente quando o contato editou a mensagem: o conteúdo já é o editado. */
144
+ edited?: MessageEdit;
145
+ [key: string]: unknown;
146
+ }
94
147
  interface Message {
95
148
  id: string;
149
+ /** Canal da Mensagem (`whatsapp` ou `instagram`). */
150
+ channel?: MessageChannel;
151
+ /** Identificador no canal: `wamid` no WhatsApp, `mid` no Instagram. */
152
+ external_id?: string | null;
153
+ /** Conteúdo; `content.edited` aparece quando o contato editou a mensagem. */
154
+ content?: MessageContent;
155
+ /** Quando o remetente apagou a mensagem; `null` quando não apagada. */
156
+ revoked_at?: string | null;
96
157
  /** Origem da mensagem (ver `MessageSource`). */
97
158
  source?: MessageSource;
98
159
  /** Chegada à BotoZap (ISO 8601); chave de `sort=created_at`. */
@@ -139,12 +200,26 @@ interface ConversationReferral {
139
200
  /** Quando o BotoZap recebeu o clique (ISO 8601). */
140
201
  received_at: string | null;
141
202
  }
203
+ /** Bloco `channel_account` embutido em Conversas, Contatos e Mensagens. */
204
+ interface ChannelAccountRef {
205
+ /** UUID interno da Conta de canal (serve de `from` no envio). */
206
+ id: string;
207
+ channel: MessageChannel;
208
+ /** Telefone formatado no WhatsApp, @username no Instagram; pode ser nulo. */
209
+ display: string | null;
210
+ }
142
211
  interface Conversation {
143
212
  id: string;
144
- /** UUID interno do Número da própria Conversa. */
145
- phone_number_id?: string;
213
+ /** Pausa do agente aguardando humano (ISO 8601); null quando não pausado. */
214
+ agent_paused_at?: string | null;
215
+ /** Canal da Conversa (`whatsapp` ou `instagram`). */
216
+ channel?: MessageChannel;
217
+ /** Conta de canal por onde a Conversa acontece (Número ou Conta do Instagram). */
218
+ channel_account?: ChannelAccountRef | null;
219
+ /** UUID interno do Número da própria Conversa; `null` fora do WhatsApp. */
220
+ phone_number_id?: string | null;
146
221
  contact?: {
147
- /** Identidade canônica do Contato: telefone ou BSUID. */
222
+ /** Identidade canônica do Contato: telefone ou BSUID no WhatsApp, IGSID no Instagram. */
148
223
  wa_id?: string | null;
149
224
  phone?: string | null;
150
225
  [key: string]: unknown;
@@ -223,6 +298,13 @@ interface BotoZapEvent {
223
298
  id: string;
224
299
  /** Cursor monotônico e contíguo, serializado como string. */
225
300
  cursor: string;
301
+ /**
302
+ * Tipo do Evento (ex.: `whatsapp.message.received`,
303
+ * `instagram.message.received`). No Instagram, `instagram.message.edited`
304
+ * traz o texto novo em `data.edit` e o conteúdo atualizado (com
305
+ * `content.edited`) em `data.message`; `instagram.message.revoked` traz
306
+ * `data.message.revoked_at`, sem o conteúdo apagado. Valores novos podem surgir.
307
+ */
226
308
  type: string;
227
309
  /**
228
310
  * WAMID da mensagem do WhatsApp que originou o Evento. `null` fora do
@@ -1569,6 +1651,10 @@ type AiCatalogModel = {
1569
1651
  cache_read_usd_per_million: number | null;
1570
1652
  cache_write_usd_per_million: number | null;
1571
1653
  notes: ("request_fee" | "long_context" | "image_input" | "variable")[];
1654
+ /** Absent: reported by the credential's own provider. `"openrouter"`: the provider's own list
1655
+ * price read from OpenRouter's public catalog, for providers whose model list has no prices
1656
+ * (OpenAI, Anthropic, Google, DeepSeek). */
1657
+ source?: "openrouter";
1572
1658
  } | null;
1573
1659
  };
1574
1660
  type AiModelCatalogSnapshot = {
@@ -3418,12 +3504,24 @@ interface ListMessagesParams extends CursorParams {
3418
3504
  has_media?: boolean;
3419
3505
  }
3420
3506
  interface SendTextParams {
3421
- /** Número de destino em E.164, ex: "+5531988887777". */
3507
+ /**
3508
+ * Destinatário: telefone E.164 (ex.: "+5531988887777") ou BSUID no WhatsApp;
3509
+ * IGSID do contato no Instagram. O canal sai da forma do endereço (ou do `from`).
3510
+ */
3422
3511
  to: string;
3423
3512
  /** Corpo do texto. */
3424
3513
  text: string;
3425
- /** ID Meta ou UUID interno do Número de origem (obrigatório se houver mais de um). */
3514
+ /**
3515
+ * Origem: ID Meta ou UUID interno do Número (WhatsApp), id da conta na Meta
3516
+ * ou UUID da Conta de canal (Instagram). Obrigatório quando há mais de uma
3517
+ * origem do mesmo canal.
3518
+ */
3426
3519
  from?: string;
3520
+ /**
3521
+ * Opções de resposta (só Instagram, só com texto, até 13, dentro da janela de
3522
+ * 24h). No WhatsApp a API recusa com 422 `channel_not_supported`.
3523
+ */
3524
+ quick_replies?: QuickReply[];
3427
3525
  }
3428
3526
  interface SendTemplateParams {
3429
3527
  to: string;
@@ -3459,6 +3557,11 @@ interface SendDocumentParams {
3459
3557
  filename?: string;
3460
3558
  from?: string;
3461
3559
  }
3560
+ /**
3561
+ * Mídia por URL pública. `to` aceita telefone/BSUID (WhatsApp) ou IGSID
3562
+ * (Instagram); `from` aceita a origem de qualquer canal. No Instagram não
3563
+ * existe `caption`: a API recusa com 422 `unsupported_caption`.
3564
+ */
3462
3565
  type SendMediaParams = SendImageParams | SendVideoParams | SendAudioParams | SendDocumentParams;
3463
3566
  /** Header de `interactive` (texto; mídia só em button e cta_url). */
3464
3567
  type InteractiveHeader = {
@@ -3550,7 +3653,10 @@ interface SendLocationParams {
3550
3653
  }
3551
3654
  interface SendReactionParams {
3552
3655
  to: string;
3553
- /** UUID interno ou wamid da mensagem RECEBIDA do contato (até 30 dias). */
3656
+ /**
3657
+ * Mensagem RECEBIDA do contato: UUID interno ou wamid no WhatsApp (até 30
3658
+ * dias); o `mid` (`external_id`) no Instagram.
3659
+ */
3554
3660
  message_id: string;
3555
3661
  /** Emoji da reação; `""` retira a reação. */
3556
3662
  emoji: string;
@@ -3578,8 +3684,8 @@ declare class Messages {
3578
3684
  /** Envia uma localização (WhatsApp; mensagem livre). */
3579
3685
  sendLocation(params: SendLocationParams, options?: SendOptions): Promise<SendResult>;
3580
3686
  /**
3581
- * Reage a uma mensagem recebida (WhatsApp). `emoji: ""` retira a reação.
3582
- * O retorno traz `reaction` com o alvo e a ação.
3687
+ * Reage a uma mensagem recebida (WhatsApp ou Instagram). `emoji: ""` retira
3688
+ * a reação. O retorno traz `reaction` com o alvo e a ação.
3583
3689
  */
3584
3690
  sendReaction(params: SendReactionParams, options?: SendOptions): Promise<SendResult>;
3585
3691
  /** Lista as mensagens da conta (paginação por cursor). */
@@ -3870,6 +3976,10 @@ declare class Contacts {
3870
3976
  }
3871
3977
 
3872
3978
  interface ListConversationsParams extends CursorParams {
3979
+ /** Recorta as conversas pelos canais do negócio autorizado. */
3980
+ customer_id?: string;
3981
+ /** true: somente conversas com agente pausado aguardando humano. */
3982
+ agent_paused?: boolean;
3873
3983
  /** id da Meta OU uuid interno do número. */
3874
3984
  phone_number_id?: string;
3875
3985
  /** "active" | "ended" — derivado da janela de 24h. */
@@ -3881,6 +3991,10 @@ interface ListConversationsParams extends CursorParams {
3881
3991
  contact?: string;
3882
3992
  /** Alias de busca por contato (usado quando `contact` não é informado). */
3883
3993
  phone_number?: string;
3994
+ /** Canal da Conversa: `whatsapp` ou `instagram` (outro valor é 422). */
3995
+ channel?: MessageChannel;
3996
+ /** UUID da Conta de canal (Número ou Conta do Instagram) de origem. */
3997
+ channel_account_id?: string;
3884
3998
  }
3885
3999
  interface CreateAssignmentParams {
3886
4000
  /** Membro a quem atribuir a conversa. */
@@ -3890,6 +4004,8 @@ interface CreateAssignmentParams {
3890
4004
  interface ReplyConversationParams {
3891
4005
  /** Corpo da resposta livre dentro da janela de 24h. */
3892
4006
  text: string;
4007
+ /** Opções de resposta (só em Conversas do Instagram; ver `messages.send`). */
4008
+ quick_replies?: QuickReply[];
3893
4009
  }
3894
4010
  /** Conversas (read + status) e atribuições a membros. */
3895
4011
  declare class Conversations {
@@ -3904,9 +4020,11 @@ declare class Conversations {
3904
4020
  list(params?: ListConversationsParams): Promise<CursorList<Conversation>>;
3905
4021
  get(id: string): Promise<Conversation>;
3906
4022
  /**
3907
- * Responde uma Conversa sem o chamador precisar combinar Contato e Número.
3908
- * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
3909
- * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
4023
+ * Responde uma Conversa sem o chamador precisar combinar Contato e origem.
4024
+ * No WhatsApp a origem é o Número da Conversa; no Instagram, a Conta de
4025
+ * canal (`channel_account.id`). A leitura e o envio usam a mesma chave; o
4026
+ * POST /messages revalida Conta, ambiente, identidade, janela, quota e
4027
+ * billing antes de chamar a Meta.
3910
4028
  */
3911
4029
  reply(id: string, params: ReplyConversationParams, options?: SendOptions): Promise<SendResult>;
3912
4030
  update(id: string, params: Record<string, unknown>): Promise<Conversation>;
@@ -4006,6 +4124,137 @@ declare class PhoneNumbers {
4006
4124
  health(id: string): Promise<Record<string, unknown>>;
4007
4125
  }
4008
4126
 
4127
+ /**
4128
+ * Saúde do token de uma Conta do Instagram: `ok`; `expiring` (vence em até 7
4129
+ * dias, a renovação automática ainda tenta); `expired`; `invalid` (a Meta
4130
+ * recusou o token); `revoked` (conta desconectada); `unknown` (conexão
4131
+ * pendente). Com `expired`, `invalid` ou `revoked` os envios falham até
4132
+ * reconectar a conta.
4133
+ */
4134
+ type InstagramTokenStatus = "ok" | "expiring" | "expired" | "invalid" | "revoked" | "unknown" | (string & {});
4135
+ /**
4136
+ * Conta de canal: o endpoint concreto de um Cliente num canal — o Número no
4137
+ * WhatsApp, a Conta do Instagram no Instagram. O `id` (UUID) serve de `from`
4138
+ * no envio e de filtro `channel_account_id` nas listagens.
4139
+ */
4140
+ interface ChannelAccount {
4141
+ id: string;
4142
+ channel: MessageChannel;
4143
+ customer_id: string;
4144
+ /** Telefone formatado no WhatsApp, @username no Instagram; pode ser nulo. */
4145
+ display: string | null;
4146
+ status: string;
4147
+ sandbox: boolean;
4148
+ /** Id do endpoint na Meta: `phone_number_id` no WhatsApp, id da conta no Instagram. */
4149
+ external_id: string;
4150
+ created_at: string;
4151
+ updated_at: string;
4152
+ /** Detalhes do Número; só em Contas de canal do WhatsApp. */
4153
+ whatsapp?: {
4154
+ id: string | null;
4155
+ phone_number_id: string;
4156
+ display_phone_number: string | null;
4157
+ verified_name: string | null;
4158
+ quality_rating: string | null;
4159
+ type: string | null;
4160
+ waba_connection_id: string | null;
4161
+ waba_id: string | null;
4162
+ connection_status: string | null;
4163
+ token_status: string | null;
4164
+ };
4165
+ /** Detalhes e saúde da conexão; só em Contas de canal do Instagram. Nunca traz o token. */
4166
+ instagram?: {
4167
+ /** Id da conta profissional na Meta (o mesmo `external_id`). */
4168
+ instagram_account_id: string;
4169
+ username: string | null;
4170
+ name: string | null;
4171
+ instagram_connection_id: string | null;
4172
+ connection_status: string | null;
4173
+ token_status: InstagramTokenStatus | null;
4174
+ /** Validade do token atual (60 dias, renovado sozinho a cada ~30). */
4175
+ token_expires_at: string | null;
4176
+ /** Última renovação bem-sucedida do token. */
4177
+ token_refreshed_at: string | null;
4178
+ };
4179
+ [key: string]: unknown;
4180
+ }
4181
+ /** Filtros de `channelAccounts.list` (GET /v1/channel_accounts). */
4182
+ interface ListChannelAccountsParams extends OffsetParams {
4183
+ /** `whatsapp` ou `instagram` (outro valor é 422). */
4184
+ channel?: MessageChannel;
4185
+ /** UUID do Cliente dono das Contas de canal. */
4186
+ customer_id?: string;
4187
+ }
4188
+ /** Estado de uma Regra de comentário. `paused_plan`: ativa, mas pausada pelo plano. */
4189
+ type CommentRuleStatus = "active" | "inactive" | "paused_plan" | (string & {});
4190
+ /**
4191
+ * Regra de comentário do Instagram: um comentário que casa `keyword` (ou
4192
+ * qualquer comentário, quando `null`) no post `media_id` (ou em todos, quando
4193
+ * `null`) recebe o direct `dm_text` e, opcionalmente, a resposta pública
4194
+ * `reply_text`.
4195
+ */
4196
+ interface CommentRule {
4197
+ id: string;
4198
+ channel_account_id: string;
4199
+ /** Palavra-chave (até 60 caracteres); `null` = qualquer comentário. */
4200
+ keyword: string | null;
4201
+ /** Texto do direct (até 1000 bytes). */
4202
+ dm_text: string;
4203
+ /** Resposta pública ao comentário (até 2200 caracteres); `null` = sem resposta. */
4204
+ reply_text: string | null;
4205
+ /** Id numérico do post (`media.id`); `null` = todos os posts. */
4206
+ media_id: string | null;
4207
+ /** Configuração gravada; o efeito real está em `status`. */
4208
+ is_active: boolean;
4209
+ status: CommentRuleStatus;
4210
+ /** `true` quando a regra está ativa mas o plano não permite operá-la. */
4211
+ paused_by_plan: boolean;
4212
+ /** Aviso não bloqueante (regra sem palavra-chave valendo para todos os posts). */
4213
+ notice: string | null;
4214
+ created_at: string;
4215
+ updated_at: string;
4216
+ [key: string]: unknown;
4217
+ }
4218
+ /** Corpo de `createCommentRule` (POST /v1/channel_accounts/:id/comment-rules). */
4219
+ interface CreateCommentRuleParams {
4220
+ /** Texto do direct enviado a quem comentou (obrigatório). */
4221
+ dm_text: string;
4222
+ /** Palavra-chave; `null`/vazio = qualquer comentário. */
4223
+ keyword?: string | null;
4224
+ /** Resposta pública ao comentário; `null`/vazio = sem resposta. */
4225
+ reply_text?: string | null;
4226
+ /** Id numérico do post; `null`/vazio = todos os posts. */
4227
+ media_id?: string | null;
4228
+ /** Padrão `true`. */
4229
+ is_active?: boolean;
4230
+ }
4231
+ /** Corpo de `updateCommentRule` (PATCH): só os campos enviados mudam. */
4232
+ type UpdateCommentRuleParams = Partial<CreateCommentRuleParams>;
4233
+ /** Contas de canal (WhatsApp e Instagram) e Regras de comentário do Instagram. */
4234
+ declare class ChannelAccounts {
4235
+ private readonly client;
4236
+ constructor(client: BotoZap);
4237
+ /** Lista as Contas de canal da conta (paginação por offset/página). numbers:read. */
4238
+ list(params?: ListChannelAccountsParams): Promise<OffsetList<ChannelAccount>>;
4239
+ /** Busca uma Conta de canal pelo UUID interno ou pelo id na Meta (`external_id`). numbers:read. */
4240
+ get(id: string): Promise<ChannelAccount>;
4241
+ /** Lista as Regras de comentário de uma Conta do Instagram (UUID). comment-rules:read. */
4242
+ listCommentRules(channelAccountId: string, params?: OffsetParams): Promise<OffsetList<CommentRule>>;
4243
+ /** Busca uma Regra de comentário. comment-rules:read. */
4244
+ getCommentRule(channelAccountId: string, ruleId: string): Promise<CommentRule>;
4245
+ /**
4246
+ * Cria uma Regra de comentário. comment-rules:write. Exige plano que inclua
4247
+ * Regras de comentário (senão 422 `plan_restricted`); palavra-chave repetida
4248
+ * para o mesmo alvo é 409 `duplicate_rule`.
4249
+ */
4250
+ createCommentRule(channelAccountId: string, params: CreateCommentRuleParams): Promise<CommentRule>;
4251
+ /**
4252
+ * Altera uma Regra de comentário (só os campos enviados). comment-rules:write.
4253
+ * `is_active: false` desliga a regra; não há exclusão pela API.
4254
+ */
4255
+ updateCommentRule(channelAccountId: string, ruleId: string, params: UpdateCommentRuleParams): Promise<CommentRule>;
4256
+ }
4257
+
4009
4258
  /** Corpo do `POST /v1/media` — espelha o contrato real da rota. */
4010
4259
  interface UploadMediaParams {
4011
4260
  /** URL http(s) de origem do arquivo. A BotoZap baixa (com guard SSRF) e sobe pra Cloud API. */
@@ -4226,6 +4475,9 @@ declare class WebhookDeliveries {
4226
4475
  interface Me {
4227
4476
  /** UUID da Conta derivado pela API a partir da chave autenticada. */
4228
4477
  account_id: string;
4478
+ /** Nome da Conta (#629). Ausente em versões anteriores da API — opcional
4479
+ * para continuar compatível com um servidor sem o campo. */
4480
+ account_name?: string;
4229
4481
  /** Ambiente ao qual a chave pertence. */
4230
4482
  environment: "live" | "sandbox";
4231
4483
  /** Scopes efetivos concedidos à chave. */
@@ -4281,6 +4533,8 @@ declare class BotoZap {
4281
4533
  readonly conversations: Conversations;
4282
4534
  readonly webhooks: Webhooks;
4283
4535
  readonly phoneNumbers: PhoneNumbers;
4536
+ /** Contas de canal (WhatsApp e Instagram) e Regras de comentário do Instagram. */
4537
+ readonly channelAccounts: ChannelAccounts;
4284
4538
  readonly contactStages: ContactStages;
4285
4539
  readonly contactFields: ContactFields;
4286
4540
  readonly calendar: Calendar;
@@ -4360,4 +4614,4 @@ declare const PLAN_ERROR_CODES: readonly ["plan_restricted", "free_form_limit_re
4360
4614
  /** True quando o erro é recusa por plano (upgrade resolve; retry não). */
4361
4615
  declare function isPlanError(error: unknown): error is BotoZapError;
4362
4616
 
4363
- export { AI_CONFIGURABLE_PURPOSES, AI_CREDENTIAL_PROVIDERS, AI_OPERATIONS, AI_PURPOSES, type AddRecipientsError, type AddRecipientsResult, AgendaConfiguration, AgendaExceptions, type AgendaRecord, Ai, type AiAgent, type AiAgentConfig, type AiAgentCoverage, type AiAgentInput, type AiAgentVersion, AiAgentsResource, type AiAlert, type AiAlertBulkFilters, type AiAlertListItem, AiAlertsResource, type AiArtifactUploadInput, type AiAudioPricing, type AiBinding, type AiBindingTarget, type AiBudget, type AiBudgetInput, type AiCapabilitySignal, type AiCapabilityUsage, type AiCapabilityUsageList, type AiCase, type AiCaseChat, type AiCaseEvent, type AiCaseKind, type AiCaseReply, type AiCaseReplyInput, type AiCaseSource, AiCasesResource, type AiCatalogItems, type AiCatalogModel, type AiCatalogProduct, type AiCatalogSyncInput, type AiCatalogSyncResult, type AiChannelGate, type AiCommercialDecision, type AiCommercialEffect, type AiCommercialJob, type AiCommercialProposal, AiCommercialProposalsResource, type AiCommercialRequest, type AiCommercialSettings, type AiConfigurablePurpose, type AiContactAuthorization, type AiConversationCheckpoint, type AiCredential, AiCredentialsResource, type AiDraftResult, type AiEligibilityOverview, AiEligibilityResource, type AiEligibilitySettings, type AiEnrollment, type AiEvolution, AiEvolutionResource, type AiEvolutionSource, type AiExecution, type AiExecutionCitations, type AiExecutionSecurity, AiExecutionsResource, type AiField, type AiFlow, type AiFlowGraph, type AiFlowInput, type AiFlowSettings, type AiFlowVersion, type AiFollowupEffect, type AiFollowupEvent, AiFollowupFlowsResource, type AiFollowupPromise, type AiFollowupPromiseDetail, type AiFollowupPromiseStatus, type AiFollowupQueueFilters, type AiFollowupQueuePage, type AiFollowupQueueRow, AiFollowupsResource, type AiGateMode, type AiInference, type AiInferenceOrigin, type AiInferenceOutcome, type AiInferenceSummary, AiInferencesResource, type AiKnowledgeChunk, type AiKnowledgeCitation, type AiKnowledgeConversation, type AiKnowledgeHit, type AiKnowledgeImport, type AiKnowledgePreview, AiKnowledgeResource, type AiKnowledgeSearchDiagnostics, type AiKnowledgeSource, type AiMemory, type AiMemoryEntry, type AiMemoryEntryEvent, AiMemoryResource, type AiModelCatalogSnapshot, type AiModelCatalogSync, type AiNoticeCheck, type AiNoticeEffect, type AiNoticeField, type AiNoticeJob, type AiNoticeSettings, AiNoticesResource, type AiOperation, type AiOperatorMetrics, AiOperatorResource, type AiPage, type AiPlatformSkill, type AiPlatformSkillComposition, type AiPreparedUpload, type AiProposal, AiProposalsResource, type AiProvider, type AiProviderInfo, type AiProviderModel, AiProvidersResource, type AiPurpose, type AiRate, type AiRateInput, type AiRecord, type AiRevision, type AiRouter, type AiRouterConfig, type AiRouterTest, AiRoutersResource, type AiScope, type AiSkill, type AiSkillInput, type AiSkillNearMiss, type AiSkillVersion, AiSkillsResource, type AiSourceKind, type AiStyleAdjustment, type AiStyleAdjustmentId, AiStyleAdjustmentsResource, type AiToolId, type AiTurnPromise, type AiUploadReceiptCallback, AiUploadsResource, AiUsageResource, type AiUsageSummary, type AiUsageTokens, type AiWindow, type ApiLog, type Appointment, type AppointmentAvailability, type AppointmentExceptionInput, type AppointmentFields, type AppointmentHistory, type AppointmentQuery, type AppointmentScheduleInput, type AppointmentServiceInput, type AppointmentStatus, Appointments, type Assignment, type AvailabilityQuery, BotoZap, BotoZapError, type BotoZapErrorCode, type BotoZapEvent, type BotoZapOptions, type Broadcast, type BroadcastRecipient, type BroadcastRecipientInput, Calendar, type CalendarConnection, type CalendarJob, type CalendarSelection, type Contact, type ContactField, ContactFields, type ContactStage, ContactStages, type Conversation, type ConversationEntryPoint, type ConversationNote, type ConversationReferral, type ConversationReminder, type CreateAppointment, type CreateAssignmentParams, type CreateBroadcastParams, type CreateContactParams, type CreateCustomerParams, type CreateDemand, type CreateOpportunity, type CreateSetupLinkParams, type CreateTemplateParams, type CreateWebhookParams, type CrmActivity, type CrmConversation, type CrmFields, type CrmMetadata, type CrmQuery, type CrmRecord, CrmResource, type CursorList, type CursorPaging, type CursorParams, type Customer, type Demand, type DemandFields, type EventList, type EventPaging, Inbox, type InboxMutation, type InboxMutationResult, type InboxState, type InboxTools, type InteractiveButtonPayload, type InteractiveCtaUrlPayload, type InteractiveHeader, type InteractiveListPayload, type InteractivePayload, type Journey, type JourneyConfig, type JourneyEnrollment, type JourneyQuery, type JourneyRun, type JourneyStep, Journeys, type ListApiLogsParams, type ListBroadcastsParams, type ListContactsParams, type ListConversationsParams, type ListEventsParams, type ListMessagesParams, type ListPhoneNumbersParams, type ListRecipientsParams, type ListTemplatesParams, type ListWebhookDeliveriesParams, type Me, type MediaAsset, type MediaUploadResult, type Message, type MessageSort, type MessageSource, type MessageStatus, type MetaCostCategory, type MetaCostDay, type MetaCostEstimate, type MetaCostGroup, type MetaCostReport, type MetaCostSource, type MetaCostSync, type MetaCostUnavailableReason, type MetaCostsParams, type OffsetList, type OffsetMeta, type OffsetParams, type Opportunity, type OpportunityFields, PLAN_ERROR_CODES, type PhoneNumber, Radar, type RadarEntry, type RadarPage, type RadarQuery, type ReplyConversationParams, type RequestOptions, SavedReplies, type SavedReply, type SavedReplyInput, type SavedReplyQuery, type ScheduleBroadcastParams, type SendAudioParams, type SendDocumentParams, type SendFailureDetails, type SendImageParams, type SendInteractiveParams, type SendLocationParams, type SendMediaParams, type SendOptions, type SendReactionParams, type SendReactionResult, type SendResult, type SendTemplateParams, type SendTextParams, type SendVideoParams, type SetupLink, type StageColor, type StageRule, type StageRuleInput, type Template, type TemplatePayload, type UpdateAppointment, type UpdateBroadcastParams, type UpdateContactParams, type UpdateCustomerParams, type UpdatePhoneNumberParams, type UpdateSetupLinkParams, type UpdateWebhookParams, type UploadMediaParams, type User, WEBHOOK_CATEGORIES, type Webhook, type WebhookAuthorizationHeaders, type WebhookCategory, type WebhookDelivery, type WebhookDeliveryStatus, isPlanError };
4617
+ export { AI_CONFIGURABLE_PURPOSES, AI_CREDENTIAL_PROVIDERS, AI_OPERATIONS, AI_PURPOSES, type AddRecipientsError, type AddRecipientsResult, AgendaConfiguration, AgendaExceptions, type AgendaRecord, Ai, type AiAgent, type AiAgentConfig, type AiAgentCoverage, type AiAgentInput, type AiAgentVersion, AiAgentsResource, type AiAlert, type AiAlertBulkFilters, type AiAlertListItem, AiAlertsResource, type AiArtifactUploadInput, type AiAudioPricing, type AiBinding, type AiBindingTarget, type AiBudget, type AiBudgetInput, type AiCapabilitySignal, type AiCapabilityUsage, type AiCapabilityUsageList, type AiCase, type AiCaseChat, type AiCaseEvent, type AiCaseKind, type AiCaseReply, type AiCaseReplyInput, type AiCaseSource, AiCasesResource, type AiCatalogItems, type AiCatalogModel, type AiCatalogProduct, type AiCatalogSyncInput, type AiCatalogSyncResult, type AiChannelGate, type AiCommercialDecision, type AiCommercialEffect, type AiCommercialJob, type AiCommercialProposal, AiCommercialProposalsResource, type AiCommercialRequest, type AiCommercialSettings, type AiConfigurablePurpose, type AiContactAuthorization, type AiConversationCheckpoint, type AiCredential, AiCredentialsResource, type AiDraftResult, type AiEligibilityOverview, AiEligibilityResource, type AiEligibilitySettings, type AiEnrollment, type AiEvolution, AiEvolutionResource, type AiEvolutionSource, type AiExecution, type AiExecutionCitations, type AiExecutionSecurity, AiExecutionsResource, type AiField, type AiFlow, type AiFlowGraph, type AiFlowInput, type AiFlowSettings, type AiFlowVersion, type AiFollowupEffect, type AiFollowupEvent, AiFollowupFlowsResource, type AiFollowupPromise, type AiFollowupPromiseDetail, type AiFollowupPromiseStatus, type AiFollowupQueueFilters, type AiFollowupQueuePage, type AiFollowupQueueRow, AiFollowupsResource, type AiGateMode, type AiInference, type AiInferenceOrigin, type AiInferenceOutcome, type AiInferenceSummary, AiInferencesResource, type AiKnowledgeChunk, type AiKnowledgeCitation, type AiKnowledgeConversation, type AiKnowledgeHit, type AiKnowledgeImport, type AiKnowledgePreview, AiKnowledgeResource, type AiKnowledgeSearchDiagnostics, type AiKnowledgeSource, type AiMemory, type AiMemoryEntry, type AiMemoryEntryEvent, AiMemoryResource, type AiModelCatalogSnapshot, type AiModelCatalogSync, type AiNoticeCheck, type AiNoticeEffect, type AiNoticeField, type AiNoticeJob, type AiNoticeSettings, AiNoticesResource, type AiOperation, type AiOperatorMetrics, AiOperatorResource, type AiPage, type AiPlatformSkill, type AiPlatformSkillComposition, type AiPreparedUpload, type AiProposal, AiProposalsResource, type AiProvider, type AiProviderInfo, type AiProviderModel, AiProvidersResource, type AiPurpose, type AiRate, type AiRateInput, type AiRecord, type AiRevision, type AiRouter, type AiRouterConfig, type AiRouterTest, AiRoutersResource, type AiScope, type AiSkill, type AiSkillInput, type AiSkillNearMiss, type AiSkillVersion, AiSkillsResource, type AiSourceKind, type AiStyleAdjustment, type AiStyleAdjustmentId, AiStyleAdjustmentsResource, type AiToolId, type AiTurnPromise, type AiUploadReceiptCallback, AiUploadsResource, AiUsageResource, type AiUsageSummary, type AiUsageTokens, type AiWindow, type ApiLog, type Appointment, type AppointmentAvailability, type AppointmentExceptionInput, type AppointmentFields, type AppointmentHistory, type AppointmentQuery, type AppointmentScheduleInput, type AppointmentServiceInput, type AppointmentStatus, Appointments, type Assignment, type AvailabilityQuery, BotoZap, BotoZapError, type BotoZapErrorCode, type BotoZapEvent, type BotoZapOptions, type Broadcast, type BroadcastRecipient, type BroadcastRecipientInput, Calendar, type CalendarConnection, type CalendarJob, type CalendarSelection, type ChannelAccount, type ChannelAccountRef, ChannelAccounts, type CommentRule, type CommentRuleStatus, type Contact, type ContactField, ContactFields, type ContactStage, ContactStages, type Conversation, type ConversationEntryPoint, type ConversationNote, type ConversationReferral, type ConversationReminder, type CreateAppointment, type CreateAssignmentParams, type CreateBroadcastParams, type CreateCommentRuleParams, type CreateContactParams, type CreateCustomerParams, type CreateDemand, type CreateOpportunity, type CreateSetupLinkParams, type CreateTemplateParams, type CreateWebhookParams, type CrmActivity, type CrmConversation, type CrmFields, type CrmMetadata, type CrmQuery, type CrmRecord, CrmResource, type CursorList, type CursorPaging, type CursorParams, type Customer, type Demand, type DemandFields, type EventList, type EventPaging, Inbox, type InboxMutation, type InboxMutationResult, type InboxState, type InboxTools, type InstagramTokenStatus, type InteractiveButtonPayload, type InteractiveCtaUrlPayload, type InteractiveHeader, type InteractiveListPayload, type InteractivePayload, type Journey, type JourneyConfig, type JourneyEnrollment, type JourneyQuery, type JourneyRun, type JourneyStep, Journeys, type ListApiLogsParams, type ListBroadcastsParams, type ListChannelAccountsParams, type ListContactsParams, type ListConversationsParams, type ListEventsParams, type ListMessagesParams, type ListPhoneNumbersParams, type ListRecipientsParams, type ListTemplatesParams, type ListWebhookDeliveriesParams, type Me, type MediaAsset, type MediaUploadResult, type Message, type MessageChannel, type MessageContent, type MessageEdit, type MessageSort, type MessageSource, type MessageStatus, type MetaCostCategory, type MetaCostDay, type MetaCostEstimate, type MetaCostGroup, type MetaCostReport, type MetaCostSource, type MetaCostSync, type MetaCostUnavailableReason, type MetaCostsParams, type OffsetList, type OffsetMeta, type OffsetParams, type Opportunity, type OpportunityFields, PLAN_ERROR_CODES, type PhoneNumber, type QuickReply, Radar, type RadarEntry, type RadarPage, type RadarQuery, type ReplyConversationParams, type RequestOptions, SavedReplies, type SavedReply, type SavedReplyInput, type SavedReplyQuery, type ScheduleBroadcastParams, type SendAudioParams, type SendDocumentParams, type SendFailureDetails, type SendImageParams, type SendInteractiveParams, type SendLocationParams, type SendMediaParams, type SendOptions, type SendReactionParams, type SendReactionResult, type SendResult, type SendTemplateParams, type SendTextParams, type SendVideoParams, type SetupLink, type StageColor, type StageRule, type StageRuleInput, type Template, type TemplatePayload, type UpdateAppointment, type UpdateBroadcastParams, type UpdateCommentRuleParams, type UpdateContactParams, type UpdateCustomerParams, type UpdatePhoneNumberParams, type UpdateSetupLinkParams, type UpdateWebhookParams, type UploadMediaParams, type User, WEBHOOK_CATEGORIES, type Webhook, type WebhookAuthorizationHeaders, type WebhookCategory, type WebhookDelivery, type WebhookDeliveryStatus, isPlanError };
package/dist/index.js CHANGED
@@ -5100,7 +5100,8 @@ var Messages = class {
5100
5100
  to: params.to,
5101
5101
  type: "text",
5102
5102
  text: { body: params.text },
5103
- from: params.from
5103
+ from: params.from,
5104
+ ...params.quick_replies !== void 0 ? { quick_replies: params.quick_replies } : {}
5104
5105
  }
5105
5106
  });
5106
5107
  return assertSendResult(result);
@@ -5164,8 +5165,8 @@ var Messages = class {
5164
5165
  );
5165
5166
  }
5166
5167
  /**
5167
- * Reage a uma mensagem recebida (WhatsApp). `emoji: ""` retira a reação.
5168
- * O retorno traz `reaction` com o alvo e a ação.
5168
+ * Reage a uma mensagem recebida (WhatsApp ou Instagram). `emoji: ""` retira
5169
+ * a reação. O retorno traz `reaction` com o alvo e a ação.
5169
5170
  */
5170
5171
  async sendReaction(params, options = {}) {
5171
5172
  return postMessage(
@@ -5212,10 +5213,12 @@ async function postMessage(client, body, options) {
5212
5213
  return assertSendResult(result);
5213
5214
  }
5214
5215
  function assertSendResult(value) {
5215
- if (typeof value.wamid !== "string" || typeof value.to !== "string" || typeof value.status !== "string" || value.id !== null && typeof value.id !== "string") {
5216
+ const hasWamid = typeof value?.wamid === "string";
5217
+ const hasExternalId = value?.wamid === null && typeof value.external_id === "string" && value.external_id !== "";
5218
+ if (!value || !(hasWamid || hasExternalId) || typeof value.to !== "string" || typeof value.status !== "string" || value.id !== null && typeof value.id !== "string") {
5216
5219
  throw new BotoZapError(
5217
5220
  "malformed_response",
5218
- "resposta de envio sem id/wamid/to/status v\xE1lidos",
5221
+ "resposta de envio sem id/wamid (ou external_id)/to/status v\xE1lidos",
5219
5222
  0
5220
5223
  );
5221
5224
  }
@@ -5480,12 +5483,16 @@ var Conversations = class {
5480
5483
  {
5481
5484
  query: {
5482
5485
  limit: params.limit,
5486
+ customer_id: params.customer_id,
5487
+ agent_paused: params.agent_paused === void 0 ? void 0 : String(params.agent_paused),
5483
5488
  after: params.after,
5484
5489
  before: params.before,
5485
5490
  phone_number_id: params.phone_number_id,
5486
5491
  status: params.status,
5487
5492
  contact: params.contact,
5488
- phone_number: params.phone_number
5493
+ phone_number: params.phone_number,
5494
+ channel: params.channel,
5495
+ channel_account_id: params.channel_account_id
5489
5496
  }
5490
5497
  }
5491
5498
  );
@@ -5497,17 +5504,19 @@ var Conversations = class {
5497
5504
  );
5498
5505
  }
5499
5506
  /**
5500
- * Responde uma Conversa sem o chamador precisar combinar Contato e Número.
5501
- * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
5502
- * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
5507
+ * Responde uma Conversa sem o chamador precisar combinar Contato e origem.
5508
+ * No WhatsApp a origem é o Número da Conversa; no Instagram, a Conta de
5509
+ * canal (`channel_account.id`). A leitura e o envio usam a mesma chave; o
5510
+ * POST /messages revalida Conta, ambiente, identidade, janela, quota e
5511
+ * billing antes de chamar a Meta.
5503
5512
  */
5504
5513
  async reply(id, params, options = {}) {
5505
5514
  const conversation = await this.get(id);
5506
- const from = conversation.phone_number_id;
5515
+ const from = conversation.channel === "instagram" ? conversation.channel_account?.id : conversation.phone_number_id;
5507
5516
  if (typeof from !== "string" || !from.trim()) {
5508
5517
  throw new BotoZapError(
5509
5518
  "malformed_response",
5510
- "Conversa sem UUID interno do N\xFAmero de origem.",
5519
+ conversation.channel === "instagram" ? "Conversa do Instagram sem UUID da Conta de canal de origem." : "Conversa sem UUID interno do N\xFAmero de origem.",
5511
5520
  0
5512
5521
  );
5513
5522
  }
@@ -5520,7 +5529,15 @@ var Conversations = class {
5520
5529
  422
5521
5530
  );
5522
5531
  }
5523
- return this.client.messages.send({ to, text: params.text, from }, options);
5532
+ return this.client.messages.send(
5533
+ {
5534
+ to,
5535
+ text: params.text,
5536
+ from,
5537
+ ...params.quick_replies !== void 0 ? { quick_replies: params.quick_replies } : {}
5538
+ },
5539
+ options
5540
+ );
5524
5541
  }
5525
5542
  update(id, params) {
5526
5543
  return this.client.requestItem(
@@ -5662,6 +5679,74 @@ function enc6(id) {
5662
5679
  return encodeURIComponent(id);
5663
5680
  }
5664
5681
 
5682
+ // src/resources/channel-accounts.ts
5683
+ var ChannelAccounts = class {
5684
+ constructor(client) {
5685
+ this.client = client;
5686
+ }
5687
+ client;
5688
+ /** Lista as Contas de canal da conta (paginação por offset/página). numbers:read. */
5689
+ list(params = {}) {
5690
+ return this.client.requestOffsetList(
5691
+ "GET",
5692
+ "/channel_accounts",
5693
+ {
5694
+ query: {
5695
+ page: params.page,
5696
+ per_page: params.per_page,
5697
+ channel: params.channel,
5698
+ customer_id: params.customer_id
5699
+ }
5700
+ }
5701
+ );
5702
+ }
5703
+ /** Busca uma Conta de canal pelo UUID interno ou pelo id na Meta (`external_id`). numbers:read. */
5704
+ get(id) {
5705
+ return this.client.requestItem("GET", `/channel_accounts/${enc7(id)}`);
5706
+ }
5707
+ /** Lista as Regras de comentário de uma Conta do Instagram (UUID). comment-rules:read. */
5708
+ listCommentRules(channelAccountId, params = {}) {
5709
+ return this.client.requestOffsetList(
5710
+ "GET",
5711
+ `/channel_accounts/${enc7(channelAccountId)}/comment-rules`,
5712
+ { query: { page: params.page, per_page: params.per_page } }
5713
+ );
5714
+ }
5715
+ /** Busca uma Regra de comentário. comment-rules:read. */
5716
+ getCommentRule(channelAccountId, ruleId) {
5717
+ return this.client.requestItem(
5718
+ "GET",
5719
+ `/channel_accounts/${enc7(channelAccountId)}/comment-rules/${enc7(ruleId)}`
5720
+ );
5721
+ }
5722
+ /**
5723
+ * Cria uma Regra de comentário. comment-rules:write. Exige plano que inclua
5724
+ * Regras de comentário (senão 422 `plan_restricted`); palavra-chave repetida
5725
+ * para o mesmo alvo é 409 `duplicate_rule`.
5726
+ */
5727
+ createCommentRule(channelAccountId, params) {
5728
+ return this.client.requestItem(
5729
+ "POST",
5730
+ `/channel_accounts/${enc7(channelAccountId)}/comment-rules`,
5731
+ { body: params }
5732
+ );
5733
+ }
5734
+ /**
5735
+ * Altera uma Regra de comentário (só os campos enviados). comment-rules:write.
5736
+ * `is_active: false` desliga a regra; não há exclusão pela API.
5737
+ */
5738
+ updateCommentRule(channelAccountId, ruleId, params) {
5739
+ return this.client.requestItem(
5740
+ "PATCH",
5741
+ `/channel_accounts/${enc7(channelAccountId)}/comment-rules/${enc7(ruleId)}`,
5742
+ { body: params }
5743
+ );
5744
+ }
5745
+ };
5746
+ function enc7(id) {
5747
+ return encodeURIComponent(id);
5748
+ }
5749
+
5665
5750
  // src/resources/media.ts
5666
5751
  var Media = class {
5667
5752
  constructor(client) {
@@ -5820,6 +5905,8 @@ var BotoZap = class {
5820
5905
  conversations;
5821
5906
  webhooks;
5822
5907
  phoneNumbers;
5908
+ /** Contas de canal (WhatsApp e Instagram) e Regras de comentário do Instagram. */
5909
+ channelAccounts;
5823
5910
  contactStages;
5824
5911
  contactFields;
5825
5912
  calendar;
@@ -5873,6 +5960,7 @@ var BotoZap = class {
5873
5960
  this.conversations = new Conversations(this);
5874
5961
  this.webhooks = new Webhooks(this);
5875
5962
  this.phoneNumbers = new PhoneNumbers(this);
5963
+ this.channelAccounts = new ChannelAccounts(this);
5876
5964
  this.media = new Media(this);
5877
5965
  this.events = new Events(this);
5878
5966
  this.usage = new Usage(this);
@@ -6071,6 +6159,7 @@ export {
6071
6159
  BotoZap,
6072
6160
  BotoZapError,
6073
6161
  Calendar,
6162
+ ChannelAccounts,
6074
6163
  ContactFields,
6075
6164
  ContactStages,
6076
6165
  CrmResource,