@adatechnology/meta-whatsapp-module 0.12.0 → 0.13.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.cts CHANGED
@@ -2561,6 +2561,23 @@ type FlowVariablesResolver = (params: {
2561
2561
  readonly session: ConversationSession;
2562
2562
  readonly profileName?: string;
2563
2563
  }) => Promise<Readonly<Record<string, unknown>>>;
2564
+ /**
2565
+ * Retentativa do envio de saída do robô (cada mensagem do turno, uma a uma). Só repete falha em que a
2566
+ * mensagem não chegou à Meta (ver `isTransientSendError`); vale a pena porque o turno já foi
2567
+ * reivindicado e o cliente, sem isto, ficaria sem resposta até escrever de novo.
2568
+ */
2569
+ type FlowSendRetryConfig = {
2570
+ /** Tentativas por mensagem, contando a primeira. Padrão 3; 1 desliga a retentativa. */
2571
+ readonly maxAttempts?: number;
2572
+ /** Espera antes da 2ª tentativa; dobra a cada falha. Padrão 500 ms. */
2573
+ readonly baseDelayMs?: number;
2574
+ /** Teto da espera. Padrão 5000 ms. */
2575
+ readonly maxDelayMs?: number;
2576
+ /** Decide se a falha vale outra tentativa. Padrão: falha de rede (`isTransientSendError`). */
2577
+ readonly shouldRetry?: (error: unknown) => boolean;
2578
+ /** Espera injetável para teste. */
2579
+ readonly sleep?: (milliseconds: number) => Promise<void>;
2580
+ };
2564
2581
  type FlowRunnerConfig = {
2565
2582
  /** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
2566
2583
  readonly startFlowKey?: string;
@@ -2602,6 +2619,8 @@ type FlowRunnerConfig = {
2602
2619
  readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
2603
2620
  /** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
2604
2621
  readonly maxCrossFlowJumps?: number;
2622
+ /** Retentativa do envio de saída. Ausente, valem os padrões de `FlowSendRetryConfig`. */
2623
+ readonly sendRetry?: FlowSendRetryConfig;
2605
2624
  /** Relógio injetável para teste. */
2606
2625
  readonly now?: () => Date;
2607
2626
  };
@@ -2728,6 +2747,7 @@ declare class FlowRunner {
2728
2747
  private readonly renderer;
2729
2748
  private readonly timeZone;
2730
2749
  private readonly turnVariables;
2750
+ private readonly sendFailures;
2731
2751
  constructor(dependencies: FlowRunnerDependencies);
2732
2752
  registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
2733
2753
  /**
@@ -2779,6 +2799,10 @@ declare class FlowRunner {
2779
2799
  /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2780
2800
  private awaitAnswer;
2781
2801
  private say;
2802
+ /**
2803
+ * Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
2804
+ * Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
2805
+ */
2782
2806
  private send;
2783
2807
  private save;
2784
2808
  private reportMissingFlow;
@@ -3696,6 +3720,24 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
3696
3720
  whatsappNumber: string;
3697
3721
  } | null>;
3698
3722
 
3723
+ /**
3724
+ * Copyright (c) 2026 Ada Technology. MIT License.
3725
+ *
3726
+ * Retentativa de UM envio de saída do robô, com limite e backoff exponencial.
3727
+ *
3728
+ * Cada mensagem do turno é retentada sozinha: se a segunda falha, a primeira (já entregue) não sai de
3729
+ * novo. Só se repete falha em que a Meta nunca recebeu a mensagem; o resto (recusa da Meta, erro de
3730
+ * banco depois do envio, janela expirada) sobe na primeira vez — repetir duplicaria ou falharia igual.
3731
+ */
3732
+
3733
+ /**
3734
+ * Padrão de `FlowSendRetryConfig.shouldRetry`: falha de rede antes de a requisição ser entregue.
3735
+ * Timeout fica de fora de propósito: a Meta pode ter aceitado a mensagem e a Cloud API não tem chave
3736
+ * de idempotência, então repetir arriscaria mandar duas vezes. O host que prefere repetir passa o
3737
+ * próprio `shouldRetry`.
3738
+ */
3739
+ declare function isTransientSendError(error: unknown): boolean;
3740
+
3699
3741
  /**
3700
3742
  * Copyright (c) 2026 Ada Technology. MIT License.
3701
3743
  *
@@ -3985,4 +4027,4 @@ type CreateMetaWhatsAppQuickReplyRoutesParams = {
3985
4027
  */
3986
4028
  declare function createMetaWhatsAppQuickReplyRoutes(params: CreateMetaWhatsAppQuickReplyRoutesParams): ModuleRouteTable;
3987
4029
 
3988
- export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateMetaWhatsAppQuickReplyRoutesParams, type CreateQuickReplyParams as CreateQuickReplyRowParams, CreateQuickReplyUseCase, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_QUICK_REPLY_WRITE_SCOPES, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, type DeleteQuickReplyParams, DeleteQuickReplyUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowAnswerValidator, type FlowAnswerValidatorResult, type FlowChoiceOption, type FlowConfigText, type FlowGlobalKeyword, type FlowGlobalKeywordMatch, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowStepInput, type FlowStepResult, type FlowTextContext, type FlowTextKind, type FlowTextResolver, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type ListQuickRepliesParams, ListQuickRepliesUseCase, type ListQuickRepliesParams$1 as ListQuickReplyRowsParams, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppDatabaseFor, type MetaWhatsAppDatabaseShape, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewQuickReplyRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, QUICK_REPLY_SCOPE, QuickReplyRepository, type QuickReplyRouteScopes, type QuickReplyRow, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ReseedFlowGraphParams, type ReseedFlowGraphResult, ReseedFlowGraphUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveQuickReplyParams, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, type UpdateQuickReplyParams, type UpdateQuickReplyParams$1 as UpdateQuickReplyRowParams, UpdateQuickReplyUseCase, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createMetaWhatsAppQuickReplyRoutes, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
4030
+ export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateMetaWhatsAppQuickReplyRoutesParams, type CreateQuickReplyParams as CreateQuickReplyRowParams, CreateQuickReplyUseCase, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_QUICK_REPLY_WRITE_SCOPES, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, type DeleteQuickReplyParams, DeleteQuickReplyUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowAnswerValidator, type FlowAnswerValidatorResult, type FlowChoiceOption, type FlowConfigText, type FlowGlobalKeyword, type FlowGlobalKeywordMatch, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowSendRetryConfig, type FlowStepInput, type FlowStepResult, type FlowTextContext, type FlowTextKind, type FlowTextResolver, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type ListQuickRepliesParams, ListQuickRepliesUseCase, type ListQuickRepliesParams$1 as ListQuickReplyRowsParams, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppDatabaseFor, type MetaWhatsAppDatabaseShape, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewQuickReplyRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, QUICK_REPLY_SCOPE, QuickReplyRepository, type QuickReplyRouteScopes, type QuickReplyRow, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ReseedFlowGraphParams, type ReseedFlowGraphResult, ReseedFlowGraphUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveQuickReplyParams, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, type UpdateQuickReplyParams, type UpdateQuickReplyParams$1 as UpdateQuickReplyRowParams, UpdateQuickReplyUseCase, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createMetaWhatsAppQuickReplyRoutes, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isTransientSendError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
package/dist/index.d.ts CHANGED
@@ -2561,6 +2561,23 @@ type FlowVariablesResolver = (params: {
2561
2561
  readonly session: ConversationSession;
2562
2562
  readonly profileName?: string;
2563
2563
  }) => Promise<Readonly<Record<string, unknown>>>;
2564
+ /**
2565
+ * Retentativa do envio de saída do robô (cada mensagem do turno, uma a uma). Só repete falha em que a
2566
+ * mensagem não chegou à Meta (ver `isTransientSendError`); vale a pena porque o turno já foi
2567
+ * reivindicado e o cliente, sem isto, ficaria sem resposta até escrever de novo.
2568
+ */
2569
+ type FlowSendRetryConfig = {
2570
+ /** Tentativas por mensagem, contando a primeira. Padrão 3; 1 desliga a retentativa. */
2571
+ readonly maxAttempts?: number;
2572
+ /** Espera antes da 2ª tentativa; dobra a cada falha. Padrão 500 ms. */
2573
+ readonly baseDelayMs?: number;
2574
+ /** Teto da espera. Padrão 5000 ms. */
2575
+ readonly maxDelayMs?: number;
2576
+ /** Decide se a falha vale outra tentativa. Padrão: falha de rede (`isTransientSendError`). */
2577
+ readonly shouldRetry?: (error: unknown) => boolean;
2578
+ /** Espera injetável para teste. */
2579
+ readonly sleep?: (milliseconds: number) => Promise<void>;
2580
+ };
2564
2581
  type FlowRunnerConfig = {
2565
2582
  /** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
2566
2583
  readonly startFlowKey?: string;
@@ -2602,6 +2619,8 @@ type FlowRunnerConfig = {
2602
2619
  readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
2603
2620
  /** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
2604
2621
  readonly maxCrossFlowJumps?: number;
2622
+ /** Retentativa do envio de saída. Ausente, valem os padrões de `FlowSendRetryConfig`. */
2623
+ readonly sendRetry?: FlowSendRetryConfig;
2605
2624
  /** Relógio injetável para teste. */
2606
2625
  readonly now?: () => Date;
2607
2626
  };
@@ -2728,6 +2747,7 @@ declare class FlowRunner {
2728
2747
  private readonly renderer;
2729
2748
  private readonly timeZone;
2730
2749
  private readonly turnVariables;
2750
+ private readonly sendFailures;
2731
2751
  constructor(dependencies: FlowRunnerDependencies);
2732
2752
  registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
2733
2753
  /**
@@ -2779,6 +2799,10 @@ declare class FlowRunner {
2779
2799
  /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2780
2800
  private awaitAnswer;
2781
2801
  private say;
2802
+ /**
2803
+ * Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
2804
+ * Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
2805
+ */
2782
2806
  private send;
2783
2807
  private save;
2784
2808
  private reportMissingFlow;
@@ -3696,6 +3720,24 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
3696
3720
  whatsappNumber: string;
3697
3721
  } | null>;
3698
3722
 
3723
+ /**
3724
+ * Copyright (c) 2026 Ada Technology. MIT License.
3725
+ *
3726
+ * Retentativa de UM envio de saída do robô, com limite e backoff exponencial.
3727
+ *
3728
+ * Cada mensagem do turno é retentada sozinha: se a segunda falha, a primeira (já entregue) não sai de
3729
+ * novo. Só se repete falha em que a Meta nunca recebeu a mensagem; o resto (recusa da Meta, erro de
3730
+ * banco depois do envio, janela expirada) sobe na primeira vez — repetir duplicaria ou falharia igual.
3731
+ */
3732
+
3733
+ /**
3734
+ * Padrão de `FlowSendRetryConfig.shouldRetry`: falha de rede antes de a requisição ser entregue.
3735
+ * Timeout fica de fora de propósito: a Meta pode ter aceitado a mensagem e a Cloud API não tem chave
3736
+ * de idempotência, então repetir arriscaria mandar duas vezes. O host que prefere repetir passa o
3737
+ * próprio `shouldRetry`.
3738
+ */
3739
+ declare function isTransientSendError(error: unknown): boolean;
3740
+
3699
3741
  /**
3700
3742
  * Copyright (c) 2026 Ada Technology. MIT License.
3701
3743
  *
@@ -3985,4 +4027,4 @@ type CreateMetaWhatsAppQuickReplyRoutesParams = {
3985
4027
  */
3986
4028
  declare function createMetaWhatsAppQuickReplyRoutes(params: CreateMetaWhatsAppQuickReplyRoutesParams): ModuleRouteTable;
3987
4029
 
3988
- export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateMetaWhatsAppQuickReplyRoutesParams, type CreateQuickReplyParams as CreateQuickReplyRowParams, CreateQuickReplyUseCase, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_QUICK_REPLY_WRITE_SCOPES, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, type DeleteQuickReplyParams, DeleteQuickReplyUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowAnswerValidator, type FlowAnswerValidatorResult, type FlowChoiceOption, type FlowConfigText, type FlowGlobalKeyword, type FlowGlobalKeywordMatch, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowStepInput, type FlowStepResult, type FlowTextContext, type FlowTextKind, type FlowTextResolver, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type ListQuickRepliesParams, ListQuickRepliesUseCase, type ListQuickRepliesParams$1 as ListQuickReplyRowsParams, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppDatabaseFor, type MetaWhatsAppDatabaseShape, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewQuickReplyRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, QUICK_REPLY_SCOPE, QuickReplyRepository, type QuickReplyRouteScopes, type QuickReplyRow, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ReseedFlowGraphParams, type ReseedFlowGraphResult, ReseedFlowGraphUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveQuickReplyParams, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, type UpdateQuickReplyParams, type UpdateQuickReplyParams$1 as UpdateQuickReplyRowParams, UpdateQuickReplyUseCase, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createMetaWhatsAppQuickReplyRoutes, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
4030
+ export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateMetaWhatsAppQuickReplyRoutesParams, type CreateQuickReplyParams as CreateQuickReplyRowParams, CreateQuickReplyUseCase, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_QUICK_REPLY_WRITE_SCOPES, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, type DeleteQuickReplyParams, DeleteQuickReplyUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowAnswerValidator, type FlowAnswerValidatorResult, type FlowChoiceOption, type FlowConfigText, type FlowGlobalKeyword, type FlowGlobalKeywordMatch, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowSendRetryConfig, type FlowStepInput, type FlowStepResult, type FlowTextContext, type FlowTextKind, type FlowTextResolver, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type ListQuickRepliesParams, ListQuickRepliesUseCase, type ListQuickRepliesParams$1 as ListQuickReplyRowsParams, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppDatabaseFor, type MetaWhatsAppDatabaseShape, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewQuickReplyRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, QUICK_REPLY_SCOPE, QuickReplyRepository, type QuickReplyRouteScopes, type QuickReplyRow, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ReseedFlowGraphParams, type ReseedFlowGraphResult, ReseedFlowGraphUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveQuickReplyParams, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, type UpdateQuickReplyParams, type UpdateQuickReplyParams$1 as UpdateQuickReplyRowParams, UpdateQuickReplyUseCase, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createMetaWhatsAppQuickReplyRoutes, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isTransientSendError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
package/dist/index.js CHANGED
@@ -2337,6 +2337,9 @@ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@ada
2337
2337
  var DEFAULT_START_FLOW_KEY = "main";
2338
2338
  var DEFAULT_MAX_INVALID_ANSWERS = 2;
2339
2339
  var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2340
+ var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
2341
+ var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
2342
+ var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
2340
2343
  var DEFAULT_FLOW_TEXT = {
2341
2344
  FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2342
2345
  CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
@@ -2717,6 +2720,47 @@ async function resolveFlowConfigText(params) {
2717
2720
  }
2718
2721
  __name(resolveFlowConfigText, "resolveFlowConfigText");
2719
2722
 
2723
+ // src/flows/sendWithRetry.ts
2724
+ import { WhatsAppConnectionError } from "@adatechnology/meta-graph-core";
2725
+ function isTransientSendError(error) {
2726
+ return error instanceof WhatsAppConnectionError;
2727
+ }
2728
+ __name(isTransientSendError, "isTransientSendError");
2729
+ var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
2730
+ var SendRetriesExhausted = class {
2731
+ static {
2732
+ __name(this, "SendRetriesExhausted");
2733
+ }
2734
+ error;
2735
+ attempts;
2736
+ isTransient;
2737
+ constructor(error, attempts, isTransient) {
2738
+ this.error = error;
2739
+ this.attempts = attempts;
2740
+ this.isTransient = isTransient;
2741
+ }
2742
+ };
2743
+ async function sendWithRetry(send, config = {}) {
2744
+ const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
2745
+ const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
2746
+ const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
2747
+ const shouldRetry = config.shouldRetry ?? isTransientSendError;
2748
+ const sleep = config.sleep ?? sleepFor;
2749
+ for (let attempt = 1; ; attempt++) {
2750
+ try {
2751
+ await send();
2752
+ return {
2753
+ attempts: attempt
2754
+ };
2755
+ } catch (error) {
2756
+ const isTransient = shouldRetry(error);
2757
+ if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
2758
+ await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
2759
+ }
2760
+ }
2761
+ }
2762
+ __name(sendWithRetry, "sendWithRetry");
2763
+
2720
2764
  // src/flows/FlowRunner.ts
2721
2765
  function contactVariables(profileName) {
2722
2766
  if (!profileName) return {};
@@ -2746,6 +2790,8 @@ var FlowRunner = class {
2746
2790
  // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2747
2791
  // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2748
2792
  turnVariables = /* @__PURE__ */ new WeakMap();
2793
+ // Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
2794
+ sendFailures = /* @__PURE__ */ new WeakMap();
2749
2795
  constructor(dependencies) {
2750
2796
  this.dependencies = dependencies;
2751
2797
  this.renderer = new FlowQuestionRenderer(dependencies.config);
@@ -3240,6 +3286,10 @@ var FlowRunner = class {
3240
3286
  body
3241
3287
  });
3242
3288
  }
3289
+ /**
3290
+ * Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
3291
+ * Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
3292
+ */
3243
3293
  async send(turn, message) {
3244
3294
  const common = {
3245
3295
  companyId: turn.companyId,
@@ -3247,14 +3297,29 @@ var FlowRunner = class {
3247
3297
  sender: "bot",
3248
3298
  startState: this.dependencies.startState
3249
3299
  };
3250
- if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3251
- ...common,
3252
- body: message.body
3253
- });
3254
- else await this.dependencies.sendMessage.sendInteractive({
3255
- ...common,
3256
- interactive: message.interactive
3257
- });
3300
+ const deliver = /* @__PURE__ */ __name(async () => {
3301
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3302
+ ...common,
3303
+ body: message.body
3304
+ });
3305
+ else await this.dependencies.sendMessage.sendInteractive({
3306
+ ...common,
3307
+ interactive: message.interactive
3308
+ });
3309
+ }, "deliver");
3310
+ try {
3311
+ await sendWithRetry(deliver, this.dependencies.config.sendRetry);
3312
+ } catch (failure) {
3313
+ if (!(failure instanceof SendRetriesExhausted)) throw failure;
3314
+ if (typeof failure.error === "object" && failure.error !== null) {
3315
+ this.sendFailures.set(failure.error, {
3316
+ attempts: failure.attempts,
3317
+ messageKind: message.kind,
3318
+ isTransient: failure.isTransient
3319
+ });
3320
+ }
3321
+ throw failure.error;
3322
+ }
3258
3323
  }
3259
3324
  save(turn, progress) {
3260
3325
  const runtime = runtimeOf(progress.context);
@@ -3282,12 +3347,16 @@ var FlowRunner = class {
3282
3347
  * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
3283
3348
  */
3284
3349
  async report(turn, flowKey, nodeId, stage, error) {
3350
+ const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
3285
3351
  const details = {
3286
3352
  companyId: turn.companyId,
3287
3353
  whatsappNumber: turn.session.whatsappNumber,
3288
3354
  flowKey,
3289
3355
  nodeId,
3290
- stage
3356
+ stage,
3357
+ ...send ? {
3358
+ send
3359
+ } : {}
3291
3360
  };
3292
3361
  try {
3293
3362
  await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
@@ -5109,6 +5178,7 @@ export {
5109
5178
  isAudioMimeType,
5110
5179
  isChoiceNode,
5111
5180
  isRetriableTranscriptionError,
5181
+ isTransientSendError,
5112
5182
  isUnsupportedTranscriptionError,
5113
5183
  issueSseTicket,
5114
5184
  messages,