@adatechnology/meta-whatsapp-module 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +174 -0
- package/dist/index.cjs +1329 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +661 -7
- package/dist/index.d.ts +661 -7
- package/dist/index.js +1280 -30
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,12 +1,34 @@
|
|
|
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, InteractiveMessage, MetaWhatsAppHooks, FlowActionKind, FlowActionHandler, ConversationSession, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams } 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';
|
|
8
9
|
|
|
9
|
-
type
|
|
10
|
+
type QueryBuilderMethod = (...args: never[]) => unknown;
|
|
11
|
+
/**
|
|
12
|
+
* Forma mínima de uma conexão Drizzle Postgres: os métodos do query builder que o módulo chama.
|
|
13
|
+
* É o que um host em drizzle-orm 0.36–0.45 (`PgDatabase`, sem `PgAsyncDatabase`) é checado contra —
|
|
14
|
+
* um `Pool` do `pg` ou outro objeto qualquer não passa.
|
|
15
|
+
*/
|
|
16
|
+
type MetaWhatsAppDatabaseShape = {
|
|
17
|
+
readonly select: QueryBuilderMethod;
|
|
18
|
+
readonly insert: QueryBuilderMethod;
|
|
19
|
+
readonly update: QueryBuilderMethod;
|
|
20
|
+
readonly delete: QueryBuilderMethod;
|
|
21
|
+
readonly execute: QueryBuilderMethod;
|
|
22
|
+
readonly transaction: QueryBuilderMethod;
|
|
23
|
+
};
|
|
24
|
+
type IsAny<TValue> = 0 extends 1 & TValue ? true : false;
|
|
25
|
+
/**
|
|
26
|
+
* `PgAsyncDatabase` só existe no drizzle-orm 1.x. Num host em 0.x o import acima não resolve e, com
|
|
27
|
+
* `skipLibCheck`, vira `any` — qualquer coisa passava como `db`. Nesse caso vale a forma mínima; em
|
|
28
|
+
* 1.x continua o tipo exato, sem mudança para quem já usa.
|
|
29
|
+
*/
|
|
30
|
+
type MetaWhatsAppDatabaseFor<TAsyncDatabase> = IsAny<TAsyncDatabase> extends true ? MetaWhatsAppDatabaseShape : TAsyncDatabase;
|
|
31
|
+
type MetaWhatsAppDatabase = MetaWhatsAppDatabaseFor<PgAsyncDatabase<PgQueryResultHKT>>;
|
|
10
32
|
type DrizzleMigrateFunction = (db: never, config: {
|
|
11
33
|
migrationsFolder: string;
|
|
12
34
|
migrationsTable?: string;
|
|
@@ -1389,6 +1411,17 @@ declare class SessionRepository {
|
|
|
1389
1411
|
patchContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string, patch: Partial<TSessionContext>): Promise<void>;
|
|
1390
1412
|
readContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string): Promise<TSessionContext | undefined>;
|
|
1391
1413
|
setFlowPosition(companyId: string, whatsappNumber: string, flowKey: string | null, currentNodeId: string | null): Promise<void>;
|
|
1414
|
+
/**
|
|
1415
|
+
* Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
|
|
1416
|
+
* escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
|
|
1417
|
+
* Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
|
|
1418
|
+
* no mesmo passo já os mudou, e regravá-los desfaria isso.
|
|
1419
|
+
*/
|
|
1420
|
+
saveFlowProgress(companyId: string, whatsappNumber: string, progress: {
|
|
1421
|
+
flowKey: string | null;
|
|
1422
|
+
currentNodeId: string | null;
|
|
1423
|
+
context: Record<string, unknown>;
|
|
1424
|
+
}): Promise<void>;
|
|
1392
1425
|
touchInbound(companyId: string, whatsappNumber: string): Promise<void>;
|
|
1393
1426
|
hoursSinceLastInbound(companyId: string, whatsappNumber: string): Promise<number | undefined>;
|
|
1394
1427
|
setMode(companyId: string, whatsappNumber: string, mode: SessionMode, assignedUserId?: string | null, clearHumanRequest?: boolean): Promise<void>;
|
|
@@ -2137,6 +2170,11 @@ interface FlowStepInput {
|
|
|
2137
2170
|
graph: FlowGraphData;
|
|
2138
2171
|
currentNodeId: string;
|
|
2139
2172
|
userAnswer?: string;
|
|
2173
|
+
/**
|
|
2174
|
+
* Valor a guardar em `contextKey` no lugar do texto cru — a data já convertida, o número já lido.
|
|
2175
|
+
* `userAnswer` continua sendo o que escolhe o ramo (`byAnswer`).
|
|
2176
|
+
*/
|
|
2177
|
+
answerValue?: unknown;
|
|
2140
2178
|
context: Record<string, unknown>;
|
|
2141
2179
|
session: ConversationSession;
|
|
2142
2180
|
channel: ChannelAdapterInterface;
|
|
@@ -2175,14 +2213,325 @@ type FlowRunResult = ({
|
|
|
2175
2213
|
visited: string[];
|
|
2176
2214
|
steps: number;
|
|
2177
2215
|
};
|
|
2216
|
+
type FlowRunOptions = {
|
|
2217
|
+
maxSteps?: number;
|
|
2218
|
+
/**
|
|
2219
|
+
* Chamado ao entrar em cada nó, com o contexto daquele momento — é onde o runner envia o
|
|
2220
|
+
* `directMessage`. Uma ação que devolve contexto já está refletida no nó seguinte.
|
|
2221
|
+
*/
|
|
2222
|
+
onNodeEntered?: (node: FlowNodeData, context: Record<string, unknown>) => Promise<void>;
|
|
2223
|
+
/** Também dispara `onNodeEntered` para o nó de partida (início de fluxo, salto por palavra-chave). */
|
|
2224
|
+
enterInitialNode?: boolean;
|
|
2225
|
+
};
|
|
2178
2226
|
declare class FlowInterpreter {
|
|
2179
2227
|
private readonly actionHandlers;
|
|
2180
2228
|
registerFlowAction(kind: FlowActionKind, handler: FlowActionHandler): void;
|
|
2181
2229
|
step(input: FlowStepInput): Promise<FlowStepResult>;
|
|
2182
2230
|
private moveTo;
|
|
2183
|
-
run(input: FlowStepInput, options?:
|
|
2184
|
-
|
|
2185
|
-
|
|
2231
|
+
run(input: FlowStepInput, options?: FlowRunOptions): Promise<FlowRunResult>;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
/**
|
|
2235
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
2236
|
+
*
|
|
2237
|
+
* Configuração do runner de fluxo. Tudo opcional: sem nada, o runner atende pelo fluxo `main`, com
|
|
2238
|
+
* os textos padrão em pt-BR e encaminhamento a uma pessoa depois de 2 respostas inválidas.
|
|
2239
|
+
*/
|
|
2240
|
+
|
|
2241
|
+
/** Qual texto do runner está sendo pedido ao resolvedor. */
|
|
2242
|
+
type FlowTextKind = 'fallback' | 'rejection' | 'non-text-answer' | 'handoff' | 'handoff-out-of-hours';
|
|
2243
|
+
type FlowTextContext = {
|
|
2244
|
+
readonly companyId: string;
|
|
2245
|
+
readonly whatsappNumber: string;
|
|
2246
|
+
readonly kind: FlowTextKind;
|
|
2247
|
+
/** Só em `kind: 'rejection'`. */
|
|
2248
|
+
readonly rejection?: FlowAnswerRejection;
|
|
2249
|
+
/** Nó em que a conversa está, quando há um. */
|
|
2250
|
+
readonly nodeId?: string;
|
|
2251
|
+
readonly flowKey?: string | null;
|
|
2252
|
+
};
|
|
2253
|
+
/**
|
|
2254
|
+
* Texto resolvido a cada uso, por empresa/conversa (modelos editados no painel, idioma do cliente).
|
|
2255
|
+
* `undefined` cai no próximo texto da cadeia e, no fim, no padrão do pacote. O texto devolvido aceita
|
|
2256
|
+
* `{{chave}}` como o fixo. Se lançar, o erro vai para `onFlowRunnerError` (`stage: 'text'`) e vale o
|
|
2257
|
+
* padrão — o cliente nunca fica sem resposta por causa do resolvedor.
|
|
2258
|
+
*/
|
|
2259
|
+
type FlowTextResolver = (context: FlowTextContext) => string | undefined | Promise<string | undefined>;
|
|
2260
|
+
/** Texto fixo ou resolvido por empresa/conversa. */
|
|
2261
|
+
type FlowConfigText = string | FlowTextResolver;
|
|
2262
|
+
/** O que o validador do host devolve: `undefined`/`{ isValid: true }` aceita. */
|
|
2263
|
+
type FlowAnswerValidatorResult = undefined | {
|
|
2264
|
+
readonly isValid: true;
|
|
2265
|
+
}
|
|
2266
|
+
/** `message` (aceita `{{chave}}`) substitui o texto de nova tentativa só desta vez. */
|
|
2267
|
+
| {
|
|
2268
|
+
readonly isValid: false;
|
|
2269
|
+
readonly message?: string;
|
|
2270
|
+
};
|
|
2271
|
+
/**
|
|
2272
|
+
* Validação extra do host, depois da do pacote ter aceitado a resposta (formato, mínimo, máximo).
|
|
2273
|
+
* Ex.: horário dentro das faixas livres da agenda, data com vaga. Recusa conta como resposta inválida
|
|
2274
|
+
* (`rejected-by-host`), com o mesmo mecanismo de nova tentativa e encaminhamento.
|
|
2275
|
+
*/
|
|
2276
|
+
type FlowAnswerValidator = (params: {
|
|
2277
|
+
readonly companyId: string;
|
|
2278
|
+
readonly session: ConversationSession;
|
|
2279
|
+
readonly node: FlowNodeData;
|
|
2280
|
+
/** Texto do cliente, aparado. */
|
|
2281
|
+
readonly answer: string;
|
|
2282
|
+
/** Valor já convertido pelo pacote (`HH:MM`, `yyyy-mm-dd`, número...). */
|
|
2283
|
+
readonly value: unknown;
|
|
2284
|
+
readonly context: Readonly<Record<string, unknown>>;
|
|
2285
|
+
}) => FlowAnswerValidatorResult | Promise<FlowAnswerValidatorResult>;
|
|
2286
|
+
/** `restart` volta ao início do fluxo de partida; `handoff` chama uma pessoa; `flow:<chave>` abre outro fluxo. */
|
|
2287
|
+
type FlowGlobalKeywordTarget = 'restart' | 'handoff' | `flow:${string}`;
|
|
2288
|
+
/** `exact`: a mensagem inteira é a palavra; `word`: a palavra aparece inteira dentro da mensagem. */
|
|
2289
|
+
type FlowGlobalKeywordMatch = 'exact' | 'word';
|
|
2290
|
+
/** Palavras que valem em qualquer nó ("menu", "atendente"), comparadas sem acento e sem caixa. */
|
|
2291
|
+
type FlowGlobalKeyword = {
|
|
2292
|
+
readonly keywords: readonly string[];
|
|
2293
|
+
/** Padrão `exact`. Com `word`, "quero falar com o atendente" aciona "atendente"; a palavra mais longa vence. */
|
|
2294
|
+
readonly match?: FlowGlobalKeywordMatch;
|
|
2295
|
+
readonly target: FlowGlobalKeywordTarget;
|
|
2296
|
+
};
|
|
2297
|
+
type FlowHandoffConfig = {
|
|
2298
|
+
/** Mensagem dentro do horário (ou sempre, sem `businessHours`). Aceita `{{chave}}`. */
|
|
2299
|
+
readonly message?: FlowConfigText;
|
|
2300
|
+
/** Mensagem fora do horário. Ausente, vale `message`. */
|
|
2301
|
+
readonly outOfHoursMessage?: FlowConfigText;
|
|
2302
|
+
/** Fixo, ou resolvido por empresa a cada encaminhamento (o painel pode mudar sem deploy). */
|
|
2303
|
+
readonly businessHours?: BusinessHours | ((companyId: string) => Promise<BusinessHours | undefined>);
|
|
2304
|
+
};
|
|
2305
|
+
type FlowVariablesResolver = (params: {
|
|
2306
|
+
readonly session: ConversationSession;
|
|
2307
|
+
readonly profileName?: string;
|
|
2308
|
+
}) => Promise<Readonly<Record<string, unknown>>>;
|
|
2309
|
+
type FlowRunnerConfig = {
|
|
2310
|
+
/** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
|
|
2311
|
+
readonly startFlowKey?: string;
|
|
2312
|
+
readonly globalKeywords?: readonly FlowGlobalKeyword[];
|
|
2313
|
+
/** Respostas inválidas seguidas no mesmo nó antes de chamar uma pessoa. Padrão 2; o nó pode sobrescrever. */
|
|
2314
|
+
readonly maxInvalidAnswers?: number;
|
|
2315
|
+
/** Texto de nova tentativa quando o nó não declara `fallbackMessage`. */
|
|
2316
|
+
readonly defaultFallbackMessage?: FlowConfigText;
|
|
2317
|
+
/** Texto de nova tentativa por motivo, antes do padrão ("essa data já passou"). */
|
|
2318
|
+
readonly rejectionMessages?: Partial<Record<FlowAnswerRejection, FlowConfigText>>;
|
|
2319
|
+
/** Corpo de escolha quando o nó não tem `question` (a Meta exige corpo). */
|
|
2320
|
+
readonly choicePrompt?: string;
|
|
2321
|
+
readonly listButtonLabel?: string;
|
|
2322
|
+
/** Rótulo da linha que pede a próxima página de um `dynamic_choice`. */
|
|
2323
|
+
readonly seeMoreLabel?: string;
|
|
2324
|
+
readonly dateLocale?: FlowDateLocale;
|
|
2325
|
+
/**
|
|
2326
|
+
* Fuso de "hoje" na validação de data (IANA). Obrigatório — ou derivado de
|
|
2327
|
+
* `handoff.businessHours.timeZone` quando o horário é fixo: servidor em UTC aceitaria "hoje" errado
|
|
2328
|
+
* entre 21h e meia-noite no Brasil.
|
|
2329
|
+
*/
|
|
2330
|
+
readonly timeZone?: string;
|
|
2331
|
+
/** Resposta que não casa com opção: `reask` (padrão) ou `default` (segue `next.default`). O nó sobrescreve. */
|
|
2332
|
+
readonly unmatchedChoice?: 'reask' | 'default';
|
|
2333
|
+
/** Resposta em áudio, imagem, localização… num nó que espera texto: avisa e repergunta, sem contar tentativa. */
|
|
2334
|
+
readonly nonTextAnswerMessage?: FlowConfigText;
|
|
2335
|
+
/** Validação extra das perguntas (não de escolha), depois da do pacote. Ver `FlowAnswerValidator`. */
|
|
2336
|
+
readonly validateAnswer?: FlowAnswerValidator;
|
|
2337
|
+
readonly handoff?: FlowHandoffConfig;
|
|
2338
|
+
/**
|
|
2339
|
+
* Conversa que pediu atendimento e saiu do fluxo: `silent` (padrão) não responde até alguém
|
|
2340
|
+
* assumir ou devolver ao bot — palavras globais continuam valendo; `continue` reabre o fluxo.
|
|
2341
|
+
*/
|
|
2342
|
+
readonly whileAwaitingHuman?: 'silent' | 'continue';
|
|
2343
|
+
/** Variáveis do host para `{{chave}}` (dados do cadastro, por exemplo). O contexto do fluxo tem precedência. */
|
|
2344
|
+
readonly resolveVariables?: FlowVariablesResolver;
|
|
2345
|
+
readonly formatValue?: InterpolateFlowTextOptions['formatValue'];
|
|
2346
|
+
readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
|
|
2347
|
+
/** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
|
|
2348
|
+
readonly maxCrossFlowJumps?: number;
|
|
2349
|
+
/** Relógio injetável para teste. */
|
|
2350
|
+
readonly now?: () => Date;
|
|
2351
|
+
};
|
|
2352
|
+
type FlowRunnerOutcome = 'handled' | 'duplicate' | 'no-session' | 'human-mode' | 'awaiting-human' | 'no-flow';
|
|
2353
|
+
|
|
2354
|
+
/**
|
|
2355
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
2356
|
+
*
|
|
2357
|
+
* Encaminhamento a uma pessoa: põe a conversa na fila (`requestHuman`, que dispara
|
|
2358
|
+
* `onHumanRequested` e `onConversationModeChanged`) e avisa o cliente com o texto certo para a hora.
|
|
2359
|
+
*
|
|
2360
|
+
* Um só caminho para os três gatilhos — o nó `handoff`, a palavra global e o excesso de respostas
|
|
2361
|
+
* inválidas. Três cópias divergiriam no texto e no horário.
|
|
2362
|
+
*/
|
|
2363
|
+
|
|
2364
|
+
type FlowHandoffDependencies = {
|
|
2365
|
+
readonly requestHuman: RequestHumanConversationUseCase;
|
|
2366
|
+
readonly sendMessage: SendMessageUseCase;
|
|
2367
|
+
readonly startState: SessionState;
|
|
2368
|
+
readonly config: FlowHandoffConfig;
|
|
2369
|
+
readonly now: () => Date;
|
|
2370
|
+
readonly interpolation: InterpolateFlowTextOptions;
|
|
2371
|
+
readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
|
|
2372
|
+
};
|
|
2373
|
+
type RequestFlowHandoffParams = {
|
|
2374
|
+
readonly companyId: string;
|
|
2375
|
+
readonly whatsappNumber: string;
|
|
2376
|
+
readonly variables: Readonly<Record<string, unknown>>;
|
|
2377
|
+
readonly node?: FlowNodeData;
|
|
2378
|
+
};
|
|
2379
|
+
declare class FlowHandoff {
|
|
2380
|
+
private readonly dependencies;
|
|
2381
|
+
constructor(dependencies: FlowHandoffDependencies);
|
|
2382
|
+
/** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
|
|
2383
|
+
request(params: RequestFlowHandoffParams): Promise<boolean>;
|
|
2384
|
+
/**
|
|
2385
|
+
* Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
|
|
2386
|
+
* sobrescrevem os textos do runner para aquele nó.
|
|
2387
|
+
*/
|
|
2388
|
+
createActionHandler(resolveVariables: (params: {
|
|
2389
|
+
session: ConversationSession;
|
|
2390
|
+
context: Record<string, unknown>;
|
|
2391
|
+
}) => Record<string, unknown>): FlowActionHandler;
|
|
2392
|
+
private reportFailure;
|
|
2393
|
+
private isWithinHours;
|
|
2394
|
+
private messageFor;
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
/**
|
|
2398
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
2399
|
+
*
|
|
2400
|
+
* Um turno do runner por conversa de cada vez. Duas mensagens do mesmo cliente processadas em
|
|
2401
|
+
* paralelo leriam a mesma posição, responderiam ao mesmo nó e a última gravação apagaria a outra.
|
|
2402
|
+
*
|
|
2403
|
+
* Porta, com implementação padrão no Postgres do próprio módulo; o host troca por outra (Redis,
|
|
2404
|
+
* fila particionada por conversa) quando quiser.
|
|
2405
|
+
*/
|
|
2406
|
+
|
|
2407
|
+
type FlowTurnLockKey = {
|
|
2408
|
+
readonly companyId: string;
|
|
2409
|
+
readonly whatsappNumber: string;
|
|
2410
|
+
};
|
|
2411
|
+
interface FlowTurnLockInterface {
|
|
2412
|
+
withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* `pg_advisory_xact_lock` numa transação que dura o turno. A transação não toca linha nenhuma —
|
|
2416
|
+
* só segura o lock (e uma conexão do pool) enquanto o turno roda; as escritas do turno usam a
|
|
2417
|
+
* conexão normal. O lock sai sozinho no fim da transação, inclusive se o processo morrer.
|
|
2418
|
+
*
|
|
2419
|
+
* Custo: uma conexão por conversa em atendimento simultâneo. Com muitas conversas ao mesmo tempo,
|
|
2420
|
+
* dimensione o pool ou injete outra implementação.
|
|
2421
|
+
*/
|
|
2422
|
+
declare class PostgresAdvisoryFlowTurnLock implements FlowTurnLockInterface {
|
|
2423
|
+
private readonly db;
|
|
2424
|
+
constructor(db: MetaWhatsAppDatabase);
|
|
2425
|
+
withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
|
|
2426
|
+
}
|
|
2427
|
+
/** Lock dentro do processo: serve para uma instância só e para testes. Não protege entre réplicas. */
|
|
2428
|
+
declare class InProcessFlowTurnLock implements FlowTurnLockInterface {
|
|
2429
|
+
private readonly tails;
|
|
2430
|
+
withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
/**
|
|
2434
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
2435
|
+
*
|
|
2436
|
+
* Runner de fluxo: o que faltava entre o `FlowInterpreter` (máquina de estados pura) e o cliente.
|
|
2437
|
+
* Carrega o grafo publicado, entende a resposta, avança o interpretador, grava posição e contexto e
|
|
2438
|
+
* fala com o cliente — pergunta, botões/lista, `directMessage`, nova tentativa e encaminhamento.
|
|
2439
|
+
*
|
|
2440
|
+
* Antes dele, cada host escrevia o próprio driver (centenas de linhas) e o motor de fluxo do pacote
|
|
2441
|
+
* não fazia nada sozinho depois do `onMessageReceived`.
|
|
2442
|
+
*/
|
|
2443
|
+
|
|
2444
|
+
type FlowRunnerDependencies = {
|
|
2445
|
+
readonly interpreter: FlowInterpreter;
|
|
2446
|
+
readonly flowGraphRepository: Pick<FlowGraphRepository, 'get'>;
|
|
2447
|
+
readonly sessionRepository: SessionRepository;
|
|
2448
|
+
readonly sendMessage: SendMessageUseCase;
|
|
2449
|
+
readonly channel: ChannelAdapterInterface;
|
|
2450
|
+
readonly handoff: FlowHandoff;
|
|
2451
|
+
readonly lock: FlowTurnLockInterface;
|
|
2452
|
+
readonly startState: SessionState;
|
|
2453
|
+
readonly config: FlowRunnerConfig;
|
|
2454
|
+
readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
|
|
2455
|
+
};
|
|
2456
|
+
type HandleFlowMessageParams = {
|
|
2457
|
+
readonly companyId: string;
|
|
2458
|
+
readonly message: WhatsAppMessage;
|
|
2459
|
+
readonly profileName?: string;
|
|
2460
|
+
};
|
|
2461
|
+
type StartFlowParams = {
|
|
2462
|
+
readonly companyId: string;
|
|
2463
|
+
readonly whatsappNumber: string;
|
|
2464
|
+
/** Ausente, o fluxo de partida. */
|
|
2465
|
+
readonly flowKey?: string;
|
|
2466
|
+
readonly profileName?: string;
|
|
2467
|
+
};
|
|
2468
|
+
/** Fuso do runner: o configurado, ou o do horário de atendimento fixo. Sem nenhum, falha no boot. */
|
|
2469
|
+
declare function resolveFlowTimeZone(config: FlowRunnerConfig): string;
|
|
2470
|
+
declare class FlowRunner {
|
|
2471
|
+
private readonly dependencies;
|
|
2472
|
+
private readonly renderer;
|
|
2473
|
+
private readonly timeZone;
|
|
2474
|
+
private readonly turnVariables;
|
|
2475
|
+
constructor(dependencies: FlowRunnerDependencies);
|
|
2476
|
+
registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
|
|
2477
|
+
/**
|
|
2478
|
+
* Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
|
|
2479
|
+
* vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
|
|
2480
|
+
* o sistema conhece pelo que o cliente digitou.
|
|
2481
|
+
*/
|
|
2482
|
+
variablesFor(params: {
|
|
2483
|
+
session: ConversationSession;
|
|
2484
|
+
context: Record<string, unknown>;
|
|
2485
|
+
}): Record<string, unknown>;
|
|
2486
|
+
/** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
|
|
2487
|
+
handle(params: HandleFlowMessageParams): Promise<FlowRunnerOutcome>;
|
|
2488
|
+
/** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
|
|
2489
|
+
start(params: StartFlowParams): Promise<FlowRunnerOutcome>;
|
|
2490
|
+
private handleLocked;
|
|
2491
|
+
private route;
|
|
2492
|
+
private guard;
|
|
2493
|
+
/** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
|
|
2494
|
+
private claim;
|
|
2495
|
+
private openTurn;
|
|
2496
|
+
private startFlowKey;
|
|
2497
|
+
private clock;
|
|
2498
|
+
private loadGraph;
|
|
2499
|
+
private globalKeywordTarget;
|
|
2500
|
+
private keywordJumpAtStart;
|
|
2501
|
+
/**
|
|
2502
|
+
* Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
|
|
2503
|
+
* fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
|
|
2504
|
+
* espera; quando o fluxo terminar, o runner volta ao silêncio.
|
|
2505
|
+
*/
|
|
2506
|
+
private applyGlobalTarget;
|
|
2507
|
+
private answerNode;
|
|
2508
|
+
/** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
|
|
2509
|
+
private renderedOptions;
|
|
2510
|
+
/**
|
|
2511
|
+
* Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
|
|
2512
|
+
* Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
|
|
2513
|
+
*/
|
|
2514
|
+
private validateWithHost;
|
|
2515
|
+
private configText;
|
|
2516
|
+
private followsDefaultWhenUnmatched;
|
|
2517
|
+
private handleInvalid;
|
|
2518
|
+
/** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
|
|
2519
|
+
private fallbackText;
|
|
2520
|
+
private handOff;
|
|
2521
|
+
private jumpTo;
|
|
2522
|
+
private runFrom;
|
|
2523
|
+
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
2524
|
+
private awaitAnswer;
|
|
2525
|
+
private say;
|
|
2526
|
+
private send;
|
|
2527
|
+
private save;
|
|
2528
|
+
private reportMissingFlow;
|
|
2529
|
+
/**
|
|
2530
|
+
* Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
|
|
2531
|
+
* uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
|
|
2532
|
+
* ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
|
|
2533
|
+
*/
|
|
2534
|
+
private report;
|
|
2186
2535
|
}
|
|
2187
2536
|
|
|
2188
2537
|
type FlowMediaLocation = {
|
|
@@ -2356,6 +2705,8 @@ declare class InboundEffectsDispatcher {
|
|
|
2356
2705
|
sessionRepository: SessionRepository;
|
|
2357
2706
|
hooks?: MetaWhatsAppHooks;
|
|
2358
2707
|
realtime?: RealtimeNotifierInterface;
|
|
2708
|
+
/** Presente quando `features.flowRunner` está ligado: o módulo dirige o fluxo depois do hook. */
|
|
2709
|
+
flowRunner?: Pick<FlowRunner, 'handle'>;
|
|
2359
2710
|
});
|
|
2360
2711
|
run(job: InboundDispatchJob): Promise<void>;
|
|
2361
2712
|
runMessageEffects(job: InboundMessageEffectsJob): Promise<void>;
|
|
@@ -2406,6 +2757,8 @@ declare class ReceiveWebhookUseCase {
|
|
|
2406
2757
|
inboundQueue?: InboundDispatchQueueInterface;
|
|
2407
2758
|
/** Não grava `location` no transcript; ver `MetaWhatsAppModuleFeatures.redactInboundLocation`. */
|
|
2408
2759
|
redactInboundLocation?: boolean;
|
|
2760
|
+
/** Runner de fluxo (`features.flowRunner`); ausente, o host dirige a conversa. */
|
|
2761
|
+
flowRunner?: Pick<FlowRunner, 'handle'>;
|
|
2409
2762
|
});
|
|
2410
2763
|
private readonly dispatcher;
|
|
2411
2764
|
execute(input: ReceiveWebhookParams): Promise<ReceiveWebhookResult>;
|
|
@@ -2662,6 +3015,24 @@ interface MetaWhatsAppModuleFeatures {
|
|
|
2662
3015
|
* fila do host. Linhas já gravadas se redigem com `conversations.redactInboundLocations`.
|
|
2663
3016
|
*/
|
|
2664
3017
|
redactInboundLocation?: boolean;
|
|
3018
|
+
/**
|
|
3019
|
+
* O módulo dirige a conversa pelo grafo publicado depois do `onMessageReceived` devolver
|
|
3020
|
+
* `'continue'`: pergunta, valida, avança, grava e encaminha. `true` usa os padrões; o objeto
|
|
3021
|
+
* configura (fluxo de partida, palavras globais, horário de atendimento, textos — ver
|
|
3022
|
+
* `FlowRunnerConfig`).
|
|
3023
|
+
*
|
|
3024
|
+
* **Desligado por omissão**: host que já dirige o próprio fluxo depois do `'continue'` passaria a
|
|
3025
|
+
* receber duas respostas. Exige `flowEngine` (padrão ligado).
|
|
3026
|
+
*/
|
|
3027
|
+
flowRunner?: boolean | FlowRunnerConfig;
|
|
3028
|
+
/**
|
|
3029
|
+
* Respostas a contatos do simulador (número começando com `0`, ver `isPreviewContact`) não chamam
|
|
3030
|
+
* a Meta: o canal devolve `preview.<uuid>` e o resto (janela, transcript, SSE) segue igual.
|
|
3031
|
+
*
|
|
3032
|
+
* **Desligado por omissão.** Nenhum número real começa com `0`, mas ligar é declarar que este
|
|
3033
|
+
* ambiente atende simulador — decisão visível onde o módulo é montado, como `previewMedia`.
|
|
3034
|
+
*/
|
|
3035
|
+
previewContacts?: boolean;
|
|
2665
3036
|
}
|
|
2666
3037
|
/**
|
|
2667
3038
|
* Transcrição de áudio. Ausente = desligada, e as colunas ficam nulas ("não avaliado").
|
|
@@ -2706,6 +3077,11 @@ interface MetaWhatsAppModuleProviders {
|
|
|
2706
3077
|
* transcrever um áudio já salvo significa ler os bytes de volta.
|
|
2707
3078
|
*/
|
|
2708
3079
|
transcription?: MetaWhatsAppTranscriptionConfig;
|
|
3080
|
+
/**
|
|
3081
|
+
* Um turno do runner por conversa. Padrão: `pg_advisory_xact_lock` no `db` do módulo (uma conexão
|
|
3082
|
+
* do pool por conversa em atendimento simultâneo). Troque por um lock distribuído próprio se preferir.
|
|
3083
|
+
*/
|
|
3084
|
+
flowTurnLock?: FlowTurnLockInterface;
|
|
2709
3085
|
}
|
|
2710
3086
|
interface CreateMetaWhatsAppModuleParams {
|
|
2711
3087
|
db: MetaWhatsAppDatabase;
|
|
@@ -2756,6 +3132,140 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
|
|
|
2756
3132
|
previewMedia: StorePreviewMediaUseCase | undefined;
|
|
2757
3133
|
webhook: {
|
|
2758
3134
|
receive: ReceiveWebhookUseCase;
|
|
3135
|
+
/**
|
|
3136
|
+
* Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
|
|
3137
|
+
* DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
|
|
3138
|
+
* Quem assina e entrega em `receive` é a rota do host.
|
|
3139
|
+
*/
|
|
3140
|
+
buildPreviewPayload: (command: PreviewInboundCommand, envelope?: Omit<PreviewPayloadEnvelope, "phoneNumberId">) => {
|
|
3141
|
+
object: string;
|
|
3142
|
+
entry: {
|
|
3143
|
+
id: string;
|
|
3144
|
+
changes: {
|
|
3145
|
+
value: {
|
|
3146
|
+
messages?: {
|
|
3147
|
+
id: string;
|
|
3148
|
+
type: string;
|
|
3149
|
+
from: string;
|
|
3150
|
+
timestamp: string;
|
|
3151
|
+
text?: {
|
|
3152
|
+
body: string;
|
|
3153
|
+
} | undefined;
|
|
3154
|
+
image?: {
|
|
3155
|
+
id: string;
|
|
3156
|
+
mime_type: string;
|
|
3157
|
+
sha256?: string | undefined;
|
|
3158
|
+
caption?: string | undefined;
|
|
3159
|
+
filename?: string | undefined;
|
|
3160
|
+
} | undefined;
|
|
3161
|
+
audio?: {
|
|
3162
|
+
id: string;
|
|
3163
|
+
mime_type: string;
|
|
3164
|
+
sha256?: string | undefined;
|
|
3165
|
+
caption?: string | undefined;
|
|
3166
|
+
filename?: string | undefined;
|
|
3167
|
+
} | undefined;
|
|
3168
|
+
video?: {
|
|
3169
|
+
id: string;
|
|
3170
|
+
mime_type: string;
|
|
3171
|
+
sha256?: string | undefined;
|
|
3172
|
+
caption?: string | undefined;
|
|
3173
|
+
filename?: string | undefined;
|
|
3174
|
+
} | undefined;
|
|
3175
|
+
document?: {
|
|
3176
|
+
id: string;
|
|
3177
|
+
mime_type: string;
|
|
3178
|
+
sha256?: string | undefined;
|
|
3179
|
+
caption?: string | undefined;
|
|
3180
|
+
filename?: string | undefined;
|
|
3181
|
+
} | undefined;
|
|
3182
|
+
sticker?: {
|
|
3183
|
+
id: string;
|
|
3184
|
+
mime_type: string;
|
|
3185
|
+
sha256?: string | undefined;
|
|
3186
|
+
caption?: string | undefined;
|
|
3187
|
+
filename?: string | undefined;
|
|
3188
|
+
} | undefined;
|
|
3189
|
+
interactive?: {
|
|
3190
|
+
type: string;
|
|
3191
|
+
button_reply?: {
|
|
3192
|
+
id: string;
|
|
3193
|
+
title: string;
|
|
3194
|
+
} | undefined;
|
|
3195
|
+
list_reply?: {
|
|
3196
|
+
id: string;
|
|
3197
|
+
title: string;
|
|
3198
|
+
} | undefined;
|
|
3199
|
+
} | undefined;
|
|
3200
|
+
button?: {
|
|
3201
|
+
text: string;
|
|
3202
|
+
payload?: string | undefined;
|
|
3203
|
+
} | undefined;
|
|
3204
|
+
order?: {
|
|
3205
|
+
catalog_id: string;
|
|
3206
|
+
product_items: {
|
|
3207
|
+
product_retailer_id: string;
|
|
3208
|
+
quantity: number;
|
|
3209
|
+
item_price: number;
|
|
3210
|
+
currency: string;
|
|
3211
|
+
}[];
|
|
3212
|
+
text?: string | undefined;
|
|
3213
|
+
} | undefined;
|
|
3214
|
+
location?: {
|
|
3215
|
+
latitude: number;
|
|
3216
|
+
longitude: number;
|
|
3217
|
+
name?: string | undefined;
|
|
3218
|
+
address?: string | undefined;
|
|
3219
|
+
url?: string | undefined;
|
|
3220
|
+
} | undefined;
|
|
3221
|
+
context?: {
|
|
3222
|
+
id?: string | undefined;
|
|
3223
|
+
from?: string | undefined;
|
|
3224
|
+
referred_product?: {
|
|
3225
|
+
catalog_id: string;
|
|
3226
|
+
product_retailer_id: string;
|
|
3227
|
+
} | undefined;
|
|
3228
|
+
} | undefined;
|
|
3229
|
+
}[] | undefined;
|
|
3230
|
+
message_echoes?: {
|
|
3231
|
+
id: string;
|
|
3232
|
+
type: string;
|
|
3233
|
+
from: string;
|
|
3234
|
+
timestamp: string;
|
|
3235
|
+
}[] | undefined;
|
|
3236
|
+
messaging_product?: string | undefined;
|
|
3237
|
+
contacts?: {
|
|
3238
|
+
wa_id: string;
|
|
3239
|
+
profile?: {
|
|
3240
|
+
name: string;
|
|
3241
|
+
} | undefined;
|
|
3242
|
+
}[] | undefined;
|
|
3243
|
+
statuses?: {
|
|
3244
|
+
id: string;
|
|
3245
|
+
status: "sent" | "delivered" | "read" | "failed";
|
|
3246
|
+
timestamp: string;
|
|
3247
|
+
recipient_id?: string | undefined;
|
|
3248
|
+
errors?: {
|
|
3249
|
+
code?: number | undefined;
|
|
3250
|
+
message?: string | undefined;
|
|
3251
|
+
title?: string | undefined;
|
|
3252
|
+
href?: string | undefined;
|
|
3253
|
+
error_data?: {
|
|
3254
|
+
details?: string | undefined;
|
|
3255
|
+
} | undefined;
|
|
3256
|
+
}[] | undefined;
|
|
3257
|
+
}[] | undefined;
|
|
3258
|
+
metadata?: {
|
|
3259
|
+
display_phone_number: string;
|
|
3260
|
+
phone_number_id: string;
|
|
3261
|
+
} | undefined;
|
|
3262
|
+
} & {
|
|
3263
|
+
[k: string]: unknown;
|
|
3264
|
+
};
|
|
3265
|
+
field?: string | undefined;
|
|
3266
|
+
}[];
|
|
3267
|
+
}[];
|
|
3268
|
+
};
|
|
2759
3269
|
verifyChallenge: (query: {
|
|
2760
3270
|
mode: string | null;
|
|
2761
3271
|
token: string | null;
|
|
@@ -2766,6 +3276,8 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
|
|
|
2766
3276
|
flows: {
|
|
2767
3277
|
interpreter: FlowInterpreter;
|
|
2768
3278
|
registerFlowAction: (kind: FlowActionKind, handler: FlowActionHandler) => void;
|
|
3279
|
+
runner: FlowRunner | undefined;
|
|
3280
|
+
registerDynamicChoiceProvider: (key: string, provider: DynamicChoiceProvider) => void;
|
|
2769
3281
|
get: GetFlowGraphUseCase;
|
|
2770
3282
|
list: ListFlowGraphsUseCase;
|
|
2771
3283
|
create: CreateFlowGraphUseCase;
|
|
@@ -2796,6 +3308,15 @@ type PreviewMediaSupport = {
|
|
|
2796
3308
|
/** Mime a devolver, já que o storage guarda bytes e não o tipo. Padrão `audio/ogg`. */
|
|
2797
3309
|
readonly defaultMimeType?: string;
|
|
2798
3310
|
};
|
|
3311
|
+
/**
|
|
3312
|
+
* Respostas a contatos do simulador (`isPreviewContact`). Ligado, todo envio para um número que
|
|
3313
|
+
* começa com `0` volta `preview.<uuid>` sem chamar a Meta — janela, transcript, SSE e status seguem
|
|
3314
|
+
* iguais, então o simulador vê exatamente o que o cliente veria. Nenhum `wa_id` real começa com `0`.
|
|
3315
|
+
*/
|
|
3316
|
+
type PreviewContactsSupport = {
|
|
3317
|
+
readonly isEnabled: boolean;
|
|
3318
|
+
readonly generateId?: () => string;
|
|
3319
|
+
};
|
|
2799
3320
|
declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
|
|
2800
3321
|
private readonly messages;
|
|
2801
3322
|
/**
|
|
@@ -2803,12 +3324,15 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
|
|
|
2803
3324
|
* que atualizar o pacote não abre nada em quem não pediu.
|
|
2804
3325
|
*/
|
|
2805
3326
|
private readonly previewMedia?;
|
|
3327
|
+
private readonly previewContacts?;
|
|
2806
3328
|
constructor(messages: WhatsAppMessageProvider,
|
|
2807
3329
|
/**
|
|
2808
3330
|
* Ausente, o adaptador se comporta como sempre: todo id vai para a Graph API. É o que garante
|
|
2809
3331
|
* que atualizar o pacote não abre nada em quem não pediu.
|
|
2810
3332
|
*/
|
|
2811
|
-
previewMedia?: PreviewMediaSupport | undefined);
|
|
3333
|
+
previewMedia?: PreviewMediaSupport | undefined, previewContacts?: PreviewContactsSupport | undefined);
|
|
3334
|
+
/** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
|
|
3335
|
+
private previewMessageId;
|
|
2812
3336
|
private translateErrors;
|
|
2813
3337
|
sendText(to: string, body: string): Promise<{
|
|
2814
3338
|
externalMessageId: string | null;
|
|
@@ -2903,6 +3427,136 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
|
|
|
2903
3427
|
whatsappNumber: string;
|
|
2904
3428
|
} | null>;
|
|
2905
3429
|
|
|
3430
|
+
/**
|
|
3431
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3432
|
+
*
|
|
3433
|
+
* O que a mensagem do cliente oferece como resposta. Toque em botão/lista é `reply` (o id é
|
|
3434
|
+
* confiável); texto e botão de template são `text` (passam por casamento de rótulo); áudio, imagem,
|
|
3435
|
+
* localização e afins são `unsupported` — o runner avisa e repergunta sem contar tentativa.
|
|
3436
|
+
*/
|
|
3437
|
+
|
|
3438
|
+
type FlowInbound = {
|
|
3439
|
+
readonly kind: 'reply';
|
|
3440
|
+
readonly answer: string;
|
|
3441
|
+
} | {
|
|
3442
|
+
readonly kind: 'text';
|
|
3443
|
+
readonly answer: string;
|
|
3444
|
+
} | {
|
|
3445
|
+
readonly kind: 'unsupported';
|
|
3446
|
+
};
|
|
3447
|
+
declare function readFlowInbound(message: WhatsAppMessage): FlowInbound;
|
|
3448
|
+
|
|
3449
|
+
/**
|
|
3450
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3451
|
+
*
|
|
3452
|
+
* Primeiro texto definido de uma cadeia de `FlowConfigText` (fixo ou resolvido por empresa). A cadeia
|
|
3453
|
+
* é a precedência que o runner já tinha — nó, motivo, padrão do host, padrão do pacote —; resolvedor
|
|
3454
|
+
* que devolve `undefined` passa a vez ao próximo.
|
|
3455
|
+
*/
|
|
3456
|
+
|
|
3457
|
+
type ResolveFlowConfigTextParams = {
|
|
3458
|
+
readonly chain: readonly (FlowConfigText | undefined)[];
|
|
3459
|
+
readonly context: FlowTextContext;
|
|
3460
|
+
/** Resolvedor que lançou: reporta e segue a cadeia (o padrão do pacote sempre fecha a resposta). */
|
|
3461
|
+
readonly onError?: (error: unknown) => Promise<void> | void;
|
|
3462
|
+
};
|
|
3463
|
+
declare function resolveFlowConfigText(params: ResolveFlowConfigTextParams): Promise<string | undefined>;
|
|
3464
|
+
|
|
3465
|
+
/**
|
|
3466
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3467
|
+
*
|
|
3468
|
+
* Textos padrão do runner (pt-BR). Todos substituíveis por `FlowRunnerConfig` ou pelo próprio nó.
|
|
3469
|
+
*/
|
|
3470
|
+
declare const DEFAULT_START_FLOW_KEY = "main";
|
|
3471
|
+
declare const DEFAULT_MAX_INVALID_ANSWERS = 2;
|
|
3472
|
+
declare const DEFAULT_FLOW_TEXT: {
|
|
3473
|
+
readonly FALLBACK: "Não entendi. Pode responder de novo?";
|
|
3474
|
+
readonly CHOICE_PROMPT: "Escolha uma opção:";
|
|
3475
|
+
readonly LIST_BUTTON_LABEL: "Ver opções";
|
|
3476
|
+
readonly SEE_MORE: "Ver mais";
|
|
3477
|
+
readonly NON_TEXT_ANSWER: "Por aqui eu entendo só texto. Pode escrever a resposta?";
|
|
3478
|
+
readonly MORE_OPTIONS_TRUNCATED: "…";
|
|
3479
|
+
readonly HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.";
|
|
3480
|
+
readonly HANDOFF_OUT_OF_HOURS: "Nossa equipe está fora do horário agora. Sua mensagem ficou registrada e respondemos assim que voltarmos.";
|
|
3481
|
+
};
|
|
3482
|
+
/** Id da linha "ver mais" de um `dynamic_choice`. Começa com `__` para não colidir com id do host. */
|
|
3483
|
+
declare const DYNAMIC_CHOICE_MORE_ID = "__more__";
|
|
3484
|
+
/**
|
|
3485
|
+
* Chave reservada do contexto com o estado do runner (tentativas inválidas, página do
|
|
3486
|
+
* `dynamic_choice`). Fica no contexto porque é estado da conversa e precisa sobreviver entre
|
|
3487
|
+
* mensagens; o prefixo `__` a separa das respostas do cliente.
|
|
3488
|
+
*/
|
|
3489
|
+
declare const FLOW_RUNTIME_CONTEXT_KEY = "__flow";
|
|
3490
|
+
|
|
3491
|
+
/**
|
|
3492
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3493
|
+
*
|
|
3494
|
+
* Escolha → mensagem do canal. Botão com até 3 opções simples, lista com descrição/seção ou com 4+,
|
|
3495
|
+
* e texto numerado quando nem a lista cabe nos tetos da Meta.
|
|
3496
|
+
*
|
|
3497
|
+
* O texto numerado é a rede de segurança: passar de um teto faz a Graph API recusar a mensagem
|
|
3498
|
+
* inteira e o cliente ver silêncio. Numerado, ele ainda responde "2" e o runner entende.
|
|
3499
|
+
*/
|
|
3500
|
+
|
|
3501
|
+
type FlowChoiceOption = {
|
|
3502
|
+
readonly id: string;
|
|
3503
|
+
readonly title: string;
|
|
3504
|
+
readonly description?: string;
|
|
3505
|
+
readonly section?: string;
|
|
3506
|
+
};
|
|
3507
|
+
type FlowOutboundMessage = {
|
|
3508
|
+
readonly kind: 'text';
|
|
3509
|
+
readonly body: string;
|
|
3510
|
+
} | {
|
|
3511
|
+
readonly kind: 'interactive';
|
|
3512
|
+
readonly interactive: InteractiveMessage;
|
|
3513
|
+
};
|
|
3514
|
+
type BuildFlowChoiceMessageParams = {
|
|
3515
|
+
readonly body: string;
|
|
3516
|
+
readonly options: readonly FlowChoiceOption[];
|
|
3517
|
+
readonly listButtonLabel: string;
|
|
3518
|
+
};
|
|
3519
|
+
declare function buildFlowChoiceMessage(params: BuildFlowChoiceMessageParams): FlowOutboundMessage;
|
|
3520
|
+
|
|
3521
|
+
/**
|
|
3522
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3523
|
+
*
|
|
3524
|
+
* O que a mensagem do cliente significa para o nó em que a conversa parou. Pura: o runner decide o
|
|
3525
|
+
* que fazer com a decisão (avançar, saltar, pedir de novo).
|
|
3526
|
+
*/
|
|
3527
|
+
|
|
3528
|
+
type FlowAnswerDecision = {
|
|
3529
|
+
readonly kind: 'answer';
|
|
3530
|
+
readonly userAnswer: string;
|
|
3531
|
+
readonly value?: unknown;
|
|
3532
|
+
} | {
|
|
3533
|
+
readonly kind: 'jump';
|
|
3534
|
+
readonly target: string;
|
|
3535
|
+
} | {
|
|
3536
|
+
readonly kind: 'see-more';
|
|
3537
|
+
} | {
|
|
3538
|
+
readonly kind: 'invalid';
|
|
3539
|
+
readonly rejection?: FlowAnswerRejection;
|
|
3540
|
+
};
|
|
3541
|
+
type ResolveFlowAnswerParams = {
|
|
3542
|
+
readonly node: FlowNodeData;
|
|
3543
|
+
/** Texto, ou o id de botão/linha. `undefined` para mídia, localização e afins. */
|
|
3544
|
+
readonly answer: string | undefined;
|
|
3545
|
+
/** Veio de toque em botão/lista — o id é confiável e não passa por casamento de texto. */
|
|
3546
|
+
readonly isInteractiveReply: boolean;
|
|
3547
|
+
readonly context: Readonly<Record<string, unknown>>;
|
|
3548
|
+
readonly clock: FlowClock;
|
|
3549
|
+
/**
|
|
3550
|
+
* Opções do nó de escolha como o cliente as viu (`{{chave}}` já resolvido). Ausente, `node.options`
|
|
3551
|
+
* cru — o texto digitado casaria com o título ainda com a marcação.
|
|
3552
|
+
*/
|
|
3553
|
+
readonly options?: readonly (readonly [string, string])[];
|
|
3554
|
+
/** Opções exibidas na última página de um `dynamic_choice` (id, título), incluindo "ver mais". */
|
|
3555
|
+
readonly dynamicOptions?: readonly (readonly [string, string])[];
|
|
3556
|
+
};
|
|
3557
|
+
declare function isChoiceNode(node: FlowNodeData): boolean;
|
|
3558
|
+
declare function resolveFlowAnswer(params: ResolveFlowAnswerParams): FlowAnswerDecision;
|
|
3559
|
+
|
|
2906
3560
|
/**
|
|
2907
3561
|
* Porta de escrita no transcript, e não a classe `LogMessageUseCase`.
|
|
2908
3562
|
*
|
|
@@ -3031,4 +3685,4 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
|
|
|
3031
3685
|
}): Promise<void>;
|
|
3032
3686
|
}
|
|
3033
3687
|
|
|
3034
|
-
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_FALLBACK_LIST_LABEL, 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 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, 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 RequestHumanConversationParams, RequestHumanConversationUseCase, 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 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 };
|
|
3688
|
+
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 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 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 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, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
|