@adatechnology/meta-whatsapp-module 0.8.1 → 0.10.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,7 +1,8 @@
1
+ import { PreviewInboundCommand, PreviewPayloadEnvelope } from '@adatechnology/meta-whatsapp-contracts/testing';
1
2
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
2
3
  import { PgAsyncDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
3
4
  import * as _adatechnology_meta_whatsapp_contracts from '@adatechnology/meta-whatsapp-contracts';
4
- import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, FlowActionKind, FlowActionHandler, ConversationSession, WhatsAppMessage, WhatsAppStatus, MetaWhatsAppHooks, SubjectResolverInterface, CatalogPort, SendChannelMediaParams } from '@adatechnology/meta-whatsapp-contracts';
5
+ import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, InteractiveMessage, MetaWhatsAppHooks, FlowActionKind, FlowActionHandler, ConversationSession, FlowNodeData, FlowAnswerRejection, FlowDateLocale, BusinessHours, InterpolateFlowTextOptions, DynamicChoiceProvider, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams, FlowClock } from '@adatechnology/meta-whatsapp-contracts';
5
6
  export { PREVIEW_MEDIA_ID_PREFIX, TranscriptionMode, resolvePreviewUploadId, toPreviewMediaId } from '@adatechnology/meta-whatsapp-contracts';
6
7
  import { WhatsAppMessageProvider } from '@adatechnology/meta-whatsapp-provider';
7
8
  export { WEBHOOK_CLAIM_TTL_SECONDS, WEBHOOK_NONCE_TTL_SECONDS } from '@adatechnology/meta-graph-core';
@@ -1389,6 +1390,17 @@ declare class SessionRepository {
1389
1390
  patchContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string, patch: Partial<TSessionContext>): Promise<void>;
1390
1391
  readContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string): Promise<TSessionContext | undefined>;
1391
1392
  setFlowPosition(companyId: string, whatsappNumber: string, flowKey: string | null, currentNodeId: string | null): Promise<void>;
1393
+ /**
1394
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
1395
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
1396
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
1397
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
1398
+ */
1399
+ saveFlowProgress(companyId: string, whatsappNumber: string, progress: {
1400
+ flowKey: string | null;
1401
+ currentNodeId: string | null;
1402
+ context: Record<string, unknown>;
1403
+ }): Promise<void>;
1392
1404
  touchInbound(companyId: string, whatsappNumber: string): Promise<void>;
1393
1405
  hoursSinceLastInbound(companyId: string, whatsappNumber: string): Promise<number | undefined>;
1394
1406
  setMode(companyId: string, whatsappNumber: string, mode: SessionMode, assignedUserId?: string | null, clearHumanRequest?: boolean): Promise<void>;
@@ -1746,6 +1758,8 @@ declare class DocumentRepository {
1746
1758
  deleteById(companyId: string, id: string): Promise<void>;
1747
1759
  }
1748
1760
 
1761
+ /** Rótulo da lista quando o canal não sabe enviar botão e os botões viram lista. */
1762
+ declare const DEFAULT_FALLBACK_LIST_LABEL = "Op\u00E7\u00F5es";
1749
1763
  type SendTextParams = {
1750
1764
  companyId: string;
1751
1765
  whatsappNumber: string;
@@ -1775,6 +1789,20 @@ type SendTemplateParams = {
1775
1789
  agentUserId?: string;
1776
1790
  startState: SessionState;
1777
1791
  };
1792
+ type SendInteractiveParams = {
1793
+ companyId: string;
1794
+ whatsappNumber: string;
1795
+ /** Botões (até 3) ou lista (até 10 linhas em até 10 seções). Validado contra `WHATSAPP_CHOICE_LIMIT`. */
1796
+ interactive: InteractiveMessage;
1797
+ sender: 'bot' | 'agent';
1798
+ agentUserId?: string;
1799
+ startState: SessionState;
1800
+ /**
1801
+ * Rótulo da lista quando `interactive.kind === 'buttons'` e o canal não implementa
1802
+ * `sendInteractiveButtons` — os botões saem como lista. Padrão `DEFAULT_FALLBACK_LIST_LABEL`.
1803
+ */
1804
+ fallbackListLabel?: string;
1805
+ };
1778
1806
  declare class SendMessageUseCase {
1779
1807
  private readonly channel;
1780
1808
  private readonly sessionRepository;
@@ -1785,6 +1813,16 @@ declare class SendMessageUseCase {
1785
1813
  private assertWithinWindow;
1786
1814
  sendText(params: SendTextParams): Promise<MessageRow | undefined>;
1787
1815
  sendMedia(params: SendMediaParams): Promise<MessageRow | undefined>;
1816
+ /**
1817
+ * Botões ou lista, pelo mesmo caminho do `sendText`: janela, envio, transcript (idempotente pelo
1818
+ * `waMessageId`). Os limites da Meta são conferidos ANTES de tudo — mensagem fora do teto a Graph
1819
+ * API recusa inteira, e o erro local (`InteractiveLimitExceededError`) diz qual campo corrigir.
1820
+ *
1821
+ * O transcript guarda `type: 'interactive'`, o corpo em `content` e a mensagem inteira (ids e
1822
+ * títulos das opções) em `payload.interactive`, para o histórico mostrar o que foi oferecido.
1823
+ */
1824
+ sendInteractive(params: SendInteractiveParams): Promise<MessageRow | undefined>;
1825
+ private sendInteractiveThroughChannel;
1788
1826
  sendTemplate(params: SendTemplateParams): Promise<MessageRow | undefined>;
1789
1827
  }
1790
1828
 
@@ -1792,25 +1830,53 @@ type TakeoverConversationParams = {
1792
1830
  companyId: string;
1793
1831
  whatsappNumber: string;
1794
1832
  agentUserId: string;
1833
+ /**
1834
+ * Quem executou a ação, quando não é o próprio atendente (ex.: supervisor atribuindo a conversa a
1835
+ * outra pessoa). Omitido, o ator é `agentUserId`.
1836
+ */
1837
+ actorId?: string;
1795
1838
  };
1796
1839
  declare class TakeoverConversationUseCase {
1797
1840
  private readonly sessionRepository;
1798
1841
  private readonly realtime?;
1799
- constructor(sessionRepository: SessionRepository, realtime?: RealtimeNotifierInterface | undefined);
1842
+ private readonly hooks?;
1843
+ constructor(sessionRepository: SessionRepository, realtime?: RealtimeNotifierInterface | undefined, hooks?: Pick<MetaWhatsAppHooks, "onConversationModeChanged"> | undefined);
1800
1844
  execute(params: TakeoverConversationParams): Promise<void>;
1801
1845
  }
1802
1846
 
1803
1847
  type ReleaseConversationParams = {
1804
1848
  companyId: string;
1805
1849
  whatsappNumber: string;
1850
+ /** Quem devolveu a conversa ao bot. Omitido, `null` — o próprio sistema (ex.: job de inatividade). */
1851
+ actorId?: string | null;
1806
1852
  };
1807
1853
  declare class ReleaseConversationUseCase {
1808
1854
  private readonly sessionRepository;
1809
1855
  private readonly realtime?;
1810
- constructor(sessionRepository: SessionRepository, realtime?: RealtimeNotifierInterface | undefined);
1856
+ private readonly hooks?;
1857
+ constructor(sessionRepository: SessionRepository, realtime?: RealtimeNotifierInterface | undefined, hooks?: Pick<MetaWhatsAppHooks, "onConversationModeChanged"> | undefined);
1811
1858
  execute(params: ReleaseConversationParams): Promise<void>;
1812
1859
  }
1813
1860
 
1861
+ type RequestHumanConversationParams = {
1862
+ companyId: string;
1863
+ whatsappNumber: string;
1864
+ /** Quem pediu. Omitido, `null` — o cliente pelo menu ou o bot decidindo encaminhar. */
1865
+ actorId?: string | null;
1866
+ };
1867
+ /**
1868
+ * Coloca a conversa na fila "aguardando atendimento" (`humanRequestedAt`) sem tirá-la do bot: quem
1869
+ * assume é o `takeover`. Dispara `onHumanRequested` (o host decide como avisar a equipe) e
1870
+ * `onConversationModeChanged` com `kind: 'human-requested'` (trilha de auditoria).
1871
+ */
1872
+ declare class RequestHumanConversationUseCase {
1873
+ private readonly sessionRepository;
1874
+ private readonly realtime?;
1875
+ private readonly hooks?;
1876
+ constructor(sessionRepository: SessionRepository, realtime?: RealtimeNotifierInterface | undefined, hooks?: Pick<MetaWhatsAppHooks, "onHumanRequested" | "onConversationModeChanged"> | undefined);
1877
+ execute(params: RequestHumanConversationParams): Promise<void>;
1878
+ }
1879
+
1814
1880
  type ListConversationsParams = {
1815
1881
  companyId: string;
1816
1882
  filters?: ListConversationsFilters;
@@ -2083,6 +2149,11 @@ interface FlowStepInput {
2083
2149
  graph: FlowGraphData;
2084
2150
  currentNodeId: string;
2085
2151
  userAnswer?: string;
2152
+ /**
2153
+ * Valor a guardar em `contextKey` no lugar do texto cru — a data já convertida, o número já lido.
2154
+ * `userAnswer` continua sendo o que escolhe o ramo (`byAnswer`).
2155
+ */
2156
+ answerValue?: unknown;
2086
2157
  context: Record<string, unknown>;
2087
2158
  session: ConversationSession;
2088
2159
  channel: ChannelAdapterInterface;
@@ -2121,14 +2192,265 @@ type FlowRunResult = ({
2121
2192
  visited: string[];
2122
2193
  steps: number;
2123
2194
  };
2195
+ type FlowRunOptions = {
2196
+ maxSteps?: number;
2197
+ /**
2198
+ * Chamado ao entrar em cada nó, com o contexto daquele momento — é onde o runner envia o
2199
+ * `directMessage`. Uma ação que devolve contexto já está refletida no nó seguinte.
2200
+ */
2201
+ onNodeEntered?: (node: FlowNodeData, context: Record<string, unknown>) => Promise<void>;
2202
+ /** Também dispara `onNodeEntered` para o nó de partida (início de fluxo, salto por palavra-chave). */
2203
+ enterInitialNode?: boolean;
2204
+ };
2124
2205
  declare class FlowInterpreter {
2125
2206
  private readonly actionHandlers;
2126
2207
  registerFlowAction(kind: FlowActionKind, handler: FlowActionHandler): void;
2127
2208
  step(input: FlowStepInput): Promise<FlowStepResult>;
2128
2209
  private moveTo;
2129
- run(input: FlowStepInput, options?: {
2130
- maxSteps?: number;
2131
- }): Promise<FlowRunResult>;
2210
+ run(input: FlowStepInput, options?: FlowRunOptions): Promise<FlowRunResult>;
2211
+ }
2212
+
2213
+ /**
2214
+ * Copyright (c) 2026 Ada Technology. MIT License.
2215
+ *
2216
+ * Configuração do runner de fluxo. Tudo opcional: sem nada, o runner atende pelo fluxo `main`, com
2217
+ * os textos padrão em pt-BR e encaminhamento a uma pessoa depois de 2 respostas inválidas.
2218
+ */
2219
+
2220
+ /** `restart` volta ao início do fluxo de partida; `handoff` chama uma pessoa; `flow:<chave>` abre outro fluxo. */
2221
+ type FlowGlobalKeywordTarget = 'restart' | 'handoff' | `flow:${string}`;
2222
+ /** Palavras que valem em qualquer nó ("menu", "atendente"), comparadas sem acento e sem caixa. */
2223
+ type FlowGlobalKeyword = {
2224
+ readonly keywords: readonly string[];
2225
+ readonly target: FlowGlobalKeywordTarget;
2226
+ };
2227
+ type FlowHandoffConfig = {
2228
+ /** Mensagem dentro do horário (ou sempre, sem `businessHours`). Aceita `{{chave}}`. */
2229
+ readonly message?: string;
2230
+ /** Mensagem fora do horário. Ausente, vale `message`. */
2231
+ readonly outOfHoursMessage?: string;
2232
+ /** Fixo, ou resolvido por empresa a cada encaminhamento (o painel pode mudar sem deploy). */
2233
+ readonly businessHours?: BusinessHours | ((companyId: string) => Promise<BusinessHours | undefined>);
2234
+ };
2235
+ type FlowVariablesResolver = (params: {
2236
+ readonly session: ConversationSession;
2237
+ readonly profileName?: string;
2238
+ }) => Promise<Readonly<Record<string, unknown>>>;
2239
+ type FlowRunnerConfig = {
2240
+ /** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
2241
+ readonly startFlowKey?: string;
2242
+ readonly globalKeywords?: readonly FlowGlobalKeyword[];
2243
+ /** Respostas inválidas seguidas no mesmo nó antes de chamar uma pessoa. Padrão 2; o nó pode sobrescrever. */
2244
+ readonly maxInvalidAnswers?: number;
2245
+ /** Texto de nova tentativa quando o nó não declara `fallbackMessage`. */
2246
+ readonly defaultFallbackMessage?: string;
2247
+ /** Texto de nova tentativa por motivo, antes do padrão ("essa data já passou"). */
2248
+ readonly rejectionMessages?: Partial<Record<FlowAnswerRejection, string>>;
2249
+ /** Corpo de escolha quando o nó não tem `question` (a Meta exige corpo). */
2250
+ readonly choicePrompt?: string;
2251
+ readonly listButtonLabel?: string;
2252
+ /** Rótulo da linha que pede a próxima página de um `dynamic_choice`. */
2253
+ readonly seeMoreLabel?: string;
2254
+ readonly dateLocale?: FlowDateLocale;
2255
+ /**
2256
+ * Fuso de "hoje" na validação de data (IANA). Obrigatório — ou derivado de
2257
+ * `handoff.businessHours.timeZone` quando o horário é fixo: servidor em UTC aceitaria "hoje" errado
2258
+ * entre 21h e meia-noite no Brasil.
2259
+ */
2260
+ readonly timeZone?: string;
2261
+ /** Resposta que não casa com opção: `reask` (padrão) ou `default` (segue `next.default`). O nó sobrescreve. */
2262
+ readonly unmatchedChoice?: 'reask' | 'default';
2263
+ /** Resposta em áudio, imagem, localização… num nó que espera texto: avisa e repergunta, sem contar tentativa. */
2264
+ readonly nonTextAnswerMessage?: string;
2265
+ readonly handoff?: FlowHandoffConfig;
2266
+ /**
2267
+ * Conversa que pediu atendimento e saiu do fluxo: `silent` (padrão) não responde até alguém
2268
+ * assumir ou devolver ao bot — palavras globais continuam valendo; `continue` reabre o fluxo.
2269
+ */
2270
+ readonly whileAwaitingHuman?: 'silent' | 'continue';
2271
+ /** Variáveis do host para `{{chave}}` (dados do cadastro, por exemplo). O contexto do fluxo tem precedência. */
2272
+ readonly resolveVariables?: FlowVariablesResolver;
2273
+ readonly formatValue?: InterpolateFlowTextOptions['formatValue'];
2274
+ readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
2275
+ /** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
2276
+ readonly maxCrossFlowJumps?: number;
2277
+ /** Relógio injetável para teste. */
2278
+ readonly now?: () => Date;
2279
+ };
2280
+ type FlowRunnerOutcome = 'handled' | 'duplicate' | 'no-session' | 'human-mode' | 'awaiting-human' | 'no-flow';
2281
+
2282
+ /**
2283
+ * Copyright (c) 2026 Ada Technology. MIT License.
2284
+ *
2285
+ * Encaminhamento a uma pessoa: põe a conversa na fila (`requestHuman`, que dispara
2286
+ * `onHumanRequested` e `onConversationModeChanged`) e avisa o cliente com o texto certo para a hora.
2287
+ *
2288
+ * Um só caminho para os três gatilhos — o nó `handoff`, a palavra global e o excesso de respostas
2289
+ * inválidas. Três cópias divergiriam no texto e no horário.
2290
+ */
2291
+
2292
+ type FlowHandoffDependencies = {
2293
+ readonly requestHuman: RequestHumanConversationUseCase;
2294
+ readonly sendMessage: SendMessageUseCase;
2295
+ readonly startState: SessionState;
2296
+ readonly config: FlowHandoffConfig;
2297
+ readonly now: () => Date;
2298
+ readonly interpolation: InterpolateFlowTextOptions;
2299
+ readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
2300
+ };
2301
+ type RequestFlowHandoffParams = {
2302
+ readonly companyId: string;
2303
+ readonly whatsappNumber: string;
2304
+ readonly variables: Readonly<Record<string, unknown>>;
2305
+ readonly node?: FlowNodeData;
2306
+ };
2307
+ declare class FlowHandoff {
2308
+ private readonly dependencies;
2309
+ constructor(dependencies: FlowHandoffDependencies);
2310
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
2311
+ request(params: RequestFlowHandoffParams): Promise<boolean>;
2312
+ /**
2313
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
2314
+ * sobrescrevem os textos do runner para aquele nó.
2315
+ */
2316
+ createActionHandler(resolveVariables: (params: {
2317
+ session: ConversationSession;
2318
+ context: Record<string, unknown>;
2319
+ }) => Record<string, unknown>): FlowActionHandler;
2320
+ private reportFailure;
2321
+ private isWithinHours;
2322
+ private messageFor;
2323
+ }
2324
+
2325
+ /**
2326
+ * Copyright (c) 2026 Ada Technology. MIT License.
2327
+ *
2328
+ * Um turno do runner por conversa de cada vez. Duas mensagens do mesmo cliente processadas em
2329
+ * paralelo leriam a mesma posição, responderiam ao mesmo nó e a última gravação apagaria a outra.
2330
+ *
2331
+ * Porta, com implementação padrão no Postgres do próprio módulo; o host troca por outra (Redis,
2332
+ * fila particionada por conversa) quando quiser.
2333
+ */
2334
+
2335
+ type FlowTurnLockKey = {
2336
+ readonly companyId: string;
2337
+ readonly whatsappNumber: string;
2338
+ };
2339
+ interface FlowTurnLockInterface {
2340
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2341
+ }
2342
+ /**
2343
+ * `pg_advisory_xact_lock` numa transação que dura o turno. A transação não toca linha nenhuma —
2344
+ * só segura o lock (e uma conexão do pool) enquanto o turno roda; as escritas do turno usam a
2345
+ * conexão normal. O lock sai sozinho no fim da transação, inclusive se o processo morrer.
2346
+ *
2347
+ * Custo: uma conexão por conversa em atendimento simultâneo. Com muitas conversas ao mesmo tempo,
2348
+ * dimensione o pool ou injete outra implementação.
2349
+ */
2350
+ declare class PostgresAdvisoryFlowTurnLock implements FlowTurnLockInterface {
2351
+ private readonly db;
2352
+ constructor(db: MetaWhatsAppDatabase);
2353
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2354
+ }
2355
+ /** Lock dentro do processo: serve para uma instância só e para testes. Não protege entre réplicas. */
2356
+ declare class InProcessFlowTurnLock implements FlowTurnLockInterface {
2357
+ private readonly tails;
2358
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2359
+ }
2360
+
2361
+ /**
2362
+ * Copyright (c) 2026 Ada Technology. MIT License.
2363
+ *
2364
+ * Runner de fluxo: o que faltava entre o `FlowInterpreter` (máquina de estados pura) e o cliente.
2365
+ * Carrega o grafo publicado, entende a resposta, avança o interpretador, grava posição e contexto e
2366
+ * fala com o cliente — pergunta, botões/lista, `directMessage`, nova tentativa e encaminhamento.
2367
+ *
2368
+ * Antes dele, cada host escrevia o próprio driver (centenas de linhas) e o motor de fluxo do pacote
2369
+ * não fazia nada sozinho depois do `onMessageReceived`.
2370
+ */
2371
+
2372
+ type FlowRunnerDependencies = {
2373
+ readonly interpreter: FlowInterpreter;
2374
+ readonly flowGraphRepository: Pick<FlowGraphRepository, 'get'>;
2375
+ readonly sessionRepository: SessionRepository;
2376
+ readonly sendMessage: SendMessageUseCase;
2377
+ readonly channel: ChannelAdapterInterface;
2378
+ readonly handoff: FlowHandoff;
2379
+ readonly lock: FlowTurnLockInterface;
2380
+ readonly startState: SessionState;
2381
+ readonly config: FlowRunnerConfig;
2382
+ readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
2383
+ };
2384
+ type HandleFlowMessageParams = {
2385
+ readonly companyId: string;
2386
+ readonly message: WhatsAppMessage;
2387
+ readonly profileName?: string;
2388
+ };
2389
+ type StartFlowParams = {
2390
+ readonly companyId: string;
2391
+ readonly whatsappNumber: string;
2392
+ /** Ausente, o fluxo de partida. */
2393
+ readonly flowKey?: string;
2394
+ readonly profileName?: string;
2395
+ };
2396
+ /** Fuso do runner: o configurado, ou o do horário de atendimento fixo. Sem nenhum, falha no boot. */
2397
+ declare function resolveFlowTimeZone(config: FlowRunnerConfig): string;
2398
+ declare class FlowRunner {
2399
+ private readonly dependencies;
2400
+ private readonly renderer;
2401
+ private readonly timeZone;
2402
+ private readonly turnVariables;
2403
+ constructor(dependencies: FlowRunnerDependencies);
2404
+ registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
2405
+ /**
2406
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2407
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2408
+ * o sistema conhece pelo que o cliente digitou.
2409
+ */
2410
+ variablesFor(params: {
2411
+ session: ConversationSession;
2412
+ context: Record<string, unknown>;
2413
+ }): Record<string, unknown>;
2414
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2415
+ handle(params: HandleFlowMessageParams): Promise<FlowRunnerOutcome>;
2416
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2417
+ start(params: StartFlowParams): Promise<FlowRunnerOutcome>;
2418
+ private handleLocked;
2419
+ private route;
2420
+ private guard;
2421
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2422
+ private claim;
2423
+ private openTurn;
2424
+ private startFlowKey;
2425
+ private clock;
2426
+ private loadGraph;
2427
+ private globalKeywordTarget;
2428
+ private keywordJumpAtStart;
2429
+ /**
2430
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2431
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2432
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2433
+ */
2434
+ private applyGlobalTarget;
2435
+ private answerNode;
2436
+ private followsDefaultWhenUnmatched;
2437
+ private handleInvalid;
2438
+ private fallbackText;
2439
+ private handOff;
2440
+ private jumpTo;
2441
+ private runFrom;
2442
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2443
+ private awaitAnswer;
2444
+ private say;
2445
+ private send;
2446
+ private save;
2447
+ private reportMissingFlow;
2448
+ /**
2449
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
2450
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
2451
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
2452
+ */
2453
+ private report;
2132
2454
  }
2133
2455
 
2134
2456
  type FlowMediaLocation = {
@@ -2302,6 +2624,8 @@ declare class InboundEffectsDispatcher {
2302
2624
  sessionRepository: SessionRepository;
2303
2625
  hooks?: MetaWhatsAppHooks;
2304
2626
  realtime?: RealtimeNotifierInterface;
2627
+ /** Presente quando `features.flowRunner` está ligado: o módulo dirige o fluxo depois do hook. */
2628
+ flowRunner?: Pick<FlowRunner, 'handle'>;
2305
2629
  });
2306
2630
  run(job: InboundDispatchJob): Promise<void>;
2307
2631
  runMessageEffects(job: InboundMessageEffectsJob): Promise<void>;
@@ -2315,7 +2639,8 @@ declare class InboundEffectsDispatcher {
2315
2639
  */
2316
2640
  declare class ProcessInboundDispatchUseCase {
2317
2641
  private readonly dispatcher;
2318
- constructor(dispatcher: InboundEffectsDispatcher);
2642
+ private readonly hooks?;
2643
+ constructor(dispatcher: InboundEffectsDispatcher, hooks?: Pick<MetaWhatsAppHooks, "onInboundEffectRejected"> | undefined);
2319
2644
  execute(job: InboundDispatchJob): Promise<void>;
2320
2645
  }
2321
2646
 
@@ -2351,6 +2676,8 @@ declare class ReceiveWebhookUseCase {
2351
2676
  inboundQueue?: InboundDispatchQueueInterface;
2352
2677
  /** Não grava `location` no transcript; ver `MetaWhatsAppModuleFeatures.redactInboundLocation`. */
2353
2678
  redactInboundLocation?: boolean;
2679
+ /** Runner de fluxo (`features.flowRunner`); ausente, o host dirige a conversa. */
2680
+ flowRunner?: Pick<FlowRunner, 'handle'>;
2354
2681
  });
2355
2682
  private readonly dispatcher;
2356
2683
  execute(input: ReceiveWebhookParams): Promise<ReceiveWebhookResult>;
@@ -2607,6 +2934,24 @@ interface MetaWhatsAppModuleFeatures {
2607
2934
  * fila do host. Linhas já gravadas se redigem com `conversations.redactInboundLocations`.
2608
2935
  */
2609
2936
  redactInboundLocation?: boolean;
2937
+ /**
2938
+ * O módulo dirige a conversa pelo grafo publicado depois do `onMessageReceived` devolver
2939
+ * `'continue'`: pergunta, valida, avança, grava e encaminha. `true` usa os padrões; o objeto
2940
+ * configura (fluxo de partida, palavras globais, horário de atendimento, textos — ver
2941
+ * `FlowRunnerConfig`).
2942
+ *
2943
+ * **Desligado por omissão**: host que já dirige o próprio fluxo depois do `'continue'` passaria a
2944
+ * receber duas respostas. Exige `flowEngine` (padrão ligado).
2945
+ */
2946
+ flowRunner?: boolean | FlowRunnerConfig;
2947
+ /**
2948
+ * Respostas a contatos do simulador (número começando com `0`, ver `isPreviewContact`) não chamam
2949
+ * a Meta: o canal devolve `preview.<uuid>` e o resto (janela, transcript, SSE) segue igual.
2950
+ *
2951
+ * **Desligado por omissão.** Nenhum número real começa com `0`, mas ligar é declarar que este
2952
+ * ambiente atende simulador — decisão visível onde o módulo é montado, como `previewMedia`.
2953
+ */
2954
+ previewContacts?: boolean;
2610
2955
  }
2611
2956
  /**
2612
2957
  * Transcrição de áudio. Ausente = desligada, e as colunas ficam nulas ("não avaliado").
@@ -2633,6 +2978,13 @@ interface MetaWhatsAppTranscriptionConfig {
2633
2978
  languageHint?: string;
2634
2979
  }
2635
2980
  interface MetaWhatsAppModuleProviders {
2981
+ /**
2982
+ * Fila durável para os efeitos do webhook (hooks, realtime). Ausente, rodam dentro da requisição,
2983
+ * como sempre. Presente, o webhook só persiste e enfileira; o worker do host chama
2984
+ * `webhook.processInboundDispatch.execute(job)`. Ver docs/webhook-durability.md — qualquer fila
2985
+ * com durabilidade e retentativa serve, inclusive uma tabela no Postgres.
2986
+ */
2987
+ inboundQueue?: InboundDispatchQueueInterface;
2636
2988
  objectStorage?: ObjectStorageInterface;
2637
2989
  cache?: CacheInterface;
2638
2990
  realtime?: RealtimeNotifierInterface;
@@ -2644,6 +2996,11 @@ interface MetaWhatsAppModuleProviders {
2644
2996
  * transcrever um áudio já salvo significa ler os bytes de volta.
2645
2997
  */
2646
2998
  transcription?: MetaWhatsAppTranscriptionConfig;
2999
+ /**
3000
+ * Um turno do runner por conversa. Padrão: `pg_advisory_xact_lock` no `db` do módulo (uma conexão
3001
+ * do pool por conversa em atendimento simultâneo). Troque por um lock distribuído próprio se preferir.
3002
+ */
3003
+ flowTurnLock?: FlowTurnLockInterface;
2647
3004
  }
2648
3005
  interface CreateMetaWhatsAppModuleParams {
2649
3006
  db: MetaWhatsAppDatabase;
@@ -2662,6 +3019,7 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2662
3019
  send: SendMessageUseCase;
2663
3020
  takeover: TakeoverConversationUseCase;
2664
3021
  release: ReleaseConversationUseCase;
3022
+ requestHuman: RequestHumanConversationUseCase;
2665
3023
  list: ListConversationsUseCase;
2666
3024
  listMessages: ListMessagesUseCase;
2667
3025
  listDocuments: ListConversationDocumentsUseCase;
@@ -2693,15 +3051,152 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2693
3051
  previewMedia: StorePreviewMediaUseCase | undefined;
2694
3052
  webhook: {
2695
3053
  receive: ReceiveWebhookUseCase;
3054
+ /**
3055
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
3056
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
3057
+ * Quem assina e entrega em `receive` é a rota do host.
3058
+ */
3059
+ buildPreviewPayload: (command: PreviewInboundCommand, envelope?: Omit<PreviewPayloadEnvelope, "phoneNumberId">) => {
3060
+ object: string;
3061
+ entry: {
3062
+ id: string;
3063
+ changes: {
3064
+ value: {
3065
+ messages?: {
3066
+ id: string;
3067
+ type: string;
3068
+ from: string;
3069
+ timestamp: string;
3070
+ text?: {
3071
+ body: string;
3072
+ } | undefined;
3073
+ image?: {
3074
+ id: string;
3075
+ mime_type: string;
3076
+ sha256?: string | undefined;
3077
+ caption?: string | undefined;
3078
+ filename?: string | undefined;
3079
+ } | undefined;
3080
+ audio?: {
3081
+ id: string;
3082
+ mime_type: string;
3083
+ sha256?: string | undefined;
3084
+ caption?: string | undefined;
3085
+ filename?: string | undefined;
3086
+ } | undefined;
3087
+ video?: {
3088
+ id: string;
3089
+ mime_type: string;
3090
+ sha256?: string | undefined;
3091
+ caption?: string | undefined;
3092
+ filename?: string | undefined;
3093
+ } | undefined;
3094
+ document?: {
3095
+ id: string;
3096
+ mime_type: string;
3097
+ sha256?: string | undefined;
3098
+ caption?: string | undefined;
3099
+ filename?: string | undefined;
3100
+ } | undefined;
3101
+ sticker?: {
3102
+ id: string;
3103
+ mime_type: string;
3104
+ sha256?: string | undefined;
3105
+ caption?: string | undefined;
3106
+ filename?: string | undefined;
3107
+ } | undefined;
3108
+ interactive?: {
3109
+ type: string;
3110
+ button_reply?: {
3111
+ id: string;
3112
+ title: string;
3113
+ } | undefined;
3114
+ list_reply?: {
3115
+ id: string;
3116
+ title: string;
3117
+ } | undefined;
3118
+ } | undefined;
3119
+ button?: {
3120
+ text: string;
3121
+ payload?: string | undefined;
3122
+ } | undefined;
3123
+ order?: {
3124
+ catalog_id: string;
3125
+ product_items: {
3126
+ product_retailer_id: string;
3127
+ quantity: number;
3128
+ item_price: number;
3129
+ currency: string;
3130
+ }[];
3131
+ text?: string | undefined;
3132
+ } | undefined;
3133
+ location?: {
3134
+ latitude: number;
3135
+ longitude: number;
3136
+ name?: string | undefined;
3137
+ address?: string | undefined;
3138
+ url?: string | undefined;
3139
+ } | undefined;
3140
+ context?: {
3141
+ id?: string | undefined;
3142
+ from?: string | undefined;
3143
+ referred_product?: {
3144
+ catalog_id: string;
3145
+ product_retailer_id: string;
3146
+ } | undefined;
3147
+ } | undefined;
3148
+ }[] | undefined;
3149
+ message_echoes?: {
3150
+ id: string;
3151
+ type: string;
3152
+ from: string;
3153
+ timestamp: string;
3154
+ }[] | undefined;
3155
+ messaging_product?: string | undefined;
3156
+ contacts?: {
3157
+ wa_id: string;
3158
+ profile?: {
3159
+ name: string;
3160
+ } | undefined;
3161
+ }[] | undefined;
3162
+ statuses?: {
3163
+ id: string;
3164
+ status: "sent" | "delivered" | "read" | "failed";
3165
+ timestamp: string;
3166
+ recipient_id?: string | undefined;
3167
+ errors?: {
3168
+ code?: number | undefined;
3169
+ message?: string | undefined;
3170
+ title?: string | undefined;
3171
+ href?: string | undefined;
3172
+ error_data?: {
3173
+ details?: string | undefined;
3174
+ } | undefined;
3175
+ }[] | undefined;
3176
+ }[] | undefined;
3177
+ metadata?: {
3178
+ display_phone_number: string;
3179
+ phone_number_id: string;
3180
+ } | undefined;
3181
+ } & {
3182
+ [k: string]: unknown;
3183
+ };
3184
+ field?: string | undefined;
3185
+ }[];
3186
+ }[];
3187
+ };
2696
3188
  verifyChallenge: (query: {
2697
3189
  mode: string | null;
2698
3190
  token: string | null;
2699
3191
  challenge: string | null;
2700
3192
  }) => string;
3193
+ processInboundDispatch: ProcessInboundDispatchUseCase;
2701
3194
  };
2702
3195
  flows: {
2703
3196
  interpreter: FlowInterpreter;
2704
3197
  registerFlowAction: (kind: FlowActionKind, handler: FlowActionHandler) => void;
3198
+ runner: FlowRunner | undefined;
3199
+ registerDynamicChoiceProvider: (key: string, provider: DynamicChoiceProvider) => void;
2705
3200
  get: GetFlowGraphUseCase;
2706
3201
  list: ListFlowGraphsUseCase;
2707
3202
  create: CreateFlowGraphUseCase;
@@ -2732,6 +3227,15 @@ type PreviewMediaSupport = {
2732
3227
  /** Mime a devolver, já que o storage guarda bytes e não o tipo. Padrão `audio/ogg`. */
2733
3228
  readonly defaultMimeType?: string;
2734
3229
  };
3230
+ /**
3231
+ * Respostas a contatos do simulador (`isPreviewContact`). Ligado, todo envio para um número que
3232
+ * começa com `0` volta `preview.<uuid>` sem chamar a Meta — janela, transcript, SSE e status seguem
3233
+ * iguais, então o simulador vê exatamente o que o cliente veria. Nenhum `wa_id` real começa com `0`.
3234
+ */
3235
+ type PreviewContactsSupport = {
3236
+ readonly isEnabled: boolean;
3237
+ readonly generateId?: () => string;
3238
+ };
2735
3239
  declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2736
3240
  private readonly messages;
2737
3241
  /**
@@ -2739,12 +3243,15 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2739
3243
  * que atualizar o pacote não abre nada em quem não pediu.
2740
3244
  */
2741
3245
  private readonly previewMedia?;
3246
+ private readonly previewContacts?;
2742
3247
  constructor(messages: WhatsAppMessageProvider,
2743
3248
  /**
2744
3249
  * Ausente, o adaptador se comporta como sempre: todo id vai para a Graph API. É o que garante
2745
3250
  * que atualizar o pacote não abre nada em quem não pediu.
2746
3251
  */
2747
- previewMedia?: PreviewMediaSupport | undefined);
3252
+ previewMedia?: PreviewMediaSupport | undefined, previewContacts?: PreviewContactsSupport | undefined);
3253
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3254
+ private previewMessageId;
2748
3255
  private translateErrors;
2749
3256
  sendText(to: string, body: string): Promise<{
2750
3257
  externalMessageId: string | null;
@@ -2761,25 +3268,10 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2761
3268
  }): Promise<{
2762
3269
  externalMessageId: string | null;
2763
3270
  }>;
2764
- sendInteractiveList(params: {
2765
- to: string;
2766
- body: string;
2767
- buttonLabel: string;
2768
- rows: {
2769
- id: string;
2770
- title: string;
2771
- }[];
2772
- }): Promise<{
3271
+ sendInteractiveList(params: ChannelInteractiveListParams): Promise<{
2773
3272
  externalMessageId: string | null;
2774
3273
  }>;
2775
- sendInteractiveButtons(params: {
2776
- to: string;
2777
- body: string;
2778
- buttons: {
2779
- id: string;
2780
- title: string;
2781
- }[];
2782
- }): Promise<{
3274
+ sendInteractiveButtons(params: ChannelInteractiveButtonsParams): Promise<{
2783
3275
  externalMessageId: string | null;
2784
3276
  }>;
2785
3277
  sendProductList(params: {
@@ -2813,13 +3305,18 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2813
3305
  declare const INBOUND_LOCATION_CONTENT = "\uD83D\uDCCD Localiza\u00E7\u00E3o";
2814
3306
 
2815
3307
  declare const META_WHATSAPP_MIGRATIONS_TABLE = "meta_whatsapp_migrations";
2816
- declare function metaWhatsAppMigrationsFolder(): string;
3308
+ type MetaWhatsAppMigrationsLayout = 'v1' | 'journal';
3309
+ type MetaWhatsAppMigrationsFolderParams = {
3310
+ readonly layout?: MetaWhatsAppMigrationsLayout;
3311
+ };
3312
+ declare function metaWhatsAppMigrationsFolder(params?: MetaWhatsAppMigrationsFolderParams): string;
2817
3313
  type RunMetaWhatsAppMigrationsParams = {
2818
3314
  db: MetaWhatsAppDatabase;
2819
3315
  migrate: (db: never, config: {
2820
3316
  migrationsFolder: string;
2821
3317
  migrationsTable?: string;
2822
3318
  }) => Promise<void>;
3319
+ layout?: MetaWhatsAppMigrationsLayout;
2823
3320
  };
2824
3321
  declare function runMetaWhatsAppMigrations(params: RunMetaWhatsAppMigrationsParams): Promise<void>;
2825
3322
 
@@ -2849,6 +3346,115 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
2849
3346
  whatsappNumber: string;
2850
3347
  } | null>;
2851
3348
 
3349
+ /**
3350
+ * Copyright (c) 2026 Ada Technology. MIT License.
3351
+ *
3352
+ * O que a mensagem do cliente oferece como resposta. Toque em botão/lista é `reply` (o id é
3353
+ * confiável); texto e botão de template são `text` (passam por casamento de rótulo); áudio, imagem,
3354
+ * localização e afins são `unsupported` — o runner avisa e repergunta sem contar tentativa.
3355
+ */
3356
+
3357
+ type FlowInbound = {
3358
+ readonly kind: 'reply';
3359
+ readonly answer: string;
3360
+ } | {
3361
+ readonly kind: 'text';
3362
+ readonly answer: string;
3363
+ } | {
3364
+ readonly kind: 'unsupported';
3365
+ };
3366
+ declare function readFlowInbound(message: WhatsAppMessage): FlowInbound;
3367
+
3368
+ /**
3369
+ * Copyright (c) 2026 Ada Technology. MIT License.
3370
+ *
3371
+ * Textos padrão do runner (pt-BR). Todos substituíveis por `FlowRunnerConfig` ou pelo próprio nó.
3372
+ */
3373
+ declare const DEFAULT_START_FLOW_KEY = "main";
3374
+ declare const DEFAULT_MAX_INVALID_ANSWERS = 2;
3375
+ declare const DEFAULT_FLOW_TEXT: {
3376
+ readonly FALLBACK: "Não entendi. Pode responder de novo?";
3377
+ readonly CHOICE_PROMPT: "Escolha uma opção:";
3378
+ readonly LIST_BUTTON_LABEL: "Ver opções";
3379
+ readonly SEE_MORE: "Ver mais";
3380
+ readonly NON_TEXT_ANSWER: "Por aqui eu entendo só texto. Pode escrever a resposta?";
3381
+ readonly MORE_OPTIONS_TRUNCATED: "…";
3382
+ readonly HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.";
3383
+ readonly HANDOFF_OUT_OF_HOURS: "Nossa equipe está fora do horário agora. Sua mensagem ficou registrada e respondemos assim que voltarmos.";
3384
+ };
3385
+ /** Id da linha "ver mais" de um `dynamic_choice`. Começa com `__` para não colidir com id do host. */
3386
+ declare const DYNAMIC_CHOICE_MORE_ID = "__more__";
3387
+ /**
3388
+ * Chave reservada do contexto com o estado do runner (tentativas inválidas, página do
3389
+ * `dynamic_choice`). Fica no contexto porque é estado da conversa e precisa sobreviver entre
3390
+ * mensagens; o prefixo `__` a separa das respostas do cliente.
3391
+ */
3392
+ declare const FLOW_RUNTIME_CONTEXT_KEY = "__flow";
3393
+
3394
+ /**
3395
+ * Copyright (c) 2026 Ada Technology. MIT License.
3396
+ *
3397
+ * Escolha → mensagem do canal. Botão com até 3 opções simples, lista com descrição/seção ou com 4+,
3398
+ * e texto numerado quando nem a lista cabe nos tetos da Meta.
3399
+ *
3400
+ * O texto numerado é a rede de segurança: passar de um teto faz a Graph API recusar a mensagem
3401
+ * inteira e o cliente ver silêncio. Numerado, ele ainda responde "2" e o runner entende.
3402
+ */
3403
+
3404
+ type FlowChoiceOption = {
3405
+ readonly id: string;
3406
+ readonly title: string;
3407
+ readonly description?: string;
3408
+ readonly section?: string;
3409
+ };
3410
+ type FlowOutboundMessage = {
3411
+ readonly kind: 'text';
3412
+ readonly body: string;
3413
+ } | {
3414
+ readonly kind: 'interactive';
3415
+ readonly interactive: InteractiveMessage;
3416
+ };
3417
+ type BuildFlowChoiceMessageParams = {
3418
+ readonly body: string;
3419
+ readonly options: readonly FlowChoiceOption[];
3420
+ readonly listButtonLabel: string;
3421
+ };
3422
+ declare function buildFlowChoiceMessage(params: BuildFlowChoiceMessageParams): FlowOutboundMessage;
3423
+
3424
+ /**
3425
+ * Copyright (c) 2026 Ada Technology. MIT License.
3426
+ *
3427
+ * O que a mensagem do cliente significa para o nó em que a conversa parou. Pura: o runner decide o
3428
+ * que fazer com a decisão (avançar, saltar, pedir de novo).
3429
+ */
3430
+
3431
+ type FlowAnswerDecision = {
3432
+ readonly kind: 'answer';
3433
+ readonly userAnswer: string;
3434
+ readonly value?: unknown;
3435
+ } | {
3436
+ readonly kind: 'jump';
3437
+ readonly target: string;
3438
+ } | {
3439
+ readonly kind: 'see-more';
3440
+ } | {
3441
+ readonly kind: 'invalid';
3442
+ readonly rejection?: FlowAnswerRejection;
3443
+ };
3444
+ type ResolveFlowAnswerParams = {
3445
+ readonly node: FlowNodeData;
3446
+ /** Texto, ou o id de botão/linha. `undefined` para mídia, localização e afins. */
3447
+ readonly answer: string | undefined;
3448
+ /** Veio de toque em botão/lista — o id é confiável e não passa por casamento de texto. */
3449
+ readonly isInteractiveReply: boolean;
3450
+ readonly context: Readonly<Record<string, unknown>>;
3451
+ readonly clock: FlowClock;
3452
+ /** Opções exibidas na última página de um `dynamic_choice` (id, título), incluindo "ver mais". */
3453
+ readonly dynamicOptions?: readonly (readonly [string, string])[];
3454
+ };
3455
+ declare function isChoiceNode(node: FlowNodeData): boolean;
3456
+ declare function resolveFlowAnswer(params: ResolveFlowAnswerParams): FlowAnswerDecision;
3457
+
2852
3458
  /**
2853
3459
  * Porta de escrita no transcript, e não a classe `LogMessageUseCase`.
2854
3460
  *
@@ -2977,4 +3583,4 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
2977
3583
  }): Promise<void>;
2978
3584
  }
2979
3585
 
2980
- export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, INBOUND_LOCATION_CONTENT, 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 LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, 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, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
3586
+ 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 CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowChoiceOption, type FlowGlobalKeyword, 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 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 LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, 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 ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, 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, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };