@adatechnology/meta-whatsapp-module 0.9.0 → 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.js CHANGED
@@ -10,7 +10,8 @@ var __dirname = /* @__PURE__ */ getDirname();
10
10
 
11
11
  // src/createMetaWhatsAppModule.ts
12
12
  import { WhatsAppMessageProvider } from "@adatechnology/meta-whatsapp-provider";
13
- import { FLOW_ACTION_KIND } from "@adatechnology/meta-whatsapp-contracts";
13
+ import { buildPreviewInboundPayload } from "@adatechnology/meta-whatsapp-contracts/testing";
14
+ import { ConfigMissingError as ConfigMissingError2, FLOW_ACTION_KIND } from "@adatechnology/meta-whatsapp-contracts";
14
15
 
15
16
  // src/repositories/SessionRepository.ts
16
17
  import { and, desc, eq, sql as sql2 } from "drizzle-orm";
@@ -399,6 +400,21 @@ var SessionRepository = class {
399
400
  updatedAt: sql2`now()`
400
401
  }).where(and(eq(sessions.companyId, companyId), eq(sessions.whatsappNumber, whatsappNumber)));
401
402
  }
403
+ /**
404
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
405
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
406
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
407
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
408
+ */
409
+ async saveFlowProgress(companyId, whatsappNumber, progress) {
410
+ await this.db.update(sessions).set({
411
+ flowKey: progress.flowKey,
412
+ currentNodeId: progress.currentNodeId,
413
+ context: progress.context,
414
+ lastActivity: sql2`now()`,
415
+ updatedAt: sql2`now()`
416
+ }).where(and(eq(sessions.companyId, companyId), eq(sessions.whatsappNumber, whatsappNumber)));
417
+ }
402
418
  // Marca a chegada de uma mensagem DO CLIENTE. É este carimbo — e não lastActivity, que também
403
419
  // se move em ações do atendente/bot — que define a janela de 24h do WhatsApp: fora dela, só
404
420
  // template aprovado reabre a conversa (ver WindowExpiredError nos contracts).
@@ -1282,13 +1298,6 @@ function toSessionContract(row) {
1282
1298
  };
1283
1299
  }
1284
1300
  __name(toSessionContract, "toSessionContract");
1285
- function extractAnswer(message) {
1286
- const interactive = message.interactive;
1287
- if (interactive?.button_reply) return interactive.button_reply.id;
1288
- if (interactive?.list_reply) return interactive.list_reply.id;
1289
- return message.text?.body;
1290
- }
1291
- __name(extractAnswer, "extractAnswer");
1292
1301
  var InboundEffectsDispatcher = class {
1293
1302
  static {
1294
1303
  __name(this, "InboundEffectsDispatcher");
@@ -1322,7 +1331,13 @@ var InboundEffectsDispatcher = class {
1322
1331
  profileName: job.profileName
1323
1332
  });
1324
1333
  if (outcome?.outcome === "handled") return;
1325
- void extractAnswer(message);
1334
+ await this.params.flowRunner?.handle({
1335
+ companyId,
1336
+ message,
1337
+ ...job.profileName === void 0 ? {} : {
1338
+ profileName: job.profileName
1339
+ }
1340
+ });
1326
1341
  }
1327
1342
  async runStatusEffects(job) {
1328
1343
  const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
@@ -1943,6 +1958,7 @@ var FlowInterpreter = class {
1943
1958
  return this.moveTo(input, resolveNext(node, branch));
1944
1959
  }
1945
1960
  if (node.type === "action") {
1961
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
1946
1962
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
1947
1963
  if (!handler) return {
1948
1964
  kind: "terminal",
@@ -1964,7 +1980,7 @@ var FlowInterpreter = class {
1964
1980
  context: contextAfterAction
1965
1981
  }, nextNodeId2);
1966
1982
  }
1967
- const isChoice = node.type === "menu" || node.questionType === "choice";
1983
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
1968
1984
  if (input.userAnswer === void 0) {
1969
1985
  return {
1970
1986
  kind: "awaiting-answer",
@@ -1972,9 +1988,10 @@ var FlowInterpreter = class {
1972
1988
  context: input.context
1973
1989
  };
1974
1990
  }
1991
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
1975
1992
  const updatedContext = node.contextKey ? {
1976
1993
  ...input.context,
1977
- [node.contextKey]: input.userAnswer
1994
+ [node.contextKey]: storedValue
1978
1995
  } : input.context;
1979
1996
  const answerId = isChoice ? input.userAnswer : void 0;
1980
1997
  const nextNodeId = resolveNext(node, answerId);
@@ -2017,6 +2034,8 @@ var FlowInterpreter = class {
2017
2034
  const visited = [
2018
2035
  input.currentNodeId
2019
2036
  ];
2037
+ const initialNode = input.graph.nodes[input.currentNodeId];
2038
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
2020
2039
  let current = input;
2021
2040
  let steps = 0;
2022
2041
  while (steps < maxSteps) {
@@ -2028,11 +2047,14 @@ var FlowInterpreter = class {
2028
2047
  steps
2029
2048
  };
2030
2049
  visited.push(result.nodeId);
2050
+ const enteredNode = current.graph.nodes[result.nodeId];
2051
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
2031
2052
  current = {
2032
2053
  ...current,
2033
2054
  currentNodeId: result.nodeId,
2034
2055
  context: result.context,
2035
- userAnswer: void 0
2056
+ userAnswer: void 0,
2057
+ answerValue: void 0
2036
2058
  };
2037
2059
  }
2038
2060
  return {
@@ -2044,6 +2066,962 @@ var FlowInterpreter = class {
2044
2066
  }
2045
2067
  };
2046
2068
 
2069
+ // src/flows/FlowRunner.ts
2070
+ import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2, matchesFlowKeyword } from "@adatechnology/meta-whatsapp-contracts";
2071
+
2072
+ // src/flows/resolveFlowAnswer.ts
2073
+ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@adatechnology/meta-whatsapp-contracts";
2074
+
2075
+ // src/flows/flowRunner.constant.ts
2076
+ var DEFAULT_START_FLOW_KEY = "main";
2077
+ var DEFAULT_MAX_INVALID_ANSWERS = 2;
2078
+ var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2079
+ var DEFAULT_FLOW_TEXT = {
2080
+ FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2081
+ CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
2082
+ LIST_BUTTON_LABEL: "Ver op\xE7\xF5es",
2083
+ SEE_MORE: "Ver mais",
2084
+ NON_TEXT_ANSWER: "Por aqui eu entendo s\xF3 texto. Pode escrever a resposta?",
2085
+ MORE_OPTIONS_TRUNCATED: "\u2026",
2086
+ HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.",
2087
+ HANDOFF_OUT_OF_HOURS: "Nossa equipe est\xE1 fora do hor\xE1rio agora. Sua mensagem ficou registrada e respondemos assim que voltarmos."
2088
+ };
2089
+ var DYNAMIC_CHOICE_MORE_ID = "__more__";
2090
+ var FLOW_RUNTIME_CONTEXT_KEY = "__flow";
2091
+
2092
+ // src/flows/resolveFlowAnswer.ts
2093
+ function isChoiceNode(node) {
2094
+ return node.type === "menu" || node.questionType === "choice";
2095
+ }
2096
+ __name(isChoiceNode, "isChoiceNode");
2097
+ function keywordRoute(node, answer, isInteractiveReply) {
2098
+ if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
2099
+ return matchFlowKeywordRoute(answer, node.next.byKeyword);
2100
+ }
2101
+ __name(keywordRoute, "keywordRoute");
2102
+ function matchOption(answer, options, isInteractiveReply) {
2103
+ if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
2104
+ return matchFlowChoice(answer, options);
2105
+ }
2106
+ __name(matchOption, "matchOption");
2107
+ function resolveChoice(params, answer) {
2108
+ const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
2109
+ if (optionId) return {
2110
+ kind: "answer",
2111
+ userAnswer: optionId
2112
+ };
2113
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2114
+ return target ? {
2115
+ kind: "jump",
2116
+ target
2117
+ } : {
2118
+ kind: "invalid"
2119
+ };
2120
+ }
2121
+ __name(resolveChoice, "resolveChoice");
2122
+ function resolveDynamicChoice(params, answer) {
2123
+ const optionId = matchOption(answer, params.dynamicOptions ?? [], params.isInteractiveReply);
2124
+ if (optionId === DYNAMIC_CHOICE_MORE_ID) return {
2125
+ kind: "see-more"
2126
+ };
2127
+ if (optionId) return {
2128
+ kind: "answer",
2129
+ userAnswer: optionId
2130
+ };
2131
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2132
+ return target ? {
2133
+ kind: "jump",
2134
+ target
2135
+ } : {
2136
+ kind: "invalid"
2137
+ };
2138
+ }
2139
+ __name(resolveDynamicChoice, "resolveDynamicChoice");
2140
+ function resolveQuestion(params, answer) {
2141
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2142
+ if (target) return {
2143
+ kind: "jump",
2144
+ target
2145
+ };
2146
+ const result = validateFlowAnswer({
2147
+ node: params.node,
2148
+ answer,
2149
+ context: params.context,
2150
+ clock: params.clock
2151
+ });
2152
+ if (!result.isValid) return {
2153
+ kind: "invalid",
2154
+ rejection: result.rejection
2155
+ };
2156
+ return {
2157
+ kind: "answer",
2158
+ userAnswer: answer,
2159
+ value: result.value
2160
+ };
2161
+ }
2162
+ __name(resolveQuestion, "resolveQuestion");
2163
+ function resolveFlowAnswer(params) {
2164
+ if (params.answer === void 0) return {
2165
+ kind: "invalid"
2166
+ };
2167
+ if (params.node.type === "dynamic_choice") return resolveDynamicChoice(params, params.answer);
2168
+ if (isChoiceNode(params.node)) return resolveChoice(params, params.answer);
2169
+ return resolveQuestion(params, params.answer);
2170
+ }
2171
+ __name(resolveFlowAnswer, "resolveFlowAnswer");
2172
+
2173
+ // src/flows/FlowQuestionRenderer.ts
2174
+ import { FlowRunnerError, WHATSAPP_CHOICE_LIMIT as WHATSAPP_CHOICE_LIMIT2, interpolateFlowText } from "@adatechnology/meta-whatsapp-contracts";
2175
+
2176
+ // src/flows/buildFlowChoiceMessage.ts
2177
+ import { WHATSAPP_CHOICE_LIMIT, listInteractiveLimitViolations } from "@adatechnology/meta-whatsapp-contracts";
2178
+ function groupSections(options) {
2179
+ const sections = [];
2180
+ for (const option of options) {
2181
+ const title = option.section?.trim() || void 0;
2182
+ const existing = sections.find((section) => section.title === title);
2183
+ if (existing) existing.rows.push(option);
2184
+ else sections.push({
2185
+ title,
2186
+ rows: [
2187
+ option
2188
+ ]
2189
+ });
2190
+ }
2191
+ return sections.map((section) => ({
2192
+ ...section.title ? {
2193
+ title: section.title
2194
+ } : {},
2195
+ rows: section.rows.map((row) => ({
2196
+ id: row.id,
2197
+ title: row.title,
2198
+ ...row.description ? {
2199
+ description: row.description
2200
+ } : {}
2201
+ }))
2202
+ }));
2203
+ }
2204
+ __name(groupSections, "groupSections");
2205
+ function asNumberedText(params) {
2206
+ const lines = params.options.map((option, index2) => {
2207
+ const description = option.description ? ` \u2014 ${option.description}` : "";
2208
+ return `${index2 + 1}. ${option.title}${description}`;
2209
+ });
2210
+ const limit = WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
2211
+ const full = `${params.body}
2212
+
2213
+ ${lines.join("\n")}`;
2214
+ if (Array.from(full).length <= limit) return {
2215
+ kind: "text",
2216
+ body: full
2217
+ };
2218
+ const truncated = `
2219
+ ${DEFAULT_FLOW_TEXT.MORE_OPTIONS_TRUNCATED}`;
2220
+ let body = `${params.body}
2221
+ `;
2222
+ for (const line of lines) {
2223
+ const candidate = `${body}
2224
+ ${line}`;
2225
+ if (Array.from(candidate).length + truncated.length > limit) break;
2226
+ body = candidate;
2227
+ }
2228
+ const withMarker = `${body}${truncated}`;
2229
+ return {
2230
+ kind: "text",
2231
+ body: Array.from(withMarker).slice(0, limit).join("")
2232
+ };
2233
+ }
2234
+ __name(asNumberedText, "asNumberedText");
2235
+ function buildFlowChoiceMessage(params) {
2236
+ const isPlain = params.options.every((option) => !option.description && !option.section);
2237
+ if (isPlain && params.options.length <= WHATSAPP_CHOICE_LIMIT.BUTTONS) {
2238
+ const buttons = {
2239
+ kind: "buttons",
2240
+ body: params.body,
2241
+ buttons: params.options.map((option) => ({
2242
+ id: option.id,
2243
+ title: option.title
2244
+ }))
2245
+ };
2246
+ if (listInteractiveLimitViolations(buttons).length === 0) return {
2247
+ kind: "interactive",
2248
+ interactive: buttons
2249
+ };
2250
+ }
2251
+ const list = {
2252
+ kind: "list",
2253
+ body: params.body,
2254
+ buttonLabel: params.listButtonLabel,
2255
+ sections: groupSections(params.options)
2256
+ };
2257
+ if (listInteractiveLimitViolations(list).length === 0) return {
2258
+ kind: "interactive",
2259
+ interactive: list
2260
+ };
2261
+ return asNumberedText(params);
2262
+ }
2263
+ __name(buildFlowChoiceMessage, "buildFlowChoiceMessage");
2264
+
2265
+ // src/flows/flowRuntimeState.ts
2266
+ function runtimeOf(context) {
2267
+ const state = context[FLOW_RUNTIME_CONTEXT_KEY];
2268
+ return state !== null && typeof state === "object" ? state : {};
2269
+ }
2270
+ __name(runtimeOf, "runtimeOf");
2271
+ function withRuntime(context, state) {
2272
+ return {
2273
+ ...context,
2274
+ [FLOW_RUNTIME_CONTEXT_KEY]: state
2275
+ };
2276
+ }
2277
+ __name(withRuntime, "withRuntime");
2278
+
2279
+ // src/flows/FlowQuestionRenderer.ts
2280
+ var FlowQuestionRenderer = class {
2281
+ static {
2282
+ __name(this, "FlowQuestionRenderer");
2283
+ }
2284
+ config;
2285
+ providers = /* @__PURE__ */ new Map();
2286
+ constructor(config) {
2287
+ this.config = config;
2288
+ for (const [key, provider] of Object.entries(config.dynamicChoiceProviders ?? {})) this.providers.set(key, provider);
2289
+ }
2290
+ registerDynamicChoiceProvider(key, provider) {
2291
+ this.providers.set(key, provider);
2292
+ }
2293
+ interpolate(text2, variables) {
2294
+ return interpolateFlowText(text2, variables, this.config.formatValue ? {
2295
+ formatValue: this.config.formatValue
2296
+ } : {});
2297
+ }
2298
+ async prepare(params) {
2299
+ const { node, context } = params;
2300
+ const variables = {
2301
+ ...context,
2302
+ ...params.variables
2303
+ };
2304
+ const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2305
+ const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2306
+ if (node.type === "dynamic_choice") {
2307
+ const options = await this.loadDynamicOptions(params);
2308
+ const shown = options.map((option) => [
2309
+ option.id,
2310
+ option.title
2311
+ ]);
2312
+ const state = {
2313
+ ...runtimeOf(context),
2314
+ dynamic: {
2315
+ nodeId: node.id,
2316
+ page: params.page,
2317
+ options: shown
2318
+ }
2319
+ };
2320
+ return {
2321
+ message: buildFlowChoiceMessage({
2322
+ body,
2323
+ options,
2324
+ listButtonLabel
2325
+ }),
2326
+ context: withRuntime(context, state)
2327
+ };
2328
+ }
2329
+ if (isChoiceNode(node) && (node.options?.length ?? 0) > 0) {
2330
+ const options = (node.options ?? []).map(([id, title]) => {
2331
+ const detail = node.optionDetails?.[id];
2332
+ return {
2333
+ id,
2334
+ title: this.interpolate(title, variables),
2335
+ ...detail?.description ? {
2336
+ description: this.interpolate(detail.description, variables)
2337
+ } : {},
2338
+ ...detail?.section ? {
2339
+ section: detail.section
2340
+ } : {}
2341
+ };
2342
+ });
2343
+ return {
2344
+ message: buildFlowChoiceMessage({
2345
+ body,
2346
+ options,
2347
+ listButtonLabel
2348
+ }),
2349
+ context
2350
+ };
2351
+ }
2352
+ if (!node.question) return {
2353
+ context
2354
+ };
2355
+ return {
2356
+ message: {
2357
+ kind: "text",
2358
+ body
2359
+ },
2360
+ context
2361
+ };
2362
+ }
2363
+ async loadDynamicOptions(params) {
2364
+ const { node } = params;
2365
+ const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
2366
+ if (!provider) throw new FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
2367
+ const pageSize = WHATSAPP_CHOICE_LIMIT2.LIST_ROWS - 1;
2368
+ const result = await provider({
2369
+ node,
2370
+ session: params.session,
2371
+ context: params.context,
2372
+ page: params.page,
2373
+ pageSize
2374
+ });
2375
+ const options = result.options.slice(0, pageSize).map((option) => ({
2376
+ id: option.id,
2377
+ title: option.title,
2378
+ ...option.description ? {
2379
+ description: option.description
2380
+ } : {}
2381
+ }));
2382
+ const seeMore = this.config.seeMoreLabel ?? DEFAULT_FLOW_TEXT.SEE_MORE;
2383
+ return result.hasMore ? [
2384
+ ...options,
2385
+ {
2386
+ id: DYNAMIC_CHOICE_MORE_ID,
2387
+ title: seeMore
2388
+ }
2389
+ ] : options;
2390
+ }
2391
+ };
2392
+
2393
+ // src/flows/readFlowInbound.ts
2394
+ function readFlowInbound(message) {
2395
+ const reply = message.interactive?.button_reply?.id ?? message.interactive?.list_reply?.id;
2396
+ if (reply !== void 0) return {
2397
+ kind: "reply",
2398
+ answer: reply
2399
+ };
2400
+ if (message.text?.body !== void 0) return {
2401
+ kind: "text",
2402
+ answer: message.text.body
2403
+ };
2404
+ if (message.button?.text !== void 0) return {
2405
+ kind: "text",
2406
+ answer: message.button.text
2407
+ };
2408
+ return {
2409
+ kind: "unsupported"
2410
+ };
2411
+ }
2412
+ __name(readFlowInbound, "readFlowInbound");
2413
+
2414
+ // src/flows/FlowRunner.ts
2415
+ function contactVariables(profileName) {
2416
+ if (!profileName) return {};
2417
+ return {
2418
+ contactName: profileName,
2419
+ contactFirstName: profileName.trim().split(/\s+/)[0] ?? profileName
2420
+ };
2421
+ }
2422
+ __name(contactVariables, "contactVariables");
2423
+ function resolveFlowTimeZone(config) {
2424
+ const businessHours = config.handoff?.businessHours;
2425
+ const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
2426
+ if (!timeZone) throw new ConfigMissingError("features.flowRunner.timeZone");
2427
+ new Intl.DateTimeFormat("en-US", {
2428
+ timeZone
2429
+ });
2430
+ return timeZone;
2431
+ }
2432
+ __name(resolveFlowTimeZone, "resolveFlowTimeZone");
2433
+ var FlowRunner = class {
2434
+ static {
2435
+ __name(this, "FlowRunner");
2436
+ }
2437
+ dependencies;
2438
+ renderer;
2439
+ timeZone;
2440
+ // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2441
+ // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2442
+ turnVariables = /* @__PURE__ */ new WeakMap();
2443
+ constructor(dependencies) {
2444
+ this.dependencies = dependencies;
2445
+ this.renderer = new FlowQuestionRenderer(dependencies.config);
2446
+ this.timeZone = resolveFlowTimeZone(dependencies.config);
2447
+ }
2448
+ registerDynamicChoiceProvider(key, provider) {
2449
+ this.renderer.registerDynamicChoiceProvider(key, provider);
2450
+ }
2451
+ /**
2452
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2453
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2454
+ * o sistema conhece pelo que o cliente digitou.
2455
+ */
2456
+ variablesFor(params) {
2457
+ return {
2458
+ ...params.context,
2459
+ ...this.turnVariables.get(params.session) ?? {}
2460
+ };
2461
+ }
2462
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2463
+ handle(params) {
2464
+ const key = {
2465
+ companyId: params.companyId,
2466
+ whatsappNumber: params.message.from
2467
+ };
2468
+ return this.dependencies.lock.withLock(key, () => this.handleLocked(params));
2469
+ }
2470
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2471
+ start(params) {
2472
+ const key = {
2473
+ companyId: params.companyId,
2474
+ whatsappNumber: params.whatsappNumber
2475
+ };
2476
+ return this.dependencies.lock.withLock(key, async () => {
2477
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.whatsappNumber);
2478
+ if (!row) return "no-session";
2479
+ const turn = await this.openTurn({
2480
+ companyId: params.companyId,
2481
+ session: toSessionContract(row),
2482
+ ...params.profileName ? {
2483
+ profileName: params.profileName
2484
+ } : {}
2485
+ });
2486
+ const graph = await this.loadGraph(params.companyId, params.flowKey ?? this.startFlowKey());
2487
+ if (!graph) return "no-flow";
2488
+ turn.isClaimed = true;
2489
+ return this.guard(turn, async () => {
2490
+ await this.runFrom(turn, {
2491
+ graph,
2492
+ nodeId: graph.startNodeId,
2493
+ context: {
2494
+ ...turn.session.context
2495
+ },
2496
+ enterInitialNode: true
2497
+ });
2498
+ return "handled";
2499
+ });
2500
+ });
2501
+ }
2502
+ async handleLocked(params) {
2503
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.message.from);
2504
+ if (!row) return "no-session";
2505
+ if (row.mode === "human") return "human-mode";
2506
+ const session = toSessionContract(row);
2507
+ if (runtimeOf(session.context).lastInboundId === params.message.id) return "duplicate";
2508
+ const turn = await this.openTurn({
2509
+ companyId: params.companyId,
2510
+ session,
2511
+ inboundId: params.message.id,
2512
+ ...params.profileName ? {
2513
+ profileName: params.profileName
2514
+ } : {}
2515
+ });
2516
+ return this.guard(turn, () => this.route(turn, readFlowInbound(params.message)));
2517
+ }
2518
+ async route(turn, inbound) {
2519
+ const globalTarget = inbound.kind === "text" ? this.globalKeywordTarget(inbound.answer) : void 0;
2520
+ if (globalTarget) return this.applyGlobalTarget(turn, globalTarget);
2521
+ const whileAwaitingHuman = this.dependencies.config.whileAwaitingHuman ?? "silent";
2522
+ if (turn.session.humanRequestedAt && !turn.session.currentNodeId && whileAwaitingHuman === "silent") {
2523
+ return "awaiting-human";
2524
+ }
2525
+ const savedFlowKey = turn.session.flowKey;
2526
+ const savedGraph = await this.loadGraph(turn.companyId, savedFlowKey ?? this.startFlowKey());
2527
+ const isStale = !savedGraph && savedFlowKey !== null && savedFlowKey !== this.startFlowKey();
2528
+ const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
2529
+ if (!graph) return "no-flow";
2530
+ await this.claim(turn);
2531
+ if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new FlowRunnerError2("flow-not-found", savedFlowKey));
2532
+ const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
2533
+ const context = {
2534
+ ...turn.session.context
2535
+ };
2536
+ if (node) {
2537
+ await this.answerNode({
2538
+ turn,
2539
+ graph,
2540
+ node,
2541
+ context,
2542
+ inbound
2543
+ });
2544
+ return "handled";
2545
+ }
2546
+ const start = graph.nodes[graph.startNodeId];
2547
+ const target = start && inbound.kind !== "unsupported" ? this.keywordJumpAtStart(start, inbound) : void 0;
2548
+ if (target) await this.jumpTo(turn, graph, target, context);
2549
+ else await this.runFrom(turn, {
2550
+ graph,
2551
+ nodeId: graph.startNodeId,
2552
+ context,
2553
+ enterInitialNode: true
2554
+ });
2555
+ return "handled";
2556
+ }
2557
+ async guard(turn, work) {
2558
+ try {
2559
+ return await work();
2560
+ } catch (error) {
2561
+ if (!turn.isClaimed) throw error;
2562
+ await this.report(turn, turn.session.flowKey, turn.session.currentNodeId, "turn", error);
2563
+ return "handled";
2564
+ }
2565
+ }
2566
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2567
+ async claim(turn) {
2568
+ if (turn.isClaimed) return;
2569
+ await this.save(turn, {
2570
+ flowKey: turn.session.flowKey,
2571
+ nodeId: turn.session.currentNodeId,
2572
+ context: {
2573
+ ...turn.session.context
2574
+ }
2575
+ });
2576
+ turn.isClaimed = true;
2577
+ }
2578
+ async openTurn(params) {
2579
+ const { session, profileName } = params;
2580
+ const resolver = this.dependencies.config.resolveVariables;
2581
+ const hostVariables = resolver ? await resolver({
2582
+ session,
2583
+ ...profileName ? {
2584
+ profileName
2585
+ } : {}
2586
+ }) : {};
2587
+ const baseVariables = {
2588
+ ...contactVariables(profileName),
2589
+ ...hostVariables
2590
+ };
2591
+ this.turnVariables.set(session, baseVariables);
2592
+ return {
2593
+ companyId: params.companyId,
2594
+ session,
2595
+ baseVariables,
2596
+ ...params.inboundId ? {
2597
+ inboundId: params.inboundId
2598
+ } : {},
2599
+ isClaimed: false
2600
+ };
2601
+ }
2602
+ startFlowKey() {
2603
+ return this.dependencies.config.startFlowKey ?? DEFAULT_START_FLOW_KEY;
2604
+ }
2605
+ clock() {
2606
+ const { config } = this.dependencies;
2607
+ return {
2608
+ now: config.now?.() ?? /* @__PURE__ */ new Date(),
2609
+ locale: config.dateLocale ?? FLOW_DATE_LOCALE_PT_BR,
2610
+ timeZone: this.timeZone
2611
+ };
2612
+ }
2613
+ loadGraph(companyId, flowKey) {
2614
+ return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2615
+ }
2616
+ globalKeywordTarget(answer) {
2617
+ const keywords = this.dependencies.config.globalKeywords ?? [];
2618
+ return keywords.find((entry) => matchesFlowKeyword(answer, entry.keywords))?.target;
2619
+ }
2620
+ keywordJumpAtStart(start, inbound) {
2621
+ if (inbound.kind === "unsupported") return void 0;
2622
+ const decision = resolveFlowAnswer({
2623
+ node: start,
2624
+ answer: inbound.answer,
2625
+ isInteractiveReply: inbound.kind === "reply",
2626
+ context: {},
2627
+ clock: this.clock()
2628
+ });
2629
+ return decision.kind === "jump" ? decision.target : void 0;
2630
+ }
2631
+ /**
2632
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2633
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2634
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2635
+ */
2636
+ async applyGlobalTarget(turn, target) {
2637
+ const context = withRuntime({
2638
+ ...turn.session.context
2639
+ }, {});
2640
+ if (target === "handoff") {
2641
+ await this.claim(turn);
2642
+ await this.handOff(turn, context);
2643
+ return "handled";
2644
+ }
2645
+ const flowKey = target === "restart" ? this.startFlowKey() : crossFlowKey2(target);
2646
+ const graph = await this.loadGraph(turn.companyId, flowKey);
2647
+ if (!graph) return "no-flow";
2648
+ await this.claim(turn);
2649
+ await this.runFrom(turn, {
2650
+ graph,
2651
+ nodeId: graph.startNodeId,
2652
+ context,
2653
+ enterInitialNode: true
2654
+ });
2655
+ return "handled";
2656
+ }
2657
+ async answerNode(params) {
2658
+ const { turn, graph, node, context, inbound } = params;
2659
+ const runtime = runtimeOf(context);
2660
+ const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2661
+ const page = dynamic?.page ?? 0;
2662
+ if (inbound.kind === "unsupported") {
2663
+ const text2 = this.dependencies.config.nonTextAnswerMessage ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER;
2664
+ await this.say(turn, text2, context);
2665
+ return this.awaitAnswer(turn, graph, node, context, page);
2666
+ }
2667
+ const decision = resolveFlowAnswer({
2668
+ node,
2669
+ answer: inbound.answer,
2670
+ isInteractiveReply: inbound.kind === "reply",
2671
+ context,
2672
+ clock: this.clock(),
2673
+ ...dynamic ? {
2674
+ dynamicOptions: dynamic.options
2675
+ } : {}
2676
+ });
2677
+ if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
2678
+ if (decision.kind === "see-more") return this.awaitAnswer(turn, graph, node, context, page + 1);
2679
+ if (decision.kind === "invalid" && this.followsDefaultWhenUnmatched(node)) {
2680
+ return this.runFrom(turn, {
2681
+ graph,
2682
+ nodeId: node.id,
2683
+ context: withRuntime(context, {}),
2684
+ userAnswer: inbound.answer,
2685
+ enterInitialNode: false
2686
+ });
2687
+ }
2688
+ if (decision.kind === "invalid") return this.handleInvalid(turn, graph, node, context, decision.rejection);
2689
+ await this.runFrom(turn, {
2690
+ graph,
2691
+ nodeId: node.id,
2692
+ context: withRuntime(context, {}),
2693
+ userAnswer: decision.userAnswer,
2694
+ ...decision.value !== void 0 ? {
2695
+ answerValue: decision.value
2696
+ } : {},
2697
+ enterInitialNode: false
2698
+ });
2699
+ }
2700
+ followsDefaultWhenUnmatched(node) {
2701
+ if (!isChoiceNode(node)) return false;
2702
+ return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2703
+ }
2704
+ async handleInvalid(turn, graph, node, context, rejection) {
2705
+ const runtime = runtimeOf(context);
2706
+ const attempts = (runtime.invalidAnswers ?? 0) + 1;
2707
+ const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
2708
+ if (attempts >= limit) return this.handOff(turn, withRuntime(context, {}));
2709
+ const updated = withRuntime(context, {
2710
+ ...runtime,
2711
+ invalidAnswers: attempts
2712
+ });
2713
+ await this.say(turn, this.fallbackText(node, rejection), updated);
2714
+ await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2715
+ }
2716
+ fallbackText(node, rejection) {
2717
+ const { config } = this.dependencies;
2718
+ return node.fallbackMessage ?? (rejection ? config.rejectionMessages?.[rejection] : void 0) ?? config.defaultFallbackMessage ?? DEFAULT_FLOW_TEXT.FALLBACK;
2719
+ }
2720
+ async handOff(turn, context) {
2721
+ const isWithinHours = await this.dependencies.handoff.request({
2722
+ companyId: turn.companyId,
2723
+ whatsappNumber: turn.session.whatsappNumber,
2724
+ variables: {
2725
+ ...context,
2726
+ ...turn.baseVariables
2727
+ }
2728
+ });
2729
+ await this.save(turn, {
2730
+ flowKey: null,
2731
+ nodeId: null,
2732
+ context: {
2733
+ ...context,
2734
+ handoffWithinBusinessHours: isWithinHours
2735
+ }
2736
+ });
2737
+ }
2738
+ async jumpTo(turn, graph, target, context) {
2739
+ if (isCrossFlowTarget2(target)) {
2740
+ const targetGraph = await this.loadGraph(turn.companyId, crossFlowKey2(target));
2741
+ if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
2742
+ return this.runFrom(turn, {
2743
+ graph: targetGraph,
2744
+ nodeId: targetGraph.startNodeId,
2745
+ context,
2746
+ enterInitialNode: true
2747
+ });
2748
+ }
2749
+ return this.runFrom(turn, {
2750
+ graph,
2751
+ nodeId: target,
2752
+ context,
2753
+ enterInitialNode: true
2754
+ });
2755
+ }
2756
+ async runFrom(turn, initial) {
2757
+ const maxJumps = this.dependencies.config.maxCrossFlowJumps ?? DEFAULT_MAX_CROSS_FLOW_JUMPS;
2758
+ let params = initial;
2759
+ for (let jump = 0; jump <= maxJumps; jump++) {
2760
+ const result = await this.dependencies.interpreter.run({
2761
+ graph: params.graph,
2762
+ currentNodeId: params.nodeId,
2763
+ ...params.userAnswer !== void 0 ? {
2764
+ userAnswer: params.userAnswer
2765
+ } : {},
2766
+ ...params.answerValue !== void 0 ? {
2767
+ answerValue: params.answerValue
2768
+ } : {},
2769
+ context: params.context,
2770
+ session: turn.session,
2771
+ channel: this.dependencies.channel
2772
+ }, {
2773
+ enterInitialNode: params.enterInitialNode,
2774
+ onNodeEntered: /* @__PURE__ */ __name(async (node, context) => {
2775
+ if (node.directMessage) await this.say(turn, node.directMessage, context);
2776
+ }, "onNodeEntered")
2777
+ });
2778
+ if (result.kind === "awaiting-answer") {
2779
+ const node = params.graph.nodes[result.nodeId];
2780
+ if (node) return this.awaitAnswer(turn, params.graph, node, result.context, 0);
2781
+ return this.save(turn, {
2782
+ flowKey: null,
2783
+ nodeId: null,
2784
+ context: result.context
2785
+ });
2786
+ }
2787
+ if (result.kind === "terminal") return this.save(turn, {
2788
+ flowKey: null,
2789
+ nodeId: null,
2790
+ context: result.context
2791
+ });
2792
+ if (result.kind === "max-steps-exceeded") {
2793
+ await this.save(turn, {
2794
+ flowKey: null,
2795
+ nodeId: null,
2796
+ context: result.context
2797
+ });
2798
+ return this.report(turn, params.graph.key, null, "max-steps", new FlowRunnerError2("cycle", result.visited.join(" -> ")));
2799
+ }
2800
+ const target = await this.loadGraph(turn.companyId, result.flowKey);
2801
+ if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
2802
+ params = {
2803
+ graph: target,
2804
+ nodeId: target.startNodeId,
2805
+ context: result.context,
2806
+ enterInitialNode: true
2807
+ };
2808
+ }
2809
+ await this.save(turn, {
2810
+ flowKey: null,
2811
+ nodeId: null,
2812
+ context: params.context
2813
+ });
2814
+ return this.report(turn, params.graph.key, null, "cross-flow", new FlowRunnerError2("too-many-jumps", params.graph.key));
2815
+ }
2816
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2817
+ async awaitAnswer(turn, graph, node, context, page) {
2818
+ try {
2819
+ const { message, context: renderedContext } = await this.renderer.prepare({
2820
+ session: turn.session,
2821
+ variables: turn.baseVariables,
2822
+ node,
2823
+ context,
2824
+ page
2825
+ });
2826
+ await this.save(turn, {
2827
+ flowKey: graph.key,
2828
+ nodeId: node.id,
2829
+ context: renderedContext
2830
+ });
2831
+ if (message) await this.send(turn, message);
2832
+ } catch (error) {
2833
+ await this.report(turn, graph.key, node.id, "render", error);
2834
+ }
2835
+ }
2836
+ async say(turn, template, context) {
2837
+ const body = this.renderer.interpolate(template, {
2838
+ ...context,
2839
+ ...turn.baseVariables
2840
+ });
2841
+ if (body.trim().length > 0) await this.send(turn, {
2842
+ kind: "text",
2843
+ body
2844
+ });
2845
+ }
2846
+ async send(turn, message) {
2847
+ const common = {
2848
+ companyId: turn.companyId,
2849
+ whatsappNumber: turn.session.whatsappNumber,
2850
+ sender: "bot",
2851
+ startState: this.dependencies.startState
2852
+ };
2853
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
2854
+ ...common,
2855
+ body: message.body
2856
+ });
2857
+ else await this.dependencies.sendMessage.sendInteractive({
2858
+ ...common,
2859
+ interactive: message.interactive
2860
+ });
2861
+ }
2862
+ save(turn, progress) {
2863
+ const runtime = runtimeOf(progress.context);
2864
+ const context = turn.inboundId ? withRuntime(progress.context, {
2865
+ ...runtime,
2866
+ lastInboundId: turn.inboundId
2867
+ }) : progress.context;
2868
+ return this.dependencies.sessionRepository.saveFlowProgress(turn.companyId, turn.session.whatsappNumber, {
2869
+ flowKey: progress.flowKey,
2870
+ currentNodeId: progress.nodeId,
2871
+ context
2872
+ });
2873
+ }
2874
+ async reportMissingFlow(turn, fromFlowKey, target, context) {
2875
+ await this.save(turn, {
2876
+ flowKey: null,
2877
+ nodeId: null,
2878
+ context
2879
+ });
2880
+ await this.report(turn, fromFlowKey, null, "cross-flow", new FlowRunnerError2("flow-not-found", target));
2881
+ }
2882
+ /**
2883
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
2884
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
2885
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
2886
+ */
2887
+ async report(turn, flowKey, nodeId, stage, error) {
2888
+ const details = {
2889
+ companyId: turn.companyId,
2890
+ whatsappNumber: turn.session.whatsappNumber,
2891
+ flowKey,
2892
+ nodeId,
2893
+ stage
2894
+ };
2895
+ try {
2896
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
2897
+ } catch {
2898
+ }
2899
+ }
2900
+ };
2901
+
2902
+ // src/flows/FlowHandoff.ts
2903
+ import { interpolateFlowText as interpolateFlowText2, isWithinBusinessHours } from "@adatechnology/meta-whatsapp-contracts";
2904
+ function readParam(node, key) {
2905
+ const value = node?.actionParams?.[key];
2906
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
2907
+ }
2908
+ __name(readParam, "readParam");
2909
+ var FlowHandoff = class {
2910
+ static {
2911
+ __name(this, "FlowHandoff");
2912
+ }
2913
+ dependencies;
2914
+ constructor(dependencies) {
2915
+ this.dependencies = dependencies;
2916
+ }
2917
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
2918
+ async request(params) {
2919
+ const { requestHuman, sendMessage, startState, interpolation } = this.dependencies;
2920
+ try {
2921
+ await requestHuman.execute({
2922
+ companyId: params.companyId,
2923
+ whatsappNumber: params.whatsappNumber
2924
+ });
2925
+ } catch (error) {
2926
+ await this.reportFailure(error, params);
2927
+ }
2928
+ const isWithinHours = await this.isWithinHours(params.companyId);
2929
+ const template = this.messageFor(isWithinHours, params.node);
2930
+ await sendMessage.sendText({
2931
+ companyId: params.companyId,
2932
+ whatsappNumber: params.whatsappNumber,
2933
+ body: interpolateFlowText2(template, params.variables, interpolation),
2934
+ sender: "bot",
2935
+ startState
2936
+ });
2937
+ return isWithinHours;
2938
+ }
2939
+ /**
2940
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
2941
+ * sobrescrevem os textos do runner para aquele nó.
2942
+ */
2943
+ createActionHandler(resolveVariables) {
2944
+ return async ({ node, session, context }) => {
2945
+ const isWithinHours = await this.request({
2946
+ companyId: session.companyId,
2947
+ whatsappNumber: session.whatsappNumber,
2948
+ variables: resolveVariables({
2949
+ session,
2950
+ context
2951
+ }),
2952
+ node
2953
+ });
2954
+ return {
2955
+ context: {
2956
+ handoffWithinBusinessHours: isWithinHours
2957
+ }
2958
+ };
2959
+ };
2960
+ }
2961
+ async reportFailure(error, params) {
2962
+ try {
2963
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, {
2964
+ companyId: params.companyId,
2965
+ whatsappNumber: params.whatsappNumber,
2966
+ flowKey: null,
2967
+ nodeId: params.node?.id ?? null,
2968
+ stage: "handoff"
2969
+ });
2970
+ } catch {
2971
+ }
2972
+ }
2973
+ async isWithinHours(companyId) {
2974
+ const source = this.dependencies.config.businessHours;
2975
+ const hours = typeof source === "function" ? await source(companyId) : source;
2976
+ return hours ? isWithinBusinessHours(hours, this.dependencies.now()) : true;
2977
+ }
2978
+ messageFor(isWithinHours, node) {
2979
+ const { config } = this.dependencies;
2980
+ const inHours = readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF;
2981
+ if (isWithinHours) return inHours;
2982
+ return readParam(node, "outOfHoursMessage") ?? config.outOfHoursMessage ?? readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS;
2983
+ }
2984
+ };
2985
+
2986
+ // src/flows/flowTurnLock.ts
2987
+ import { sql as sql5 } from "drizzle-orm";
2988
+ function lockName(key) {
2989
+ return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
2990
+ }
2991
+ __name(lockName, "lockName");
2992
+ var PostgresAdvisoryFlowTurnLock = class {
2993
+ static {
2994
+ __name(this, "PostgresAdvisoryFlowTurnLock");
2995
+ }
2996
+ db;
2997
+ constructor(db) {
2998
+ this.db = db;
2999
+ }
3000
+ withLock(key, work) {
3001
+ return this.db.transaction(async (transaction) => {
3002
+ await transaction.execute(sql5`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3003
+ return work();
3004
+ });
3005
+ }
3006
+ };
3007
+ var InProcessFlowTurnLock = class {
3008
+ static {
3009
+ __name(this, "InProcessFlowTurnLock");
3010
+ }
3011
+ tails = /* @__PURE__ */ new Map();
3012
+ async withLock(key, work) {
3013
+ const name = lockName(key);
3014
+ const previous = this.tails.get(name) ?? Promise.resolve();
3015
+ const current = previous.catch(() => void 0).then(work);
3016
+ this.tails.set(name, current);
3017
+ try {
3018
+ return await current;
3019
+ } finally {
3020
+ if (this.tails.get(name) === current) this.tails.delete(name);
3021
+ }
3022
+ }
3023
+ };
3024
+
2047
3025
  // src/flows/createSendMediaAction.ts
2048
3026
  function mediaTypeFor2(mimeType) {
2049
3027
  if (mimeType.startsWith("image/")) return "image";
@@ -2209,7 +3187,7 @@ async function listAvailableProducts(params) {
2209
3187
  __name(listAvailableProducts, "listAvailableProducts");
2210
3188
 
2211
3189
  // src/repositories/FlowMediaRepository.ts
2212
- import { and as and5, asc as asc2, eq as eq6, sql as sql5 } from "drizzle-orm";
3190
+ import { and as and5, asc as asc2, eq as eq6, sql as sql6 } from "drizzle-orm";
2213
3191
  var FlowMediaRepository = class {
2214
3192
  static {
2215
3193
  __name(this, "FlowMediaRepository");
@@ -2261,7 +3239,7 @@ var FlowMediaRepository = class {
2261
3239
  caption: params.caption ?? null,
2262
3240
  sortOrder: params.sortOrder ?? 0,
2263
3241
  active: true,
2264
- updatedAt: sql5`now()`
3242
+ updatedAt: sql6`now()`
2265
3243
  }
2266
3244
  }).returning();
2267
3245
  return row;
@@ -2277,7 +3255,7 @@ var FlowMediaRepository = class {
2277
3255
  ...params.active !== void 0 ? {
2278
3256
  active: params.active
2279
3257
  } : {},
2280
- updatedAt: sql5`now()`
3258
+ updatedAt: sql6`now()`
2281
3259
  }).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id))).returning();
2282
3260
  return row;
2283
3261
  }
@@ -2291,13 +3269,13 @@ var FlowMediaRepository = class {
2291
3269
  }
2292
3270
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2293
3271
  async detachRemovedNodes(params) {
2294
- const condition = params.existingNodeIds.length === 0 ? void 0 : sql5`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3272
+ const condition = params.existingNodeIds.length === 0 ? void 0 : sql6`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2295
3273
  await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.flowKey, params.flowKey), condition));
2296
3274
  }
2297
3275
  };
2298
3276
 
2299
3277
  // src/repositories/FlowMediaIdRepository.ts
2300
- import { eq as eq7, sql as sql6 } from "drizzle-orm";
3278
+ import { eq as eq7, sql as sql7 } from "drizzle-orm";
2301
3279
  var FlowMediaIdRepository = class {
2302
3280
  static {
2303
3281
  __name(this, "FlowMediaIdRepository");
@@ -2321,20 +3299,20 @@ var FlowMediaIdRepository = class {
2321
3299
  */
2322
3300
  async set(params) {
2323
3301
  await this.db.update(flowMedia).set({
2324
- metaMediaIds: sql6`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3302
+ metaMediaIds: sql7`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2325
3303
  }).where(eq7(flowMedia.id, params.flowMediaId));
2326
3304
  }
2327
3305
  /** Remove só a chave deste número — o id do outro número continua válido. */
2328
3306
  async clear(params) {
2329
3307
  await this.db.update(flowMedia).set({
2330
- metaMediaIds: sql6`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3308
+ metaMediaIds: sql7`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2331
3309
  }).where(eq7(flowMedia.id, params.flowMediaId));
2332
3310
  }
2333
3311
  };
2334
3312
 
2335
3313
  // src/channel/WhatsAppChannelAdapter.ts
2336
3314
  import { WhatsAppWindowExpiredError as ProviderWindowExpiredError } from "@adatechnology/meta-graph-core";
2337
- import { WindowExpiredError as WindowExpiredError2 } from "@adatechnology/meta-whatsapp-contracts";
3315
+ import { WindowExpiredError as WindowExpiredError2, isPreviewContact } from "@adatechnology/meta-whatsapp-contracts";
2338
3316
 
2339
3317
  // src/channel/previewMedia.ts
2340
3318
  import { PREVIEW_MEDIA_ID_PREFIX, toPreviewMediaId, resolvePreviewUploadId } from "@adatechnology/meta-whatsapp-contracts";
@@ -2346,9 +3324,16 @@ var WhatsAppChannelAdapter = class {
2346
3324
  }
2347
3325
  messages;
2348
3326
  previewMedia;
2349
- constructor(messages2, previewMedia) {
3327
+ previewContacts;
3328
+ constructor(messages2, previewMedia, previewContacts) {
2350
3329
  this.messages = messages2;
2351
3330
  this.previewMedia = previewMedia;
3331
+ this.previewContacts = previewContacts;
3332
+ }
3333
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3334
+ previewMessageId(to) {
3335
+ if (!this.previewContacts?.isEnabled || !isPreviewContact(to)) return void 0;
3336
+ return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
2352
3337
  }
2353
3338
  async translateErrors(operation) {
2354
3339
  try {
@@ -2359,12 +3344,20 @@ var WhatsAppChannelAdapter = class {
2359
3344
  }
2360
3345
  }
2361
3346
  async sendText(to, body) {
3347
+ const previewId = this.previewMessageId(to);
3348
+ if (previewId) return {
3349
+ externalMessageId: previewId
3350
+ };
2362
3351
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2363
3352
  return {
2364
3353
  externalMessageId: result.waMessageId
2365
3354
  };
2366
3355
  }
2367
3356
  async sendMedia(params) {
3357
+ const previewId = this.previewMessageId(params.to);
3358
+ if (previewId) return {
3359
+ externalMessageId: previewId
3360
+ };
2368
3361
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2369
3362
  return {
2370
3363
  externalMessageId: result.waMessageId,
@@ -2372,12 +3365,20 @@ var WhatsAppChannelAdapter = class {
2372
3365
  };
2373
3366
  }
2374
3367
  async sendTemplate(params) {
3368
+ const previewId = this.previewMessageId(params.to);
3369
+ if (previewId) return {
3370
+ externalMessageId: previewId
3371
+ };
2375
3372
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2376
3373
  return {
2377
3374
  externalMessageId: result.waMessageId
2378
3375
  };
2379
3376
  }
2380
3377
  async sendInteractiveList(params) {
3378
+ const previewId = this.previewMessageId(params.to);
3379
+ if (previewId) return {
3380
+ externalMessageId: previewId
3381
+ };
2381
3382
  const sections = (params.sections ?? [
2382
3383
  {
2383
3384
  rows: params.rows ?? []
@@ -2403,6 +3404,10 @@ var WhatsAppChannelAdapter = class {
2403
3404
  };
2404
3405
  }
2405
3406
  async sendInteractiveButtons(params) {
3407
+ const previewId = this.previewMessageId(params.to);
3408
+ if (previewId) return {
3409
+ externalMessageId: previewId
3410
+ };
2406
3411
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2407
3412
  to: params.to,
2408
3413
  bodyText: params.body,
@@ -2413,6 +3418,10 @@ var WhatsAppChannelAdapter = class {
2413
3418
  };
2414
3419
  }
2415
3420
  async sendProductList(params) {
3421
+ const previewId = this.previewMessageId(params.to);
3422
+ if (previewId) return {
3423
+ externalMessageId: previewId
3424
+ };
2416
3425
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2417
3426
  to: params.to,
2418
3427
  headerText: params.headerText,
@@ -2860,6 +3869,9 @@ var ReceiveWebhookUseCase = class {
2860
3869
  } : {},
2861
3870
  ...params.realtime ? {
2862
3871
  realtime: params.realtime
3872
+ } : {},
3873
+ ...params.flowRunner ? {
3874
+ flowRunner: params.flowRunner
2863
3875
  } : {}
2864
3876
  });
2865
3877
  }
@@ -3116,7 +4128,9 @@ function createMetaWhatsAppModule(params) {
3116
4128
  isEnabled: true,
3117
4129
  objectStorage: providers.objectStorage
3118
4130
  } : void 0;
3119
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4131
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4132
+ isEnabled: true
4133
+ } : void 0);
3120
4134
  const sessionRepository = new SessionRepository(db);
3121
4135
  const messageRepository = new MessageRepository(db);
3122
4136
  const settingsRepository = new SettingsRepository(db);
@@ -3127,6 +4141,40 @@ function createMetaWhatsAppModule(params) {
3127
4141
  const flowMediaRepository = new FlowMediaRepository(db);
3128
4142
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
3129
4143
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
4144
+ const requestHuman = new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks);
4145
+ const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
4146
+ const flowRunnerFeature = params.features?.flowRunner ?? false;
4147
+ const flowRunnerConfig = flowInterpreter && flowRunnerFeature ? flowRunnerFeature === true ? {} : flowRunnerFeature : void 0;
4148
+ const flowHandoff = flowRunnerConfig ? new FlowHandoff({
4149
+ requestHuman,
4150
+ sendMessage,
4151
+ startState,
4152
+ config: flowRunnerConfig.handoff ?? {},
4153
+ now: flowRunnerConfig.now ?? (() => /* @__PURE__ */ new Date()),
4154
+ interpolation: flowRunnerConfig.formatValue ? {
4155
+ formatValue: flowRunnerConfig.formatValue
4156
+ } : {},
4157
+ ...hooks ? {
4158
+ hooks
4159
+ } : {}
4160
+ }) : void 0;
4161
+ const flowRunner = flowInterpreter && flowRunnerConfig && flowHandoff ? new FlowRunner({
4162
+ interpreter: flowInterpreter,
4163
+ flowGraphRepository,
4164
+ sessionRepository,
4165
+ sendMessage,
4166
+ channel,
4167
+ handoff: flowHandoff,
4168
+ lock: providers.flowTurnLock ?? new PostgresAdvisoryFlowTurnLock(db),
4169
+ startState,
4170
+ config: flowRunnerConfig,
4171
+ ...hooks ? {
4172
+ hooks
4173
+ } : {}
4174
+ }) : void 0;
4175
+ if (flowInterpreter && flowRunner && flowHandoff) {
4176
+ flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
4177
+ }
3130
4178
  const receiveWebhook = new ReceiveWebhookUseCase({
3131
4179
  appSecret: config.appSecret,
3132
4180
  phoneNumberId: config.phoneNumberId,
@@ -3140,9 +4188,11 @@ function createMetaWhatsAppModule(params) {
3140
4188
  ...providers.inboundQueue ? {
3141
4189
  inboundQueue: providers.inboundQueue
3142
4190
  } : {},
3143
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4191
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4192
+ ...flowRunner ? {
4193
+ flowRunner
4194
+ } : {}
3144
4195
  });
3145
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
3146
4196
  if (flowInterpreter && providers.objectStorage?.getObject) {
3147
4197
  flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3148
4198
  flowMediaRepository,
@@ -3213,7 +4263,7 @@ function createMetaWhatsAppModule(params) {
3213
4263
  takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
3214
4264
  release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
3215
4265
  // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
3216
- requestHuman: new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks),
4266
+ requestHuman,
3217
4267
  list: new ListConversationsUseCase(sessionRepository),
3218
4268
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3219
4269
  listDocuments,
@@ -3252,6 +4302,18 @@ function createMetaWhatsAppModule(params) {
3252
4302
  webhook: {
3253
4303
  receive: receiveWebhook,
3254
4304
  // GET de verificação da Meta — o host liga na sua rota e devolve o retorno como texto puro.
4305
+ /**
4306
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
4307
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
4308
+ * Quem assina e entrega em `receive` é a rota do host.
4309
+ */
4310
+ buildPreviewPayload: /* @__PURE__ */ __name((command, envelope) => buildPreviewInboundPayload(command, {
4311
+ ...config.wabaId ? {
4312
+ wabaId: config.wabaId
4313
+ } : {},
4314
+ ...envelope,
4315
+ phoneNumberId: config.phoneNumberId
4316
+ }), "buildPreviewPayload"),
3255
4317
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3256
4318
  ...query,
3257
4319
  expectedToken: config.webhookVerifyToken
@@ -3265,6 +4327,9 @@ function createMetaWhatsAppModule(params) {
3265
4327
  } : {},
3266
4328
  ...providers.realtime ? {
3267
4329
  realtime: providers.realtime
4330
+ } : {},
4331
+ ...flowRunner ? {
4332
+ flowRunner
3268
4333
  } : {}
3269
4334
  }), hooks)
3270
4335
  },
@@ -3272,6 +4337,12 @@ function createMetaWhatsAppModule(params) {
3272
4337
  flows: flowInterpreter ? {
3273
4338
  interpreter: flowInterpreter,
3274
4339
  registerFlowAction: /* @__PURE__ */ __name((kind, handler) => flowInterpreter.registerFlowAction(kind, handler), "registerFlowAction"),
4340
+ // undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
4341
+ runner: flowRunner,
4342
+ registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
4343
+ if (!flowRunner) throw new ConfigMissingError2("features.flowRunner");
4344
+ flowRunner.registerDynamicChoiceProvider(key, provider);
4345
+ }, "registerDynamicChoiceProvider"),
3275
4346
  get: new GetFlowGraphUseCase(flowGraphRepository),
3276
4347
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3277
4348
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3398,18 +4469,26 @@ export {
3398
4469
  CreateFlowGraphUseCase,
3399
4470
  DEFAULT_FALLBACK_LIST_LABEL,
3400
4471
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4472
+ DEFAULT_FLOW_TEXT,
4473
+ DEFAULT_MAX_INVALID_ANSWERS,
4474
+ DEFAULT_START_FLOW_KEY,
4475
+ DYNAMIC_CHOICE_MORE_ID,
3401
4476
  DeleteConversationUseCase,
3402
4477
  DeleteFlowGraphUseCase,
3403
4478
  DocumentRepository,
3404
4479
  ExportConversationUseCase,
4480
+ FLOW_RUNTIME_CONTEXT_KEY,
3405
4481
  FlowGraphCache,
3406
4482
  FlowGraphRepository,
4483
+ FlowHandoff,
3407
4484
  FlowInterpreter,
3408
4485
  FlowMediaIdRepository,
3409
4486
  FlowMediaRepository,
4487
+ FlowRunner,
3410
4488
  GetFlowGraphUseCase,
3411
4489
  GetLiveFlowPositionsUseCase,
3412
4490
  INBOUND_LOCATION_CONTENT,
4491
+ InProcessFlowTurnLock,
3413
4492
  InboundEffectsDispatcher,
3414
4493
  IngestInboundMediaUseCase,
3415
4494
  InvalidFlowGraphError,
@@ -3424,6 +4503,7 @@ export {
3424
4503
  OptimisticLockError,
3425
4504
  PREVIEW_MEDIA_ID_PREFIX,
3426
4505
  PRODUCT_LIST_LIMIT,
4506
+ PostgresAdvisoryFlowTurnLock,
3427
4507
  ProcessInboundDispatchUseCase,
3428
4508
  PurgeExpiredDocumentsUseCase,
3429
4509
  ReceiveWebhookUseCase,
@@ -3443,6 +4523,7 @@ export {
3443
4523
  WEBHOOK_CLAIM_TTL_SECONDS,
3444
4524
  WEBHOOK_NONCE_TTL_SECONDS,
3445
4525
  WhatsAppChannelAdapter,
4526
+ buildFlowChoiceMessage,
3446
4527
  buildInboundJobId,
3447
4528
  claimWebhookDelivery,
3448
4529
  confirmWebhookDelivery,
@@ -3455,14 +4536,18 @@ export {
3455
4536
  flowGraphs,
3456
4537
  flowMedia,
3457
4538
  isAudioMimeType,
4539
+ isChoiceNode,
3458
4540
  isRetriableTranscriptionError,
3459
4541
  isUnsupportedTranscriptionError,
3460
4542
  issueSseTicket,
3461
4543
  messages,
3462
4544
  metaWhatsAppMigrationsFolder,
3463
4545
  metaWhatsAppSchema,
4546
+ readFlowInbound,
3464
4547
  redeemSseTicket,
3465
4548
  resolveFailureStatus,
4549
+ resolveFlowAnswer,
4550
+ resolveFlowTimeZone,
3466
4551
  resolvePreviewUploadId,
3467
4552
  runMetaWhatsAppMigrations,
3468
4553
  sessions,