@peopl-health/nexus 5.73.1 → 5.74.0-dev.15344

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.
@@ -0,0 +1,3 @@
1
+ const CHECK_IN_TYPES = ['contingencia', 'seguimiento'];
2
+
3
+ module.exports = { CHECK_IN_TYPES };
@@ -19,6 +19,7 @@ const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
19
19
  const { logger } = require('../../utils/logger');
20
20
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
21
21
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
22
+ const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
22
23
  const { isJsonBlob } = require('../../utils/formatUtils');
23
24
  const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
24
25
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
@@ -355,6 +356,8 @@ class BaseLLMProvider {
355
356
  })
356
357
  .filter(Boolean);
357
358
 
359
+ if (outreachBrief.checkIn) return this._buildCheckInDueMessage(outreachBrief, lines);
360
+
358
361
  const why = lines([
359
362
  ['último triaje contestado', outreachBrief.lastTriageAt],
360
363
  ['grado máximo en ese triaje', outreachBrief.maxGrade],
@@ -388,6 +391,49 @@ class BaseLLMProvider {
388
391
  return [{ role: 'developer', content: parts.join('\n') }];
389
392
  }
390
393
 
394
+ _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
395
+ const ago = (at) => {
396
+ const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
397
+ if (!Number.isFinite(minutes) || minutes < 0) return '';
398
+ return minutes < 60 ? ` (hace ${minutes} min)` : ` (hace ${Math.floor(minutes / 60)} h ${minutes % 60} min)`;
399
+ };
400
+ const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
401
+ const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
402
+ const pending = lines([
403
+ ['lo que querías preguntarle', checkIn.question],
404
+ ['por qué quedó abierto', checkIn.concern],
405
+ ['qué dato esperabas', checkIn.awaiting],
406
+ ['desde', local(checkIn.armedAt)],
407
+ ['nivel de la escalación', checkIn.urgency],
408
+ ]);
409
+ const conversation = lines([
410
+ ['su último mensaje', said(exchange?.patient)],
411
+ ['tu último mensaje (tuyo o del equipo)', said(exchange?.own)],
412
+ ['mensajes tuyos o del equipo hoy', exchange ? String(exchange.ownMessagesToday) : null],
413
+ ]);
414
+ const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
415
+ const parts = [
416
+ '[CHECK-IN QUE VENCE (prioritario) para este turno]',
417
+ 'Venció el plazo para retomar algo pendiente con ella. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a buscarla o si ya no hace falta.',
418
+ '', '## Qué quedó pendiente', ...pending,
419
+ ];
420
+ if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
421
+ parts.push(
422
+ '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
423
+ '',
424
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
425
+ '- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
426
+ '- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
427
+ '- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
428
+ '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ella ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
429
+ '- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
430
+ '- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
431
+ '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que ella contó o acordó.',
432
+ 'Si escribes: breve, sin saludar ni escribir su nombre, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
433
+ );
434
+ return [{ role: 'developer', content: parts.join('\n') }];
435
+ }
436
+
391
437
  _buildSkillCatalogMessage(skillCatalog) {
392
438
  const described = (Array.isArray(skillCatalog) ? skillCatalog : []).filter((skill) => skill?.name && skill?.description);
393
439
  if (!described.length) return [];
@@ -0,0 +1,93 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const { getMessages } = require('../../services/messageService');
4
+ const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
5
+ const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
6
+ const { readPendingReminderForPatient } = require('./clinicalAirtableService');
7
+
8
+ const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
9
+ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
10
+ const TRIGGERED_BY_PREFIX = 'send_reminder:';
11
+ const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
12
+ const EXCERPT_LENGTH = 160;
13
+
14
+ const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
15
+
16
+ function mandatoryInstruction(firstName, question) {
17
+ return `${firstName || 'La paciente'} no ha vuelto a escribir y quedó un tema abierto que querías retomar. Esto es lo que decidiste preguntarle: "${question}".
18
+
19
+ Antes de escribir, revisa la conversación desde que decidiste preguntarlo. Si ya lo respondió — a ti o al equipo —, no se lo vuelvas a preguntar: retoma desde lo que dijo y pregunta solo lo que siga faltando; si ya no falta nada, cierra en una línea breve y cálida. No le preguntes si el equipo ya la contactó o ya le dio indicaciones: eso no te toca a ti; si tu pregunta lo incluía, quita esa parte.
20
+
21
+ Escríbele tú, de forma breve y natural, en tu tono de siempre, como quien retoma algo pendiente de una conversación. NO digas que pidió un recordatorio ni que se lo prometiste — no lo hizo. No menciones alertas, planes, seguimientos programados ni nada del sistema. No repitas un mensaje que ya le enviaste. Si contesta, sigue la conversación con normalidad.`;
22
+ }
23
+
24
+ async function recentCheckIns(code, now) {
25
+ const rows = await getMessages(
26
+ {
27
+ numero: code,
28
+ from_me: true,
29
+ createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
30
+ $or: [
31
+ { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
32
+ { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
33
+ ],
34
+ },
35
+ { sort: { createdAt: 1 }, select: 'createdAt' },
36
+ );
37
+ return (rows || []).map((row) => new Date(row.createdAt).toISOString());
38
+ }
39
+
40
+ async function lastMessage(code, now, fromMe) {
41
+ const [row] = await getMessages(
42
+ { numero: code, from_me: fromMe, origin: { $ne: 'instruction' }, createdAt: { $lt: now } },
43
+ { sort: { createdAt: -1 }, limit: 1, select: 'createdAt plainBody body' },
44
+ ) || [];
45
+ if (!row) return null;
46
+ const text = String(row.plainBody || row.body || '').trim();
47
+ return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
48
+ }
49
+
50
+ async function recentExchange(code, now) {
51
+ const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
52
+ const [patient, own, ownToday] = await Promise.all([
53
+ lastMessage(code, now, false),
54
+ lastMessage(code, now, true),
55
+ getMessages({ numero: code, from_me: true, origin: { $ne: 'instruction' }, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
56
+ ]);
57
+ return { patient, own, ownMessagesToday: (ownToday || []).length };
58
+ }
59
+
60
+ async function briefFor(code, now, checkIn) {
61
+ const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
62
+ return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
63
+ }
64
+
65
+ async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
66
+ let checkIn;
67
+ if (type === 'contingencia') {
68
+ const planId = String(reminderId).replace(/-patient$/, '');
69
+ const net = (await readActiveNets(code)).find((candidate) => candidate.carePlan.planId === planId);
70
+ if (!net) return { mode: 'stale', reason: 'net_not_active' };
71
+ const urgency = escalationUrgencyOf(net);
72
+ const netQuestion = net.patientReminder?.message || question;
73
+ if (MANDATORY_URGENCIES.has(urgency)) {
74
+ return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
75
+ }
76
+ checkIn = {
77
+ type,
78
+ question: netQuestion,
79
+ concern: net.carePlan.concern,
80
+ awaiting: net.carePlan.awaitingCharacterization,
81
+ armedAt: net.carePlan.createdAt,
82
+ urgency,
83
+ };
84
+ return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
85
+ }
86
+
87
+ const plan = await readPendingReminderForPatient({ code, reminderId });
88
+ if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
89
+ checkIn = { type, question: plan.message || question, concern: plan.windowReasoning, awaiting: null, armedAt: null, urgency: null };
90
+ return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
91
+ }
92
+
93
+ module.exports = { checkInTriggeredBy, planCheckInDue };
@@ -552,6 +552,34 @@ async function markReminderSent({ code, reminderId, trace = null }) {
552
552
  });
553
553
  }
554
554
 
555
+ async function settleCheckInRow({ code, reminderId, sent = false, reason = null, requireActive = false, onlyIfDispatched = false, trace = null }) {
556
+ if (!code || !reminderId) return false;
557
+ return auditedWrite({
558
+ trace,
559
+ code,
560
+ table: 'reminder',
561
+ meta: { reminderId, lifecycle: sent ? 'sent' : 'stood_down' },
562
+ write: async () => {
563
+ const fields = sent ? { is_active: false, is_sent: true } : { is_active: false, stand_down_reason: reason };
564
+ const updated = await airtableService.updateRecordByFilter(
565
+ Monitoreo_ID,
566
+ 'reminder',
567
+ `AND(${[
568
+ fieldEquals('whatsapp_id', code),
569
+ fieldEquals('schedule_id', reminderId),
570
+ 'IF({is_sent}, "true", "false") = "false"',
571
+ requireActive ? 'IF({is_active}, "true", "false") = "true"' : null,
572
+ onlyIfDispatched ? fieldEquals('stand_down_reason', 'dispatched') : null,
573
+ ].filter(Boolean).join(', ')})`,
574
+ fields,
575
+ code,
576
+ );
577
+ if (!updated?.length) throw new Error(`check-in ${reminderId} was not settled`);
578
+ return updated;
579
+ },
580
+ });
581
+ }
582
+
555
583
  async function recordContingencyEscalation({ code, trace, planId, dueAtUtc, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern, message, actionRequested, priority = null, isLive = null }) {
556
584
  return auditedWrite({
557
585
  trace,
@@ -698,6 +726,7 @@ module.exports = {
698
726
  cancelFollowUp,
699
727
  hasCheckInNear,
700
728
  markReminderSent,
729
+ settleCheckInRow,
701
730
  recordContingencyEscalation,
702
731
  cancelContingencyRows,
703
732
  standDownAllPendingRows,
@@ -278,6 +278,12 @@ const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireCeiling
278
278
  patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
279
279
  });
280
280
 
281
+ function escalationUrgencyOf(net) {
282
+ if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
283
+ const silence = net?.patientReminder?.firesAfterSilenceMinutes;
284
+ return Object.keys(ESCALATION_SILENCE_MINUTES).find((level) => ESCALATION_SILENCE_MINUTES[level] === silence) || null;
285
+ }
286
+
281
287
  async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
282
288
  const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
283
289
  if (!silence) return { armed: false, reason: 'urgency_not_covered' };
@@ -462,4 +468,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
462
468
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
463
469
  }
464
470
 
465
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
471
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
@@ -8,11 +8,13 @@ const DECISIONS = ['write', 'hold'];
8
8
 
9
9
  const HOLD_REASONS = [
10
10
  'already_wrote_today',
11
+ 'answered_since_armed',
11
12
  'case_closed_nothing_pending',
12
13
  'contingency_already_armed',
13
14
  'no_change_since_last_outreach',
14
15
  'no_utility_anchor',
15
16
  'recent_patient_activity',
17
+ 'rescheduled_for_cadence',
16
18
  'unanswered_outreach_limit',
17
19
  'other',
18
20
  ];
@@ -8,7 +8,8 @@ const { AssistantMessageError, injectAssistantMessages } = require('../services/
8
8
  const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
9
9
 
10
10
  const { getRecordByFilter } = require('../services/airtableService');
11
- const { sendMessage, processInstruction, processSystemMessage } = require('../core/NexusMessaging');
11
+ const { sendMessage, processInstruction, processSystemMessage, processCheckInDue, isDraining } = require('../core/NexusMessaging');
12
+ const { CHECK_IN_TYPES } = require('../clinical/config/checkInConfig');
12
13
  const { createAssistant, switchAssistant } = require('../clinical');
13
14
  const { cancelPendingFollowUps } = require('../clinical/services/clinicalAirtableService');
14
15
 
@@ -70,6 +71,18 @@ const addInsAssistantController = async (req, res) => {
70
71
  }
71
72
  };
72
73
 
74
+ const checkInDueController = async (req, res) => {
75
+ const { code, reminder_id: reminderId, type, description, first_name: firstName } = req.body || {};
76
+ if (!code || !reminderId) return res.status(400).json({ success: false, error: 'code and reminder_id are required' });
77
+ if (!CHECK_IN_TYPES.includes(type)) return res.status(400).json({ success: false, error: `type must be one of ${CHECK_IN_TYPES.join(' | ')}` });
78
+ if (isDraining()) return res.status(503).json({ success: false, error: 'draining' });
79
+
80
+ processCheckInDue(code, { reminderId, type, question: description || '', firstName: firstName || null })
81
+ .then((result) => logger.info('[AssistantController] Check-in settled', { code, reminderId, ...result }))
82
+ .catch((error) => logger.error('[AssistantController] Check-in failed', { error: error.message, code, reminderId }));
83
+ return res.status(202).json({ success: true, accepted: true });
84
+ };
85
+
73
86
  const addMsgAssistantController = async (req, res) => {
74
87
  try {
75
88
  await injectAssistantMessages(req.body, processSystemMessage);
@@ -148,6 +161,7 @@ const switchAssistantController = async (req, res) => {
148
161
 
149
162
  module.exports = {
150
163
  addInsAssistantController,
164
+ checkInDueController,
151
165
  addMsgAssistantController,
152
166
  createAssistantController,
153
167
  doNotAlertController,
@@ -45,10 +45,12 @@ const {
45
45
  readPendingReminderForPatient,
46
46
  cancelPendingFollowUps,
47
47
  markReminderSent,
48
+ settleCheckInRow,
48
49
  cancelFollowUp,
49
50
  hasCheckInNear,
50
51
  } = require('../clinical/services/clinicalAirtableService');
51
- const { cancelContingencies } = require('../clinical/services/contingencyDispatchService');
52
+ const { cancelContingencies, applyContingencyEvent } = require('../clinical/services/contingencyDispatchService');
53
+ const { checkInTriggeredBy, planCheckInDue } = require('../clinical/services/checkInDueService');
52
54
  const { isContingencyCancelOnReplyLive } = require('../clinical/flags/contingencyFlags');
53
55
  const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
54
56
 
@@ -484,7 +486,7 @@ class NexusMessaging {
484
486
 
485
487
  async sendAssistantReply(messageData) {
486
488
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
487
- if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
489
+ if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
488
490
  const contact = await replyContactFor(messageData.code);
489
491
  if (contact) messageData = { ...messageData, ...contact };
490
492
  }
@@ -512,7 +514,7 @@ class NexusMessaging {
512
514
  // Proactive outreach lands days after the patient last wrote, so the session is usually closed.
513
515
  // Waiting for Twilio 63016 to bounce would delay every message in the batch by a round-trip.
514
516
  if (messageData.preemptiveWindowRoute && this._needsTemplateRoute(messageData)
515
- && !(await isWithin24HourWindow(messageData.code))) {
517
+ && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
516
518
  try {
517
519
  messageData = await buildOutreachCarrier(messageData, {
518
520
  provider: this.provider,
@@ -1000,6 +1002,7 @@ class NexusMessaging {
1000
1002
  firstName = null,
1001
1003
  reminderType = 'seguimiento',
1002
1004
  reminderPrefix = null,
1005
+ replyToContact = false,
1003
1006
  dryRun = false,
1004
1007
  } = {}) {
1005
1008
  const outreachStartedAt = new Date().toISOString();
@@ -1030,7 +1033,7 @@ class NexusMessaging {
1030
1033
  turnKind: TURN_KIND.PROACTIVE_OUTREACH,
1031
1034
  outreachBrief: brief,
1032
1035
  preemptiveWindowRoute: true,
1033
- outreachCarrier: { reminderType, reminderPrefix, firstName },
1036
+ outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1034
1037
  outreachStartedAt,
1035
1038
  // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1036
1039
  triggeredBy: triggeredBy || null,
@@ -1119,6 +1122,62 @@ class NexusMessaging {
1119
1122
  };
1120
1123
  }
1121
1124
 
1125
+ async processCheckInDue(code, { reminderId, type, question = '', firstName = null } = {}) {
1126
+ if (!code || !reminderId) throw new Error('code and reminderId are required');
1127
+ const claim = await acquireSendClaim({ idempotencyKey: `checkin-due:${reminderId}`, code });
1128
+ if (!claim.acquired) return { decision: 'skipped', holdReason: 'duplicate', sent: false };
1129
+
1130
+ let plan = null;
1131
+ let dispatched = false;
1132
+ try {
1133
+ plan = await planCheckInDue({ code, reminderId, type, question, firstName });
1134
+ if (plan.mode === 'stale') {
1135
+ await settleCheckInRow({ code, reminderId, reason: plan.reason });
1136
+ await completeSendClaim(claim.claimId);
1137
+ return { decision: 'skipped', holdReason: plan.reason, sent: false };
1138
+ }
1139
+ dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1140
+ if (!dispatched) {
1141
+ await completeSendClaim(claim.claimId);
1142
+ return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1143
+ }
1144
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1145
+
1146
+ const triggeredBy = checkInTriggeredBy(reminderId);
1147
+ let result;
1148
+ if (plan.mode === 'mandatory') {
1149
+ const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1150
+ const sent = outcome === 'sent' || outcome === 'unknown';
1151
+ result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1152
+ } else {
1153
+ const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1154
+ result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1155
+ }
1156
+
1157
+ const settled = result.sent
1158
+ ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1159
+ : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1160
+ if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1161
+ await completeSendClaim(claim.claimId);
1162
+ return result;
1163
+ } catch (error) {
1164
+ logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1165
+ if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1166
+ await releaseSendClaim(claim.claimId);
1167
+ throw error;
1168
+ }
1169
+ }
1170
+
1171
+ async _fireCheckInNet(code, planId, reminderId) {
1172
+ if (!planId) return;
1173
+ try {
1174
+ const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1175
+ if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1176
+ } catch (error) {
1177
+ logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1178
+ }
1179
+ }
1180
+
1122
1181
  async _retireSkippedFollowUp(code, reminderId, holdReason) {
1123
1182
  const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1124
1183
  if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
@@ -1348,6 +1407,10 @@ const processOutreach = async (code, options) => {
1348
1407
  return await requireDefaultInstance().processOutreach(code, options);
1349
1408
  };
1350
1409
 
1410
+ const processCheckInDue = async (code, options) => {
1411
+ return await requireDefaultInstance().processCheckInDue(code, options);
1412
+ };
1413
+
1351
1414
  const processScheduledFollowUp = async (code, options) => {
1352
1415
  return await requireDefaultInstance().processScheduledFollowUp(code, options);
1353
1416
  };
@@ -1356,6 +1419,8 @@ const processSystemMessage = async (code, messages, role, options) => {
1356
1419
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
1357
1420
  };
1358
1421
 
1422
+ const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1423
+
1359
1424
  const getEventBus = () => getDefaultInstance()?.getEventBus();
1360
1425
 
1361
1426
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -1369,8 +1434,10 @@ module.exports = {
1369
1434
  scheduleTemplateApproval,
1370
1435
  processInstruction,
1371
1436
  processOutreach,
1437
+ processCheckInDue,
1372
1438
  processScheduledFollowUp,
1373
1439
  processSystemMessage,
1440
+ isDraining,
1374
1441
  setDefaultInstance,
1375
1442
  getDefaultInstance,
1376
1443
  requireDefaultInstance,
package/lib/index.d.ts CHANGED
@@ -275,6 +275,7 @@ declare module '@peopl-health/nexus' {
275
275
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
276
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
277
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
278
+ processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
278
279
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
279
280
  isConnected(): boolean;
280
281
  shutdown(options?: ShutdownOptions): Promise<DrainResult>;
@@ -467,6 +468,15 @@ declare module '@peopl-health/nexus' {
467
468
  lastInboundAt?: string | null;
468
469
  lastOutboundAt?: string | null;
469
470
  lastOutreach?: string | null;
471
+ checkIn?: { type: string; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null } | null;
472
+ recentCheckIns?: string[];
473
+ }
474
+
475
+ export interface CheckInDueResult {
476
+ decision: 'write' | 'hold' | 'skipped';
477
+ holdReason: string | null;
478
+ nextCheckAt?: string | null;
479
+ sent: boolean;
470
480
  }
471
481
 
472
482
  export interface OutreachDecision {
@@ -2,6 +2,7 @@ const express = require('express');
2
2
 
3
3
  const assistantRouteDefinitions = {
4
4
  'POST /add-instruction': 'addInsAssistantController',
5
+ 'POST /check-in-due': 'checkInDueController',
5
6
  'POST /add-msg': 'addMsgAssistantController',
6
7
  'POST /create': 'createAssistantController',
7
8
  'POST /info': 'getInfoAssistantController',
@@ -195,6 +196,7 @@ const officeAssistantController = require('../controllers/officeAssistantControl
195
196
  const builtInControllers = {
196
197
  // Assistant controllers
197
198
  addInsAssistantController: assistantController.addInsAssistantController,
199
+ checkInDueController: assistantController.checkInDueController,
198
200
  addMsgAssistantController: assistantController.addMsgAssistantController,
199
201
  createAssistantController: assistantController.createAssistantController,
200
202
  getInfoAssistantController: assistantController.getInfoAssistantController,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.73.1",
3
+ "version": "5.74.0-dev.15344",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",