@botozap/sdk 0.8.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # @botozap/sdk
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Cover the API additions of 2026-09-29:
8
+
9
+ - SDK: `messages.sendInteractive` (button/list/cta_url in Cloud API shape, typed as `InteractivePayload`), `messages.sendLocation` and `messages.sendReaction` (target is the internal UUID or wamid of a received message; `emoji: ""` removes it; `SendResult.reaction` echoes target and action). `messages.list({ sort: "created_at" | "event_at" })`; `Message.source` (`MessageSource`), `created_at`, `event_at` and `Conversation.last_message`. `WEBHOOK_CATEGORIES` with the opt-in `app_messages` category; `WebhookDeliveryStatus` gains `limited`. `ai.providers.get()` types `providers` as `AiProviderInfo` with `accepts_new_credentials`; `AI_CREDENTIAL_PROVIDERS` (openai, anthropic). `BotoZapErrorCode`, `PLAN_ERROR_CODES` and `isPlanError` for `plan_restricted`, `free_form_limit_reached` and `free_number_cap`.
10
+ - CLI: `messages send-interactive`, `messages send-location`, `messages react` (`--remove`), `messages list --sort` and an ORIGEM column; help for `app_messages` and `limited`.
11
+ - MCP: `send_message` accepts `interactive`, `location` and `reaction`; `list_messages` accepts `sort`; `send_message` output includes `reaction`; delivery status `limited`; webhook tools document `app_messages`.
12
+
13
+ - ca116b8: Add authenticated account introspection through `boto.me.get()`. MCP initializes from `/me`, limits its tools to the credential scopes and environment, and declares tool safety annotations.
14
+
15
+ Deploy the BotoZap API with `GET /v1/me` before upgrading MCP. MCP startup fails closed when introspection is unavailable; it does not fall back to the complete tool catalog.
16
+
17
+ Compact MCP JSON responses and publish the validated schema projection for typed entities. Preserve business content and pagination, expose webhook signing secrets only at creation, and clarify tool identifiers and side effects.
18
+
19
+ Compatibility changes:
20
+
21
+ - Tools outside the credential scopes or supported environment are omitted from discovery. OAuth additionally requires the concrete API routes used by each tool; operations still pass through API authorization.
22
+ - In Streamable HTTP, a session caches its identity for 60 seconds. API keys remain bound to their original fingerprint. OAuth bearer changes trigger introspection and must preserve the account, environment, user, client and grant. Tools and event polls share the cache and concurrent refresh; API calls still authorize each operation.
23
+ - Typed MCP results now discard fields outside their schemas in both `structuredContent` and legacy JSON text. The reviewed endpoint responses have no identified public field removed by this change; `list_users.data[].id` and its `user_id` alias were already declared and remain available. Webhook `secret` is retained only in `create_webhook`; it is excluded from list/get/update results. `authorization_secret_id`, `private_trace` and `internal_debug` are concrete extras discarded by regression fixtures, not fields currently returned by the reviewed API presenters.
24
+ - Deploy and verify `GET /v1/me` on every supported API base URL **before publishing either SDK or MCP**. Versionless `npx @botozap/mcp` or `pnpm dlx @botozap/mcp` can pick up the new release immediately; delaying the API deploy would break their session initialization.
25
+
26
+ The field audit and ordered release checks are recorded in `docs/chatgpt-phase1-release.md`.
27
+
28
+ - ef10a36: Add optional `idempotencyKey` options to `messages.send`, `sendTemplate`, `sendMedia` and `conversations.reply`. Calls without this option retain their existing HTTP payload and behavior.
29
+
30
+ MCP send tools accept optional `idempotency_key`: call the read-only `prepare_send_intent` once before a new send, or reuse `draft.idempotency_key` returned by `stage_review_reply`. Keep the same key and payload after a timeout. Never generate a replacement key to bypass pending/conflicting sends. Existing tool calls remain valid without a key or preparation step and retain legacy behavior. New review UI sends always include a key; public API clients and ordinary SDK callers may also continue omitting the header.
31
+
32
+ Add an opt-in MCP Apps review panel (`BOTOZAP_MCP_UI_ENABLED=true`), thread entrypoint, Radar/history context, explicit confirmation and retry using the original intent. The UI bundle is packaged locally with no external assets. Deploy API idempotency support before upgrading these send tools. Plugin manifests are local candidates, not published directory listings.
33
+
34
+ - 9453f19: Support OAuth bearer credentials and rotating access-token providers in the SDK. MCP publishes protected-resource metadata, validates each request against account introspection, and binds OAuth sessions to the user, client, grant and account so token refresh preserves the connection.
35
+
36
+ Require current scopes and allowed routes for tools and background event reads. API-key authentication retains its existing behavior. Enable OAuth only after deploying the coordinated BotoZap authorization endpoints and grant policies.
37
+
38
+ ### Patch Changes
39
+
40
+ - bc67b0c: Preserve the API's validated `outcome` and `retry` enums on SDK/MCP errors. Confirmed rejection releases the idempotency claim, so the same key can retry after backoff or correction. The review UI unlocks a confirmed rejection and keeps unknown outcomes protected. Existing calls without keys remain unchanged.
41
+
3
42
  ## 0.8.0
4
43
 
5
44
  ### Minor Changes
package/README.md CHANGED
@@ -95,8 +95,49 @@ await boto.messages.send({
95
95
  await boto.conversations.reply("uuid-da-conversa", {
96
96
  text: "Resposta do agente",
97
97
  });
98
+
99
+ // Botões de resposta, lista ou botão de link (objeto interactive da Cloud API)
100
+ await boto.messages.sendInteractive({
101
+ to: "+5531988887777",
102
+ interactive: {
103
+ type: "button",
104
+ body: { text: "Confirma o horário?" },
105
+ action: {
106
+ buttons: [
107
+ { type: "reply", reply: { id: "sim", title: "Sim" } },
108
+ { type: "reply", reply: { id: "nao", title: "Não" } },
109
+ ],
110
+ },
111
+ },
112
+ });
113
+
114
+ // Localização
115
+ await boto.messages.sendLocation({
116
+ to: "+5531988887777",
117
+ latitude: -3.119,
118
+ longitude: -60.0217,
119
+ name: "Loja Centro",
120
+ });
121
+
122
+ // Reação a uma mensagem RECEBIDA (UUID interno ou wamid, até 30 dias); "" retira
123
+ const r = await boto.messages.sendReaction({
124
+ to: "+5531988887777",
125
+ message_id: "wamid.HBgM...",
126
+ emoji: "👍",
127
+ });
128
+ r.reaction?.action; // "react" | "unreact"
129
+
130
+ // Listar na ordem real das mensagens (histórico importado incluído)
131
+ const page = await boto.messages.list({ sort: "event_at", limit: 50 });
132
+ page.data[0]?.source; // "api" | "app" | "history" | "broadcast"
98
133
  ```
99
134
 
135
+ Interactive, localização e reação são mensagens livres: exigem a janela de 24h
136
+ aberta. A API valida o `interactive` (limites da Cloud API) e recusa com `422
137
+ invalid_request`; reação recusa com `invalid_reaction`, `missing_reaction_target`,
138
+ `reaction_target_not_found`, `reaction_target_invalid` ou `reaction_target_expired`.
139
+ O cursor de `messages.list` vale só para o `sort` que o gerou.
140
+
100
141
  ## Clientes e templates
101
142
 
102
143
  ```ts
@@ -209,6 +250,33 @@ catch (err) {
209
250
 
210
251
  `err.headers` traz só os headers da resposta — nenhuma credencial de request entra nele.
211
252
 
253
+ ### Recusas de plano
254
+
255
+ `isPlanError(err)` reconhece recusas que só um upgrade resolve (retry não):
256
+ `403 plan_restricted` nas escritas de IA, Agenda, Calendário, Jornadas e execuções
257
+ (`422 plan_restricted` em funil, aquecimento e regras de comentário),
258
+ `429 free_form_limit_reached` (limite de mensagens 1:1 do Free) e
259
+ `402 free_number_cap` no setup além do teto de Números do Free. Credencial de IA
260
+ nova só para `openai`/`anthropic` (`AI_CREDENTIAL_PROVIDERS`; os demais respondem
261
+ `422 provider_not_enabled`); `ai.providers.get()` traz `accepts_new_credentials`
262
+ por provedor.
263
+
264
+ ```ts
265
+ import { isPlanError } from "@botozap/sdk";
266
+
267
+ catch (err) {
268
+ if (isPlanError(err)) mostrarUpgrade(err.code);
269
+ }
270
+ ```
271
+
272
+ ### Webhooks
273
+
274
+ `WEBHOOK_CATEGORIES` lista as categorias de `webhooks.create({ events })`:
275
+ `messages`, `statuses`, `crm`, `account` (inclui `whatsapp.phone_number.connected`)
276
+ e `app_messages`, opt-in, com `whatsapp.message.echo`, `.edited` e `.revoked` do
277
+ app WhatsApp Business em coexistência. Em `webhookDeliveries.list`, o status
278
+ `limited` marca a entrega cortada pelo limite de repasse do Free (sem retry).
279
+
212
280
  ## Configuração
213
281
 
214
282
  ```ts
@@ -238,8 +306,17 @@ O SDK cobre os recursos da API `/v1`:
238
306
  - `media` — subir arquivo (obter um media_id) e **buscar metadados + URL de download** de uma mídia recebida
239
307
  - `events` — reler inbound e mudanças de status pelo cursor durável da Conta/ambiente
240
308
  - `usage` — `metaCosts`: custo aproximado da Meta por dia, categoria e moeda (Pricing Analytics), com estimativa por tarifa publicada onde a Meta não devolveu custo
309
+ - `me` — `get`: Conta, ambiente (`live` ou `sandbox`) e scopes efetivos da chave autenticada; não retorna a chave nem uma identidade pessoal
241
310
  - `users`, `apiLogs`, `webhookDeliveries` — leitura
242
311
 
312
+ `me.get()` é útil para conferir a identidade configurada antes de executar
313
+ operações em uma integração:
314
+
315
+ ```ts
316
+ const identity = await boto.me.get();
317
+ // { account_id: "…", environment: "live", scopes: ["messages:write"] }
318
+ ```
319
+
243
320
  Inbound e mudanças de status compartilham um stream crescente. Guarde
244
321
  `paging.cursor` e use-o como `after` na leitura seguinte; após uma desconexão,
245
322
  isso recupera o intervalo persistido sem depender de memória do processo:
@@ -385,3 +462,43 @@ substitui snapshots nem transforma uma inferência incerta em custo zero.
385
462
 
386
463
  A CLI `ai usage save-rate` recebe o mesmo JSON por `--input-file`; o MCP expõe
387
464
  `audio_pricing` opcional e anulável na ferramenta `ai_usage_save_rate`.
465
+
466
+ ## Token OAuth
467
+
468
+ Além de `apiKey`, o cliente aceita `accessToken`. Um provider permite usar o token renovado em cada requisição:
469
+
470
+ ```ts
471
+ const boto = new BotoZap({
472
+ accessToken: async () => getCurrentOAuthAccessToken(),
473
+ });
474
+ await boto.contacts.list();
475
+ ```
476
+
477
+ Informe uma única credencial. O SDK envia `Authorization: Bearer` e não realiza o fluxo de login ou a renovação; o aplicativo fornece o token atual. `boto.me.get()` devolve os scopes e, para OAuth, `auth_type`, `user_id`, `client_id`, `grant_id` e `allowed_routes`. A autorização sempre é revalidada pelo servidor.
478
+
479
+
480
+ ### Repetir um envio sem duplicar a intenção
481
+
482
+ A opção `idempotencyKey` é opcional. Crie uma chave antes da primeira tentativa
483
+ e preserve-a se perder a resposta; o corpo e a credencial também devem ser os
484
+ mesmos. Sem a opção, o SDK mantém o comportamento anterior.
485
+
486
+ ```ts
487
+ const options = { idempotencyKey: crypto.randomUUID() };
488
+ await boto.messages.send({ to: "5511999999999", text: "Seu pedido está pronto." }, options);
489
+ // Retry da mesma intenção: use novamente o mesmo payload e options.
490
+ ```
491
+
492
+ `sendTemplate`, `sendMedia` e `conversations.reply` aceitam a mesma opção como
493
+ último argumento. O servidor retorna a resposta original; payload diferente ou
494
+ tentativa pendente retornam 409. Resultados terminais ficam disponíveis por 24h.
495
+ Pendências desconhecidas não reabrem automaticamente. Depois de 24h, confira o
496
+ histórico antes de reenviar; nunca troque a chave para contornar uma pendência.
497
+ Requer a API com suporte a `Idempotency-Key` em `POST /v1/messages`.
498
+
499
+ Recusas confirmadas (`outcome: rejected`) liberam a chave. Aguarde o backoff ou
500
+ corrija a causa e repita com a mesma chave; após liberação, outro payload é uma
501
+ nova intenção. `unknown` ou `accepted` exigem conciliação antes de considerar
502
+ outro envio. SDK e MCP preservam `outcome` e `retry` da API. Resultados concluídos
503
+ vencidos são removidos pelo cron a cada minuto; claims incertas não são removidas
504
+ por tempo, conforme o runbook `botozap/docs/ops/message-send-receipts.md`.
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AI_CONFIGURABLE_PURPOSES: () => AI_CONFIGURABLE_PURPOSES,
24
+ AI_CREDENTIAL_PROVIDERS: () => AI_CREDENTIAL_PROVIDERS,
24
25
  AI_OPERATIONS: () => AI_OPERATIONS,
25
26
  AI_PURPOSES: () => AI_PURPOSES,
26
27
  AgendaConfiguration: () => AgendaConfiguration,
@@ -57,8 +58,11 @@ __export(index_exports, {
57
58
  CrmResource: () => CrmResource,
58
59
  Inbox: () => Inbox,
59
60
  Journeys: () => Journeys,
61
+ PLAN_ERROR_CODES: () => PLAN_ERROR_CODES,
60
62
  Radar: () => Radar,
61
- SavedReplies: () => SavedReplies
63
+ SavedReplies: () => SavedReplies,
64
+ WEBHOOK_CATEGORIES: () => WEBHOOK_CATEGORIES,
65
+ isPlanError: () => isPlanError
62
66
  });
63
67
  module.exports = __toCommonJS(index_exports);
64
68
 
@@ -103,16 +107,28 @@ function assertAudioPricing(value) {
103
107
  var BotoZapError = class extends Error {
104
108
  code;
105
109
  status;
110
+ outcome;
111
+ retry;
106
112
  /** Headers da resposta HTTP. Ausente em erros sem resposta (status 0). */
107
113
  headers;
108
- constructor(code, message, status, headers) {
114
+ constructor(code, message, status, headers, details) {
109
115
  super(message);
110
116
  this.name = "BotoZapError";
111
117
  this.code = code;
112
118
  this.status = status;
113
119
  this.headers = headers;
120
+ this.outcome = details?.outcome;
121
+ this.retry = details?.retry;
114
122
  }
115
123
  };
124
+ var PLAN_ERROR_CODES = [
125
+ "plan_restricted",
126
+ "free_form_limit_reached",
127
+ "free_number_cap"
128
+ ];
129
+ function isPlanError(error) {
130
+ return error instanceof BotoZapError && PLAN_ERROR_CODES.includes(error.code);
131
+ }
116
132
 
117
133
  // src/resources/ai/upload.ts
118
134
  var receipts = /* @__PURE__ */ new WeakMap();
@@ -3877,6 +3893,7 @@ var AI_OPERATIONS = [
3877
3893
  ];
3878
3894
 
3879
3895
  // src/resources/ai/types.ts
3896
+ var AI_CREDENTIAL_PROVIDERS = ["openai", "anthropic"];
3880
3897
  var AI_PURPOSES = [
3881
3898
  "default",
3882
3899
  "agent_turn",
@@ -4000,7 +4017,7 @@ var AiCredentialsResource = class {
4000
4017
  get(input) {
4001
4018
  return request(this.client, AI_OPERATIONS[11], input);
4002
4019
  }
4003
- /** Cria credencial própria no Vault; a resposta nunca contém a chave. */
4020
+ /** Cria credencial própria no Vault; a resposta nunca contém a chave. Só `AI_CREDENTIAL_PROVIDERS` (openai/anthropic); os demais: 422 `provider_not_enabled`. */
4004
4021
  create(input) {
4005
4022
  return request(this.client, AI_OPERATIONS[12], input);
4006
4023
  }
@@ -5144,8 +5161,9 @@ var Messages = class {
5144
5161
  }
5145
5162
  client;
5146
5163
  /** Envia uma mensagem de texto. */
5147
- async send(params) {
5164
+ async send(params, options = {}) {
5148
5165
  const result = await this.client.requestObject("POST", "/messages", {
5166
+ idempotencyKey: options.idempotencyKey,
5149
5167
  body: {
5150
5168
  to: params.to,
5151
5169
  type: "text",
@@ -5156,8 +5174,9 @@ var Messages = class {
5156
5174
  return assertSendResult(result);
5157
5175
  }
5158
5176
  /** Envia uma mensagem usando um template aprovado. */
5159
- async sendTemplate(params) {
5177
+ async sendTemplate(params, options = {}) {
5160
5178
  const result = await this.client.requestObject("POST", "/messages", {
5179
+ idempotencyKey: options.idempotencyKey,
5161
5180
  body: {
5162
5181
  to: params.to,
5163
5182
  type: "template",
@@ -5168,7 +5187,7 @@ var Messages = class {
5168
5187
  return assertSendResult(result);
5169
5188
  }
5170
5189
  /** Envia mídia por URL pública. */
5171
- async sendMedia(params) {
5190
+ async sendMedia(params, options = {}) {
5172
5191
  const media = { link: params.link };
5173
5192
  if ("caption" in params && params.caption !== void 0) {
5174
5193
  media.caption = params.caption;
@@ -5177,6 +5196,7 @@ var Messages = class {
5177
5196
  media.filename = params.filename;
5178
5197
  }
5179
5198
  const result = await this.client.requestObject("POST", "/messages", {
5199
+ idempotencyKey: options.idempotencyKey,
5180
5200
  body: {
5181
5201
  to: params.to,
5182
5202
  from: params.from,
@@ -5186,6 +5206,47 @@ var Messages = class {
5186
5206
  });
5187
5207
  return assertSendResult(result);
5188
5208
  }
5209
+ /**
5210
+ * Envia botões de resposta, lista ou botão de link (WhatsApp; mensagem livre,
5211
+ * exige janela de 24h aberta).
5212
+ */
5213
+ async sendInteractive(params, options = {}) {
5214
+ return postMessage(
5215
+ this.client,
5216
+ { to: params.to, from: params.from, type: "interactive", interactive: params.interactive },
5217
+ options
5218
+ );
5219
+ }
5220
+ /** Envia uma localização (WhatsApp; mensagem livre). */
5221
+ async sendLocation(params, options = {}) {
5222
+ const location = {
5223
+ latitude: params.latitude,
5224
+ longitude: params.longitude
5225
+ };
5226
+ if (params.name !== void 0) location.name = params.name;
5227
+ if (params.address !== void 0) location.address = params.address;
5228
+ return postMessage(
5229
+ this.client,
5230
+ { to: params.to, from: params.from, type: "location", location },
5231
+ options
5232
+ );
5233
+ }
5234
+ /**
5235
+ * Reage a uma mensagem recebida (WhatsApp). `emoji: ""` retira a reação.
5236
+ * O retorno traz `reaction` com o alvo e a ação.
5237
+ */
5238
+ async sendReaction(params, options = {}) {
5239
+ return postMessage(
5240
+ this.client,
5241
+ {
5242
+ to: params.to,
5243
+ from: params.from,
5244
+ type: "reaction",
5245
+ reaction: { message_id: params.message_id, emoji: params.emoji }
5246
+ },
5247
+ options
5248
+ );
5249
+ }
5189
5250
  /** Lista as mensagens da conta (paginação por cursor). */
5190
5251
  list(params = {}) {
5191
5252
  return this.client.requestCursorList("GET", "/messages", {
@@ -5193,6 +5254,7 @@ var Messages = class {
5193
5254
  limit: params.limit,
5194
5255
  after: params.after,
5195
5256
  before: params.before,
5257
+ sort: params.sort,
5196
5258
  phone_number_id: params.phone_number_id,
5197
5259
  conversation_id: params.conversation_id,
5198
5260
  direction: params.direction,
@@ -5210,6 +5272,13 @@ var Messages = class {
5210
5272
  );
5211
5273
  }
5212
5274
  };
5275
+ async function postMessage(client, body, options) {
5276
+ const result = await client.requestObject("POST", "/messages", {
5277
+ idempotencyKey: options.idempotencyKey,
5278
+ body
5279
+ });
5280
+ return assertSendResult(result);
5281
+ }
5213
5282
  function assertSendResult(value) {
5214
5283
  if (typeof value.wamid !== "string" || typeof value.to !== "string" || typeof value.status !== "string" || value.id !== null && typeof value.id !== "string") {
5215
5284
  throw new BotoZapError(
@@ -5500,7 +5569,7 @@ var Conversations = class {
5500
5569
  * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
5501
5570
  * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
5502
5571
  */
5503
- async reply(id, params) {
5572
+ async reply(id, params, options = {}) {
5504
5573
  const conversation = await this.get(id);
5505
5574
  const from = conversation.phone_number_id;
5506
5575
  if (typeof from !== "string" || !from.trim()) {
@@ -5519,7 +5588,7 @@ var Conversations = class {
5519
5588
  422
5520
5589
  );
5521
5590
  }
5522
- return this.client.messages.send({ to, text: params.text, from });
5591
+ return this.client.messages.send({ to, text: params.text, from }, options);
5523
5592
  }
5524
5593
  update(id, params) {
5525
5594
  return this.client.requestItem(
@@ -5796,6 +5865,18 @@ var WebhookDeliveries = class {
5796
5865
  }
5797
5866
  };
5798
5867
 
5868
+ // src/resources/me.ts
5869
+ var MeResource = class {
5870
+ constructor(client) {
5871
+ this.client = client;
5872
+ }
5873
+ client;
5874
+ /** Retorna a Conta, o ambiente e os scopes efetivos da chave. */
5875
+ get() {
5876
+ return this.client.requestItem("GET", "/me");
5877
+ }
5878
+ };
5879
+
5799
5880
  // src/client.ts
5800
5881
  var DEFAULT_BASE_URL = "https://botozap.com.br/api/v1";
5801
5882
  var BotoZap = class {
@@ -5824,14 +5905,15 @@ var BotoZap = class {
5824
5905
  users;
5825
5906
  apiLogs;
5826
5907
  webhookDeliveries;
5827
- apiKey;
5908
+ me;
5909
+ credential;
5828
5910
  baseUrl;
5829
5911
  fetchImpl;
5830
5912
  constructor(options) {
5831
- if (!options || !options.apiKey) {
5832
- throw new Error("BotoZap: apiKey \xE9 obrigat\xF3rio.");
5913
+ if (!options || Boolean(options.apiKey) === Boolean(options.accessToken)) {
5914
+ throw new Error("BotoZap: informe apenas apiKey ou accessToken.");
5833
5915
  }
5834
- this.apiKey = options.apiKey;
5916
+ this.credential = options.accessToken ?? options.apiKey;
5835
5917
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
5836
5918
  const resolvedFetch = options.fetch ?? globalThis.fetch;
5837
5919
  if (typeof resolvedFetch !== "function") {
@@ -5865,6 +5947,7 @@ var BotoZap = class {
5865
5947
  this.users = new Users(this);
5866
5948
  this.apiLogs = new ApiLogs(this);
5867
5949
  this.webhookDeliveries = new WebhookDeliveries(this);
5950
+ this.me = new MeResource(this);
5868
5951
  }
5869
5952
  /** PUT de artefato em URL assinada, sem token BotoZap nem cookies. Não segue redirecionamentos. */
5870
5953
  async putArtifact(url, contentType, file) {
@@ -5906,12 +5989,16 @@ var BotoZap = class {
5906
5989
  if (value !== void 0) url.searchParams.set(key, String(value));
5907
5990
  }
5908
5991
  }
5992
+ const credential = typeof this.credential === "function" ? await this.credential() : this.credential;
5993
+ if (!credential || /[\s,]/.test(credential)) {
5994
+ throw new BotoZapError("invalid_credential", "Credencial Bearer inv\xE1lida.", 401);
5995
+ }
5909
5996
  let res;
5910
5997
  try {
5911
5998
  res = await this.fetchImpl(url.toString(), {
5912
5999
  method,
5913
6000
  headers: {
5914
- Authorization: `Bearer ${this.apiKey}`,
6001
+ Authorization: `Bearer ${credential}`,
5915
6002
  ...opts.body instanceof FormData ? {} : { "Content-Type": "application/json" },
5916
6003
  Accept: "application/json",
5917
6004
  ...opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : {}
@@ -5920,6 +6007,7 @@ var BotoZap = class {
5920
6007
  signal: opts.signal
5921
6008
  });
5922
6009
  } catch (cause) {
6010
+ if (cause instanceof BotoZapError) throw cause;
5923
6011
  const detail = cause instanceof Error ? cause.message : String(cause);
5924
6012
  throw new BotoZapError(
5925
6013
  "network_error",
@@ -5940,7 +6028,11 @@ var BotoZap = class {
5940
6028
  envelope?.error?.code ?? "http_error",
5941
6029
  envelope?.error?.message ?? `HTTP ${res.status}`,
5942
6030
  res.status,
5943
- headers
6031
+ headers,
6032
+ {
6033
+ outcome: envelope?.error?.outcome === "rejected" || envelope?.error?.outcome === "accepted" || envelope?.error?.outcome === "unknown" ? envelope.error.outcome : void 0,
6034
+ retry: envelope?.error?.retry === "backoff" || envelope?.error?.retry === "after_correction" || envelope?.error?.retry === "reconcile_first" || envelope?.error?.retry === "unknown" ? envelope.error.retry : void 0
6035
+ }
5944
6036
  );
5945
6037
  }
5946
6038
  return data;
@@ -6004,9 +6096,19 @@ function safeJson(text) {
6004
6096
  return text;
6005
6097
  }
6006
6098
  }
6099
+
6100
+ // src/types.ts
6101
+ var WEBHOOK_CATEGORIES = [
6102
+ "messages",
6103
+ "statuses",
6104
+ "crm",
6105
+ "account",
6106
+ "app_messages"
6107
+ ];
6007
6108
  // Annotate the CommonJS export names for ESM import in node:
6008
6109
  0 && (module.exports = {
6009
6110
  AI_CONFIGURABLE_PURPOSES,
6111
+ AI_CREDENTIAL_PROVIDERS,
6010
6112
  AI_OPERATIONS,
6011
6113
  AI_PURPOSES,
6012
6114
  AgendaConfiguration,
@@ -6043,7 +6145,10 @@ function safeJson(text) {
6043
6145
  CrmResource,
6044
6146
  Inbox,
6045
6147
  Journeys,
6148
+ PLAN_ERROR_CODES,
6046
6149
  Radar,
6047
- SavedReplies
6150
+ SavedReplies,
6151
+ WEBHOOK_CATEGORIES,
6152
+ isPlanError
6048
6153
  });
6049
6154
  //# sourceMappingURL=index.cjs.map