@peopl-health/nexus 5.54.0-dev.7970 → 5.54.0-dev.7973

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.
@@ -1,46 +1,28 @@
1
1
  const runtimeConfig = require('../../config/runtimeConfig');
2
2
 
3
- const DEFAULT_OFFER_WINDOW_MS = 24 * 60 * 60 * 1000;
4
- const DEFAULT_HUMAN_QUIET_MS = 24 * 60 * 60 * 1000;
5
- const DEFAULT_ACTIVITY_QUIET_MS = 2 * 60 * 60 * 1000;
3
+ const DEFAULT_OFFER_WINDOW_MS = 4 * 60 * 60 * 1000;
4
+ const DEFAULT_HUMAN_QUIET_MS = 60 * 60 * 1000;
6
5
  const DEFAULT_TAP_WINDOW_MS = 30 * 60 * 1000;
7
- const DEFAULT_PLEDGE_MS = 24 * 60 * 60 * 1000;
6
+ const DEFAULT_PLEDGE_MS = 30 * 60 * 1000;
8
7
  const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
9
8
 
10
9
  const CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
11
10
 
12
11
  const SAFETY_NET_SOURCE = 'paused_safety_net';
13
12
 
14
- const PATIENT_FACING_ORIGINS = ['whatsapp_platform', 'assistant'];
15
- const HUMAN_ORIGINS = ['whatsapp_platform'];
16
- const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
17
- const RECEIVED_STATUSES = ['delivered', 'read'];
18
-
19
- const anyReplyFilter = (code, since) => ({
13
+ const humanReplyFilter = (code, since) => ({
20
14
  numero: code,
21
15
  from_me: true,
22
16
  content_sid: null,
23
- origin: { $in: PATIENT_FACING_ORIGINS },
24
- 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
17
+ origin: { $ne: 'assistant' },
25
18
  triggeredBy: { $ne: SAFETY_NET_SOURCE },
26
19
  createdAt: { $gt: since }
27
20
  });
28
21
 
29
- const humanReplyFilter = (code, since) => ({
30
- ...anyReplyFilter(code, since),
31
- origin: { $in: HUMAN_ORIGINS }
32
- });
33
-
34
- const settledHumanReplyFilter = (code, since, unconfirmedBefore) => ({
35
- ...humanReplyFilter(code, since),
36
- $or: [
37
- { 'statusInfo.status': { $in: RECEIVED_STATUSES } },
38
- { createdAt: { $lte: unconfirmedBefore } }
39
- ]
40
- });
41
-
42
22
  const CHOICE_LABEL_KEYS = {
43
- callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL'
23
+ urgent: 'PAUSED_SAFETY_NET_URGENT_LABEL',
24
+ callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL',
25
+ later: 'PAUSED_SAFETY_NET_LATER_LABEL'
44
26
  };
45
27
 
46
28
  let injected = {};
@@ -67,19 +49,15 @@ const duration = (key, envKey, fallback) => {
67
49
  module.exports = {
68
50
  CONTACT_WINDOW,
69
51
  SAFETY_NET_SOURCE,
70
- anyReplyFilter,
71
52
  humanReplyFilter,
72
- settledHumanReplyFilter,
73
53
  CHOICE_LABEL_KEYS,
74
54
  configureSafetyNet,
75
55
  _resetSafetyNetConfig,
76
56
  getSafetyNetContentSid: () => text('contentSid', 'PAUSED_SAFETY_NET_CONTENT_SID'),
77
- getSafetyNetUnassignedContentSid: () => text('unassignedContentSid', 'PAUSED_SAFETY_NET_UNASSIGNED_CONTENT_SID'),
78
57
  getSafetyNetPhone: () => text('phone', 'PAUSED_SAFETY_NET_PHONE'),
79
58
  getSafetyNetLabel: (choice) => text(`${choice}Label`, CHOICE_LABEL_KEYS[choice]),
80
59
  getOfferWindowMs: () => duration('offerWindowMs', 'PAUSED_SAFETY_NET_WINDOW_MS', DEFAULT_OFFER_WINDOW_MS),
81
60
  getHumanQuietMs: () => duration('humanQuietMs', 'SAFETY_NET_HUMAN_QUIET_MS', DEFAULT_HUMAN_QUIET_MS),
82
- getActivityQuietMs: () => duration('activityQuietMs', 'SAFETY_NET_ACTIVITY_QUIET_MS', DEFAULT_ACTIVITY_QUIET_MS),
83
61
  getTapWindowMs: () => duration('tapWindowMs', 'SAFETY_NET_TAP_WINDOW_MS', DEFAULT_TAP_WINDOW_MS),
84
62
  getPledgeMs: () => duration('pledgeMs', 'SAFETY_NET_PLEDGE_MS', DEFAULT_PLEDGE_MS),
85
63
  getSweepIntervalMs: () => duration('sweepIntervalMs', 'SAFETY_NET_SWEEP_INTERVAL_MS', DEFAULT_SWEEP_INTERVAL_MS)
@@ -0,0 +1,9 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ function inboundRecoveryLive() {
4
+ return String(runtimeConfig.get('INBOUND_RECOVERY_LIVE', 'true')).trim().toLowerCase() === 'true';
5
+ }
6
+
7
+ module.exports = {
8
+ inboundRecoveryLive,
9
+ };
@@ -15,7 +15,7 @@ const { cleanupFiles } = require('../../helpers/filesHelper.js');
15
15
  const { getMessages, countMessages } = require('../../services/messageService');
16
16
 
17
17
  const { getAssistantById } = require('./assistantResolver');
18
- const { PAUSED, coverUnansweredPatient } = require('./pausedSafetyNetService');
18
+ const { coverUnansweredPatient } = require('./pausedSafetyNetService');
19
19
 
20
20
  const MEDIA_BACKLOG_LIMIT = 10;
21
21
 
@@ -112,7 +112,7 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
112
112
  return { shouldProcess: false, messages: null, timings, pendingMediaUpdates: [] };
113
113
  }
114
114
 
115
- if (thread.stopped) await coverUnansweredPatient({ code, reason: PAUSED });
115
+ if (thread.stopped) await coverUnansweredPatient({ code });
116
116
 
117
117
  const backlog = await fetchMediaBacklog(code, lastMessage[0]);
118
118
  const replies = [...backlog, ...lastMessage];
@@ -1,14 +1,12 @@
1
1
  const {
2
2
  CONTACT_WINDOW,
3
3
  SAFETY_NET_SOURCE,
4
- getActivityQuietMs,
5
4
  getHumanQuietMs,
6
5
  getOfferWindowMs,
7
6
  getPledgeMs,
8
7
  getSafetyNetContentSid,
9
8
  getSafetyNetLabel,
10
9
  getSafetyNetPhone,
11
- getSafetyNetUnassignedContentSid,
12
10
  getTapWindowMs
13
11
  } = require('../config/safetyNetConfig');
14
12
  const { logger } = require('../../utils/logger');
@@ -17,23 +15,28 @@ const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../..
17
15
 
18
16
  const { normalizePayload: normalize, registerInteractiveRoute, unregisterInteractiveRoute } = require('../../core/interactiveRouteService');
19
17
  const { getMessages } = require('../../services/messageService');
18
+ const { getPatientTasks, updatePatientTask } = require('../../services/patientTaskService');
20
19
 
21
20
  const { WriteClaimStore } = require('./writeClaimStore');
22
- const { recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
23
- const { anyoneRepliedSince, humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
21
+ const { PAUSED_THREAD_DETAILS_PREFIX, recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
22
+ const { humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
24
23
 
25
24
  const getMessaging = () => require('../../core/NexusMessaging');
26
25
 
27
26
  const SOURCE = SAFETY_NET_SOURCE;
28
27
  const PAYLOAD_PREFIX = 'peopl_safetynet_';
29
- const CHOICES = ['callback'];
30
- const PAUSED = 'paused';
31
- const UNASSIGNED = 'unassigned';
28
+ const CHOICES = ['urgent', 'callback', 'later'];
32
29
  const REQUEST_CATEGORY = 'contact_team_member';
30
+ const CAN_WAIT_NOTE = 'El paciente indicó que su solicitud puede esperar.';
31
+ const ATTENDED_STATUS = 'sin atender';
33
32
 
34
33
  const REQUEST_COPY = {
34
+ urgent: {
35
+ question: 'El paciente indicó que su situación es urgente',
36
+ details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y eligió "urgencia". Se le dio el número para llamar. Revisar la conversación ahora.`
37
+ },
35
38
  callback: {
36
- question: 'El paciente pidió que el equipo lo contacte',
39
+ question: 'El paciente pidió que el equipo lo contacte hoy',
37
40
  details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y pidió que lo contacten. Se le prometió contacto; revisar la conversación.`
38
41
  }
39
42
  };
@@ -78,25 +81,15 @@ function matchSafetyNetChoice(payload, title) {
78
81
  }) || null;
79
82
  }
80
83
 
81
- const dialledNumbers = (template) => Object.values(template?.types ?? {})
82
- .flatMap((type) => type?.actions ?? [])
83
- .filter((action) => action?.type === 'PHONE_NUMBER')
84
- .map((action) => action?.phone);
85
-
86
84
  async function warnIfPhoneDiffersFromTemplate(contentSid) {
87
85
  const phone = getSafetyNetPhone();
88
86
  if (!phone || phoneCheckedFor === contentSid) return;
89
87
  phoneCheckedFor = contentSid;
90
88
  try {
91
- const provider = getMessaging().requireProvider();
89
+ const body = await getMessaging().requireProvider().renderTemplate(contentSid);
92
90
  const digits = (value) => String(value ?? '').replace(/\D/g, '');
93
- const wanted = digits(phone);
94
-
95
- if (dialledNumbers(await provider.getTemplate(contentSid)).map(digits).includes(wanted)) return;
96
-
97
- const body = await provider.renderTemplate(contentSid);
98
- if (body && !digits(body).includes(wanted)) {
99
- logger.error('[PausedSafetyNet] The configured phone number is absent from the template', { contentSid });
91
+ if (body && !digits(body).includes(digits(phone))) {
92
+ logger.error('[PausedSafetyNet] The configured phone number is absent from the template body', { contentSid });
100
93
  }
101
94
  } catch (error) {
102
95
  phoneCheckedFor = null;
@@ -104,19 +97,13 @@ async function warnIfPhoneDiffersFromTemplate(contentSid) {
104
97
  }
105
98
  }
106
99
 
107
- function templateFor(reason) {
108
- if (reason !== UNASSIGNED) return getSafetyNetContentSid();
109
- return getSafetyNetUnassignedContentSid() || getSafetyNetContentSid();
110
- }
111
-
112
- async function offerSafetyNet({ code, reason = PAUSED }) {
100
+ async function offerSafetyNet({ code }) {
113
101
  try {
114
- if (!code || !getSafetyNetContentSid() || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
102
+ const contentSid = getSafetyNetContentSid();
103
+ if (!code || !contentSid || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
115
104
  if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
116
105
  if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
117
- if (await anyoneRepliedSince(code, new Date(Date.now() - getActivityQuietMs()))) return { sent: false, reason: 'conversation_active' };
118
106
 
119
- const contentSid = templateFor(reason);
120
107
  await warnIfPhoneDiffersFromTemplate(contentSid);
121
108
 
122
109
  const result = await getMessaging().sendMessage({ code, contentSid, triggeredBy: SOURCE });
@@ -131,13 +118,11 @@ async function offerSafetyNet({ code, reason = PAUSED }) {
131
118
  }
132
119
  }
133
120
 
134
- const offerContentSids = () => [getSafetyNetContentSid(), getSafetyNetUnassignedContentSid()].filter(Boolean);
135
-
136
121
  async function offerIsLive(code) {
137
122
  try {
138
123
  const since = new Date(Date.now() - getOfferWindowMs());
139
124
  const [sent] = await getMessages(
140
- { numero: code, from_me: true, content_sid: { $in: offerContentSids() }, createdAt: { $gt: since } },
125
+ { numero: code, from_me: true, content_sid: getSafetyNetContentSid(), createdAt: { $gt: since } },
141
126
  { sort: { createdAt: -1 }, limit: 1 }
142
127
  );
143
128
  return Boolean(sent);
@@ -155,7 +140,7 @@ async function unansweredText(code) {
155
140
  return written ? written.plainBody || written.body : null;
156
141
  }
157
142
 
158
- async function coverUnansweredPatient({ code, reason = PAUSED }) {
143
+ async function coverUnansweredPatient({ code }) {
159
144
  if (!code) return;
160
145
 
161
146
  const claim = await acquireSendClaim({ idempotencyKey: `safetynet-cover:${code}` });
@@ -163,7 +148,7 @@ async function coverUnansweredPatient({ code, reason = PAUSED }) {
163
148
 
164
149
  const results = await Promise.allSettled([
165
150
  unansweredText(code).then((text) => recordPausedThreadMessage({ code, text })),
166
- offerSafetyNet({ code, reason }),
151
+ offerSafetyNet({ code }),
167
152
  ]);
168
153
 
169
154
  const covered = results.every((r) => r.status === 'fulfilled');
@@ -183,8 +168,32 @@ async function fileUrgentRequest(code, choice) {
183
168
  });
184
169
  }
185
170
 
171
+ async function markCanWait(code) {
172
+ const { requests = [] } = await getPatientTasks(code);
173
+ const target = requests.find((request) => request.status === ATTENDED_STATUS
174
+ && request.category === REQUEST_CATEGORY
175
+ && String(request.details || '').startsWith(PAUSED_THREAD_DETAILS_PREFIX));
176
+ if (!target) return false;
177
+
178
+ await updatePatientTask({
179
+ code,
180
+ kind: 'requests',
181
+ recordId: target.recordId,
182
+ changes: {
183
+ urgency: 'routine',
184
+ note: [target.note, CAN_WAIT_NOTE].filter(Boolean).join('\n')
185
+ },
186
+ updatedBy: SOURCE,
187
+ source: SOURCE
188
+ });
189
+ return true;
190
+ }
191
+
186
192
  async function applyChoice(code, choice) {
193
+ if (choice === 'later') return { queued: true, downgraded: await markCanWait(code), pledge: null };
194
+
187
195
  const queued = await fileUrgentRequest(code, choice);
196
+ if (choice !== 'callback') return { queued, pledge: null };
188
197
  if (!queued) return { queued, pledge: null };
189
198
 
190
199
  try {
@@ -200,17 +209,6 @@ const withPhone = (text, closing) => {
200
209
  return phone ? `${text} ${closing.replace('{phone}', phone)}` : text;
201
210
  };
202
211
 
203
- function pledgeWindowText() {
204
- const minutes = Math.ceil(getPledgeMs() / 60000);
205
- if (minutes < 120) return `en los próximos ${minutes} minutos`;
206
-
207
- const hours = Math.ceil(minutes / 60);
208
- if (hours < 24) return `en las próximas ${hours} horas`;
209
-
210
- const days = Math.ceil(hours / 24);
211
- return days <= 1 ? 'en las próximas 24 horas' : `en los próximos ${days} días`;
212
- }
213
-
214
212
  function ackFor(choice, outcome) {
215
213
  if (outcome.stale) {
216
214
  return withPhone('Recibimos tu respuesta y el equipo va a revisar tu conversación.', 'Si necesitas ayuda ahora, llámanos al {phone}.');
@@ -220,6 +218,16 @@ function ackFor(choice, outcome) {
220
218
  return withPhone('No pudimos registrar tu solicitud.', 'Por favor llámanos al {phone} para que te atendamos.');
221
219
  }
222
220
 
221
+ if (choice === 'urgent') {
222
+ return withPhone('Entendido, ya avisamos al equipo.', 'Si es una urgencia médica, llámanos ahora al {phone}.');
223
+ }
224
+
225
+ if (choice === 'later') {
226
+ return outcome.downgraded
227
+ ? withPhone('Gracias, lo anotamos. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.')
228
+ : withPhone('Gracias. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.');
229
+ }
230
+
223
231
  if (!outcome.pledge) {
224
232
  return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
225
233
  }
@@ -231,8 +239,9 @@ function ackFor(choice, outcome) {
231
239
  );
232
240
  }
233
241
 
242
+ const minutes = Math.round(getPledgeMs() / 60000);
234
243
  return withPhone(
235
- `Listo. Un miembro del equipo te va a contactar ${pledgeWindowText()}.`,
244
+ `Listo. Un miembro del equipo te va a contactar en los próximos ${minutes} minutos.`,
236
245
  'Si te sientes peor antes, llámanos al {phone}.'
237
246
  );
238
247
  }
@@ -301,8 +310,6 @@ module.exports = {
301
310
  coverUnansweredPatient,
302
311
  disarmSafetyNet,
303
312
  offerSafetyNet,
304
- PAUSED,
305
- UNASSIGNED,
306
313
  handleSafetyNetTap,
307
314
  matchSafetyNetChoice,
308
315
  registerSafetyNetRoutes,
@@ -3,9 +3,9 @@ const { Symptoms_ID } = require('../../config/airtableConfig');
3
3
  const { logger } = require('../../utils/logger');
4
4
  const { getRecordByFilter } = require('../../services/airtableService');
5
5
  const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
6
- const { Thread } = require('../../models/threadModel');
7
6
  const runtimeConfig = require('../../config/runtimeConfig');
8
7
  const { createIntervalSweeper } = require('../../utils/intervalSweeper');
8
+ const { botIsPaused: threadIsPaused } = require('../../helpers/pausedThreadHelper');
9
9
  const { recordUnresolvedRequest } = require('./clinicalAirtableService');
10
10
  const { handleTriageCompleted } = require('./triageRecommendationService');
11
11
  const { WriteClaimStore } = require('./writeClaimStore');
@@ -25,6 +25,8 @@ const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttl
25
25
 
26
26
  const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
27
27
 
28
+ const botIsPaused = (code) => threadIsPaused(code, { label: '[recommendationRecovery]' });
29
+
28
30
  function orphanFormula(now) {
29
31
  const newest = new Date(now.getTime() - MIN_AGE_MS).toISOString();
30
32
  const oldest = new Date(now.getTime() - SCAN_WINDOW_MS).toISOString();
@@ -53,17 +55,6 @@ function describe(row) {
53
55
  };
54
56
  }
55
57
 
56
- async function botIsPaused(code) {
57
- if (!code) return false;
58
- try {
59
- const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
60
- return Boolean(paused);
61
- } catch (error) {
62
- logger.warn('[recommendationRecovery] thread state unreadable; treating the bot as paused', { code, error: error.message });
63
- return true;
64
- }
65
- }
66
-
67
58
  async function fileOpsTicket(orphan) {
68
59
  if (!orphan.code) return false;
69
60
  return recordUnresolvedRequest({
@@ -1,9 +1,7 @@
1
- const {
2
- CONTACT_WINDOW, anyReplyFilter, getPledgeMs, getSweepIntervalMs, humanReplyFilter, settledHumanReplyFilter
3
- } = require('../config/safetyNetConfig');
1
+ const { CONTACT_WINDOW, getPledgeMs, getSweepIntervalMs, humanReplyFilter } = require('../config/safetyNetConfig');
4
2
  const { createIntervalSweeper } = require('../../utils/intervalSweeper');
5
3
  const { logger } = require('../../utils/logger');
6
- const { clampBackToHourWindow, clampToHourWindow } = require('../../utils/scheduleUtils');
4
+ const { clampToHourWindow } = require('../../utils/scheduleUtils');
7
5
 
8
6
  const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
9
7
 
@@ -15,30 +13,16 @@ const SWEEP_LIMIT = 200;
15
13
  const BREACH_CATEGORY = 'contact_team_member';
16
14
  const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
17
15
 
18
- const DELIVERY_GRACE_MS = 10 * 60 * 1000;
19
-
20
- async function repliedSince(filter) {
21
- const [reply] = await getMessages(filter, { sort: { createdAt: -1 }, limit: 1 });
16
+ async function humanRepliedSince(code, since) {
17
+ const [reply] = await getMessages(humanReplyFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
22
18
  return Boolean(reply);
23
19
  }
24
20
 
25
- const humanRepliedSince = (code, since) => repliedSince(humanReplyFilter(code, since));
26
- const humanReplySettledSince = (code, since) => repliedSince(
27
- settledHumanReplyFilter(code, since, new Date(Date.now() - DELIVERY_GRACE_MS))
28
- );
29
- const anyoneRepliedSince = (code, since) => repliedSince(anyReplyFilter(code, since));
30
-
31
21
  function pledgeDueAt(pledgedAt) {
32
22
  const target = new Date(pledgedAt.getTime() + getPledgeMs());
33
-
34
- const pulled = clampBackToHourWindow(target, CONTACT_WINDOW);
35
- if (pulled && pulled.getTime() > pledgedAt.getTime()) {
36
- return { dueAt: pulled, deferredToWindow: false };
37
- }
38
-
39
- const pushed = clampToHourWindow(target, CONTACT_WINDOW);
40
- if (!pushed) return { dueAt: target, deferredToWindow: false };
41
- return { dueAt: pushed, deferredToWindow: pushed.getTime() > target.getTime() };
23
+ const opened = clampToHourWindow(target, CONTACT_WINDOW);
24
+ if (!opened) return { dueAt: target, deferredToWindow: false };
25
+ return { dueAt: opened, deferredToWindow: opened.getTime() > target.getTime() };
42
26
  }
43
27
 
44
28
  async function openPledge({ code }) {
@@ -67,11 +51,6 @@ const settle = async (id, from, state) => Boolean(
67
51
  await SafetyNetPledge.findOneAndUpdate({ _id: id, state: from }, { $set: { state, resolvedAt: new Date() } }).lean()
68
52
  );
69
53
 
70
- const returnToPending = (id) => SafetyNetPledge.updateOne(
71
- { _id: id, state: 'reporting' },
72
- { $set: { state: 'pending', reportingSince: null } }
73
- );
74
-
75
54
  const takeReportingLease = async (id) => Boolean(
76
55
  await SafetyNetPledge.findOneAndUpdate(
77
56
  { _id: id, $or: [{ state: 'pending' }, { state: 'reporting', reportingSince: { $lt: new Date(Date.now() - REPORT_LEASE_MS) } }] },
@@ -94,18 +73,13 @@ async function sweepSafetyNetPledges() {
94
73
  try {
95
74
  if (!await takeReportingLease(pledge._id)) continue;
96
75
 
97
- if (await humanReplySettledSince(pledge.code, pledge.pledgedAt)) {
98
- await settle(pledge._id, 'reporting', 'met');
99
- continue;
100
- }
101
-
102
76
  if (await humanRepliedSince(pledge.code, pledge.pledgedAt)) {
103
- await returnToPending(pledge._id);
77
+ await settle(pledge._id, 'reporting', 'met');
104
78
  continue;
105
79
  }
106
80
 
107
81
  if (!await reportBreach(pledge)) {
108
- await returnToPending(pledge._id);
82
+ await SafetyNetPledge.updateOne({ _id: pledge._id, state: 'reporting' }, { $set: { state: 'pending', reportingSince: null } });
109
83
  logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
110
84
  continue;
111
85
  }
@@ -130,9 +104,7 @@ const stopSafetyNetSweep = () => sweeper.stop();
130
104
  module.exports = {
131
105
  startSafetyNetSweep,
132
106
  stopSafetyNetSweep,
133
- anyoneRepliedSince,
134
107
  humanRepliedSince,
135
- humanReplySettledSince,
136
108
  openPledge,
137
109
  pledgeDueAt,
138
110
  sweepSafetyNetPledges,
@@ -5,6 +5,7 @@ const { logger } = require('../utils/logger');
5
5
  const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
6
6
  const { setPreprocessingHandler } = require('../services/preprocessingService');
7
7
  const { clearTriageHistoryCache } = require('../services/triageHistoryService');
8
+ const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
8
9
  const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
9
10
  const { _resetDefaultInstance } = require('../core/NexusMessaging');
10
11
  const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
@@ -19,7 +20,7 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
19
20
  const SWEEP_STOP_MS = 2000;
20
21
 
21
22
  function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
22
- const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep()]);
23
+ const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep()]);
23
24
  return withTimeout(stopped, timeoutMs, 'sweeps.stop')
24
25
  .catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
25
26
  }
@@ -31,7 +31,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
31
31
  const { BatchingManager } = require('../core/BatchingManager');
32
32
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
33
33
  const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
34
- const { UNASSIGNED, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
34
+ const { coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
35
35
  const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
36
36
  const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
37
37
  const {
@@ -674,54 +674,75 @@ class NexusMessaging {
674
674
 
675
675
  async _handleWithCheckAfter(chatId) {
676
676
  return await this._executeWithPipeline(chatId, 'message', 'preempt',
677
- async (preProcessResult, shouldContinue, runId) => {
678
- return await this._processMessages(chatId, async () => {
679
- const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
680
- logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
681
- return null;
682
- });
683
- if (!resolved) {
684
- await coverUnansweredPatient({ code: chatId, reason: UNASSIGNED });
685
- return null;
686
- }
677
+ async (preProcessResult, shouldContinue, runId) =>
678
+ this._runPatientTurn(chatId, preProcessResult, shouldContinue, runId)
679
+ );
680
+ }
687
681
 
688
- const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
689
-
690
- await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
691
- this.phiProcessor.inData(
692
- { body: u.processedContent, code: chatId },
693
- ({ body: encoded }) => updateMessage(
694
- { message_id: u.message_id },
695
- { $set: {
696
- assistant_id: u.assistantId,
697
- thread_id: u.threadId,
698
- 'media.metadata.processedContent': encoded,
699
- }}
700
- ),
701
- () => null,
702
- )
703
- ));
704
-
705
- if (!preProcessed.shouldProcess) return null;
706
-
707
- const result = await this.assistantProcessor.executeLLM(
708
- resolved.thread, resolved.assistant,
709
- { prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
710
- preProcessed.messages[0]
711
- );
682
+ async recoverInboundTurn(code, { confirmStillUnanswered = null } = {}) {
683
+ return await this._executeWithPipeline(code, 'message', 'queue',
684
+ async (preProcessResult, shouldContinue, runId) =>
685
+ this._runPatientTurn(code, preProcessResult, shouldContinue, runId, { confirmStillUnanswered })
686
+ );
687
+ }
712
688
 
713
- try {
714
- if (storeRunMetrics) {
715
- await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
716
- }
717
- } catch (error) {
718
- await this.assistantProcessor.discardResponse?.(chatId, result);
719
- throw error;
720
- }
721
- return { ...result, timings: preProcessed.timings };
722
- }, shouldContinue, runId);
689
+ async _runPatientTurn(chatId, preProcessResult, shouldContinue, runId, { confirmStillUnanswered = null } = {}) {
690
+ return await this._processMessages(chatId, async () => {
691
+ const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
692
+ logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
693
+ return null;
694
+ });
695
+ if (!resolved) {
696
+ await coverUnansweredPatient({ code: chatId });
697
+ return null;
723
698
  }
724
- );
699
+
700
+ const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
701
+
702
+ await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
703
+ this.phiProcessor.inData(
704
+ { body: u.processedContent, code: chatId },
705
+ ({ body: encoded }) => updateMessage(
706
+ { message_id: u.message_id },
707
+ { $set: {
708
+ assistant_id: u.assistantId,
709
+ thread_id: u.threadId,
710
+ 'media.metadata.processedContent': encoded,
711
+ }}
712
+ ),
713
+ () => null,
714
+ )
715
+ ));
716
+
717
+ if (!preProcessed.shouldProcess) return null;
718
+
719
+ if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
720
+ logger.info('[inboundRecovery] a reply landed while the replay was queued; standing down', { code: chatId });
721
+ return null;
722
+ }
723
+
724
+ const result = await this.assistantProcessor.executeLLM(
725
+ resolved.thread, resolved.assistant,
726
+ { prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
727
+ preProcessed.messages[0]
728
+ );
729
+
730
+ if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
731
+ logger.info('[inboundRecovery] a reply landed while the replay was generating; discarding it', { code: chatId });
732
+ await this.assistantProcessor.discardResponse?.(chatId, result);
733
+ return null;
734
+ }
735
+
736
+ try {
737
+ if (storeRunMetrics) {
738
+ await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
739
+ }
740
+ } catch (error) {
741
+ await this.assistantProcessor.discardResponse?.(chatId, result);
742
+ throw error;
743
+ }
744
+ return { ...result, timings: preProcessed.timings };
745
+ }, shouldContinue, runId);
725
746
  }
726
747
 
727
748
  async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
@@ -0,0 +1,15 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { Thread } = require('../models/threadModel');
3
+
4
+ async function botIsPaused(code, { label = '[pausedThread]' } = {}) {
5
+ if (!code) return false;
6
+ try {
7
+ const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
8
+ return Boolean(paused);
9
+ } catch (error) {
10
+ logger.warn(`${label} thread state unreadable; treating the bot as paused`, { code, error: error.message });
11
+ return true;
12
+ }
13
+ }
14
+
15
+ module.exports = { botIsPaused };
package/lib/index.d.ts CHANGED
@@ -331,6 +331,7 @@ declare module '@peopl-health/nexus' {
331
331
  parserConfig?: ParserConfig;
332
332
  ner?: NerOptions;
333
333
  recommendationRecovery?: RecommendationRecoveryOptions;
334
+ inboundRecovery?: InboundRecoveryOptions;
334
335
  }
335
336
 
336
337
  export interface RecommendationRecoveryOptions {
@@ -338,6 +339,11 @@ declare module '@peopl-health/nexus' {
338
339
  intervalMs?: number;
339
340
  }
340
341
 
342
+ export interface InboundRecoveryOptions {
343
+ enabled: boolean;
344
+ intervalMs?: number;
345
+ }
346
+
341
347
  export interface NerEntity {
342
348
  start: number;
343
349
  end: number;
package/lib/index.js CHANGED
@@ -31,6 +31,7 @@ const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
31
31
  const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
32
32
  const { startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
33
  const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
34
+ const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
34
35
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
35
36
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
36
37
  const { createWorkflowRunner } = require('./core/workflowRunner');
@@ -199,6 +200,19 @@ class Nexus {
199
200
  logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
200
201
  }
201
202
 
203
+ try {
204
+ if (options.inboundRecovery?.enabled === true) {
205
+ startInboundRecoverySweep({
206
+ recover: (code, opts) => this.messaging.recoverInboundTurn(code, opts),
207
+ isProcessing: (code) => this.messaging.isProcessing(code),
208
+ intervalMs: options.inboundRecovery.intervalMs,
209
+ });
210
+ logger.info('[Nexus] inbound recovery sweep armed');
211
+ }
212
+ } catch (e) {
213
+ logger.warn('Warning: failed to arm the inbound recovery sweep:', e?.message || e);
214
+ }
215
+
202
216
  try {
203
217
  if (options.recommendationRecovery?.enabled === true) {
204
218
  startRecommendationRecoverySweep({ intervalMs: options.recommendationRecovery.intervalMs });
@@ -0,0 +1,209 @@
1
+ const runtimeConfig = require('../config/runtimeConfig');
2
+ const { logger } = require('../utils/logger');
3
+ const { isWithinHourWindow } = require('../utils/scheduleUtils');
4
+ const { createIntervalSweeper } = require('../utils/intervalSweeper');
5
+ const { Thread } = require('../models/threadModel');
6
+ const { botIsPaused } = require('../helpers/pausedThreadHelper');
7
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
8
+ const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
9
+ const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
10
+ const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
11
+ const { getMessages, countMessages } = require('./messageService');
12
+
13
+ const MIN_AGE_MS = 5 * 60 * 1000;
14
+ const MAX_AGE_MS = 60 * 60 * 1000;
15
+ const SCAN_LIMIT = 200;
16
+ const MAX_CANDIDATES = 20;
17
+ const MAX_RECOVERIES_PER_PASS = 3;
18
+ const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
19
+ const REPLAY_SETTLE_MS = 5 * 60 * 1000;
20
+ const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
21
+ const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
22
+
23
+ const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
24
+ const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
25
+
26
+ async function unansweredThreads(now) {
27
+ return Thread.find(
28
+ {
29
+ stopped: false,
30
+ lastMessageFromMe: false,
31
+ lastMessageAt: { $gte: new Date(now.getTime() - MAX_AGE_MS), $lte: new Date(now.getTime() - MIN_AGE_MS) },
32
+ },
33
+ { code: 1, lastMessageAt: 1 },
34
+ ).sort({ lastMessageAt: 1 }).limit(SCAN_LIMIT).lean();
35
+ }
36
+
37
+ const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
38
+
39
+ async function stillUnanswered(code, now = new Date()) {
40
+ const [newest] = await getMessages(
41
+ { numero: code, from_me: false, interactive_type: null },
42
+ { select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
43
+ );
44
+ if (!newest) return null;
45
+
46
+ const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
47
+ if (!Number.isFinite(ageMs) || ageMs < MIN_AGE_MS || ageMs > MAX_AGE_MS) return null;
48
+
49
+ const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt } });
50
+ return replies === 0 ? newest : null;
51
+ }
52
+
53
+ async function fileTicket(code, alert) {
54
+ try {
55
+ return Boolean(await alert({ code, category: 'contact_team_member', question: 'El paciente escribió y no recibió respuesta.' }));
56
+ } catch (error) {
57
+ logger.error('[inboundRecovery] could not file the ops ticket', { code, error: error.message });
58
+ return false;
59
+ }
60
+ }
61
+
62
+ async function sweepUnansweredInbound({
63
+ now = new Date(),
64
+ recover = null,
65
+ isProcessing = () => false,
66
+ live = inboundRecoveryLive,
67
+ claims = recoveryClaims,
68
+ ticketGate = ticketClaims,
69
+ isPaused = threadIsOwnedByAHuman,
70
+ alert = recordUnresolvedRequest,
71
+ } = {}) {
72
+ let threads;
73
+ try {
74
+ threads = await unansweredThreads(now);
75
+ } catch (error) {
76
+ logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
77
+ return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
78
+ }
79
+
80
+ const candidates = [];
81
+ for (const thread of threads) {
82
+ if (!thread.code) continue;
83
+ if (isProcessing(thread.code)) continue;
84
+ try {
85
+ const inbound = await stillUnanswered(thread.code, now);
86
+ if (inbound) candidates.push({ code: thread.code, inbound });
87
+ } catch (error) {
88
+ logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
89
+ code: thread.code, error: error.message,
90
+ });
91
+ }
92
+ }
93
+
94
+ if (!candidates.length) return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
95
+
96
+ if (candidates.length > MAX_CANDIDATES) {
97
+ logger.error('[inboundRecovery] too many patients look unanswered; acting on none', {
98
+ found: candidates.length, ceiling: MAX_CANDIDATES,
99
+ });
100
+ return { scanned: candidates.length, recovered: 0, alerted: 0, skipped: candidates.length };
101
+ }
102
+
103
+ const canRecover = live() && typeof recover === 'function';
104
+ let recovered = 0;
105
+ let alerted = 0;
106
+ let skipped = 0;
107
+
108
+ for (const { code, inbound } of candidates) {
109
+ const key = String(inbound._id);
110
+ const ageMs = now.getTime() - new Date(inbound.createdAt).getTime();
111
+
112
+ if (await isPaused(code)) { skipped += 1; continue; }
113
+
114
+ const claim = await claims.acquire(key, 'handled');
115
+ if (claim === 'unavailable') {
116
+ skipped += 1;
117
+ logger.error('[inboundRecovery] patient looks unanswered and could not be claimed', { code, ageMs });
118
+ continue;
119
+ }
120
+
121
+ if (claim === 'taken') {
122
+ const claimedAt = typeof claims.claimedAtMs === 'function' ? await claims.claimedAtMs(key) : null;
123
+ if (claimedAt === null || (now.getTime() - claimedAt) < REPLAY_SETTLE_MS) { skipped += 1; continue; }
124
+
125
+ const ticket = await ticketGate.acquire(key, 'alerted');
126
+ if (ticket !== 'acquired') { skipped += 1; continue; }
127
+
128
+ logger.error('[inboundRecovery] a replay already ran and the patient is still unanswered', { code, ageMs });
129
+ if (await fileTicket(code, alert)) {
130
+ alerted += 1;
131
+ } else {
132
+ await ticketGate.release(key);
133
+ }
134
+ continue;
135
+ }
136
+
137
+ const reachable = isWithinHourWindow(now, PATIENT_CONTACT_WINDOW) && await isWithin24HourWindow(code);
138
+
139
+ if (canRecover && reachable && recovered < MAX_RECOVERIES_PER_PASS) {
140
+ logger.error('[inboundRecovery] patient was left unanswered, replaying the turn', { code, ageMs });
141
+ try {
142
+ await recover(code);
143
+ recovered += 1;
144
+ continue;
145
+ } catch (error) {
146
+ await claims.release(key);
147
+ logger.error('[inboundRecovery] replay could not be dispatched', { code, ageMs, error: error.message });
148
+ continue;
149
+ }
150
+ }
151
+
152
+ logger.error('[inboundRecovery] patient was left unanswered', {
153
+ code, ageMs, recoveryLive: canRecover, reachable,
154
+ });
155
+ if (await fileTicket(code, alert)) {
156
+ alerted += 1;
157
+ } else {
158
+ await claims.release(key);
159
+ }
160
+ }
161
+
162
+ return { scanned: candidates.length, recovered, alerted, skipped };
163
+ }
164
+
165
+ function sweepIntervalMs() {
166
+ const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
167
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
168
+ }
169
+
170
+ let sweeper = null;
171
+
172
+ function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
173
+ if (!sweeper) {
174
+ sweeper = createIntervalSweeper({
175
+ label: '[inboundRecovery]',
176
+ sweep: () => sweepUnansweredInbound({
177
+ recover: typeof recover === 'function'
178
+ ? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
179
+ : null,
180
+ isProcessing,
181
+ }),
182
+ defaultIntervalMs: sweepIntervalMs,
183
+ });
184
+ }
185
+ return sweeper.start({ intervalMs });
186
+ }
187
+
188
+ function stopInboundRecoverySweep() {
189
+ if (!sweeper) return Promise.resolve();
190
+ const stopping = sweeper.stop();
191
+ sweeper = null;
192
+ return stopping;
193
+ }
194
+
195
+ module.exports = {
196
+ startInboundRecoverySweep,
197
+ stopInboundRecoverySweep,
198
+ sweepUnansweredInbound,
199
+ DEFAULT_SWEEP_INTERVAL_MS,
200
+ stillUnanswered,
201
+ threadIsOwnedByAHuman,
202
+ _claims: recoveryClaims,
203
+ _ticketClaims: ticketClaims,
204
+ MIN_AGE_MS,
205
+ MAX_AGE_MS,
206
+ MAX_CANDIDATES,
207
+ MAX_RECOVERIES_PER_PASS,
208
+ SCAN_LIMIT,
209
+ };
@@ -18,18 +18,6 @@ function clampToHourWindow(when, { timeZone, startHour, endHour }) {
18
18
  return local.startOf('day').hour(startHour).toDate();
19
19
  }
20
20
 
21
- function clampBackToHourWindow(when, { timeZone, startHour, endHour }) {
22
- const local = moment.tz(when, timeZone);
23
- if (!local.isValid()) {
24
- logger.warn('[clampBackToHourWindow] Invalid date', { when, timeZone });
25
- return null;
26
- }
27
- const hour = local.hour();
28
- if (hour >= startHour && hour < endHour) return local.toDate();
29
- if (hour < startHour) local.subtract(1, 'day');
30
- return local.startOf('day').hour(endHour).subtract(1, 'minute').toDate();
31
- }
32
-
33
21
  function isWithinHourWindow(when, { timeZone, startHour, endHour }) {
34
22
  const local = moment.tz(when, timeZone);
35
23
  if (!local.isValid()) {
@@ -100,4 +88,4 @@ function calculateDelay(sendTime, timeZone) {
100
88
  }
101
89
  }
102
90
 
103
- module.exports = { calculateDelay, clampBackToHourWindow, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
91
+ module.exports = { calculateDelay, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.54.0-dev.7970",
3
+ "version": "5.54.0-dev.7973",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",