@peopl-health/nexus 5.74.0-dev.15350 → 5.75.0-dev.15396

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.
@@ -108,6 +108,7 @@ class AssistantProcessor {
108
108
  if (ctx) {
109
109
  ctx.outreachReminderType = runOptions.outreachCarrier?.reminderType || null;
110
110
  ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
111
+ ctx.checkInOtherPlans = runOptions.outreachBrief?.checkIn?.otherPlans ?? null;
111
112
  }
112
113
  if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
113
114
  if (runOptions.prePromptResult?.metadata) {
@@ -0,0 +1,3 @@
1
+ const CHECK_IN_TYPES = ['contingencia', 'seguimiento'];
2
+
3
+ module.exports = { CHECK_IN_TYPES };
@@ -19,10 +19,13 @@ 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');
25
26
 
27
+ const EXCHANGE_LINE_LENGTH = 400;
28
+
26
29
  const CONSUMER_SIGNALS_KEY = 'consumer';
27
30
 
28
31
  const { getToolSchemas: getRegistrySchemas } = require('../../services/toolRegistryService');
@@ -348,13 +351,15 @@ class BaseLLMProvider {
348
351
  if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
349
352
 
350
353
  const lines = (entries) => entries
351
- .map(([label, value]) => {
354
+ .map(([label, value, maxLength]) => {
352
355
  const raw = Array.isArray(value) ? value.join(', ') : value;
353
- const text = sanitizeInlineText(String(raw ?? '')).trim();
356
+ const text = sanitizeInlineText(String(raw ?? ''), maxLength).trim();
354
357
  return text ? `- ${label}: ${text}` : null;
355
358
  })
356
359
  .filter(Boolean);
357
360
 
361
+ if (outreachBrief.checkIn) return this._buildCheckInDueMessage(outreachBrief, lines);
362
+
358
363
  const why = lines([
359
364
  ['último triaje contestado', outreachBrief.lastTriageAt],
360
365
  ['grado máximo en ese triaje', outreachBrief.maxGrade],
@@ -388,6 +393,49 @@ class BaseLLMProvider {
388
393
  return [{ role: 'developer', content: parts.join('\n') }];
389
394
  }
390
395
 
396
+ _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
397
+ const ago = (at) => {
398
+ const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
399
+ if (!Number.isFinite(minutes) || minutes < 0) return '';
400
+ return minutes < 60 ? ` (hace ${minutes} min)` : ` (hace ${Math.floor(minutes / 60)} h ${minutes % 60} min)`;
401
+ };
402
+ const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
403
+ const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
404
+ const pending = lines([
405
+ ['lo que querías preguntarle', checkIn.question],
406
+ ['por qué quedó abierto', checkIn.concern],
407
+ ['qué dato esperabas', checkIn.awaiting],
408
+ ['desde', local(checkIn.armedAt)],
409
+ ['nivel de la escalación', checkIn.urgency],
410
+ ]);
411
+ const conversation = lines([
412
+ ['su último mensaje', said(exchange?.patient), EXCHANGE_LINE_LENGTH],
413
+ ['tu último mensaje (tuyo o del equipo)', said(exchange?.own), EXCHANGE_LINE_LENGTH],
414
+ ['mensajes tuyos o del equipo hoy', exchange ? String(exchange.ownMessagesToday) : null],
415
+ ]);
416
+ const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
417
+ const parts = [
418
+ '[CHECK-IN QUE VENCE (prioritario) para este turno]',
419
+ '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.',
420
+ '', '## Qué quedó pendiente', ...pending,
421
+ ];
422
+ if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
423
+ parts.push(
424
+ '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
425
+ '',
426
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
427
+ '- 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.',
428
+ '- 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.',
429
+ '- 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.',
430
+ '- 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.',
431
+ '- 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.',
432
+ '- 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.',
433
+ '- 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ó.',
434
+ '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.',
435
+ );
436
+ return [{ role: 'developer', content: parts.join('\n') }];
437
+ }
438
+
391
439
  _buildSkillCatalogMessage(skillCatalog) {
392
440
  const described = (Array.isArray(skillCatalog) ? skillCatalog : []).filter((skill) => skill?.name && skill?.description);
393
441
  if (!described.length) return [];
@@ -0,0 +1,124 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const { getMessages } = require('../../services/messageService');
4
+ const { checkInsPausedUntil } = require('../../services/threadService');
5
+ const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
6
+ const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
7
+ const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
8
+ const { logger } = require('../../utils/logger');
9
+
10
+ const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
11
+ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
12
+ const TRIGGERED_BY_PREFIX = 'send_reminder:';
13
+ const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
14
+ const EXCERPT_LENGTH = 160;
15
+ const OWN_ORIGINS = ['assistant', 'whatsapp_platform'];
16
+ const LAST_MESSAGE_SCAN = 5;
17
+
18
+ const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
19
+
20
+ function mandatoryInstruction(firstName, question) {
21
+ 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}".
22
+
23
+ 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.
24
+
25
+ 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.`;
26
+ }
27
+
28
+ async function recentCheckIns(code, now) {
29
+ const rows = await getMessages(
30
+ {
31
+ numero: code,
32
+ from_me: true,
33
+ createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
34
+ $or: [
35
+ { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
36
+ { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
37
+ ],
38
+ },
39
+ { sort: { createdAt: 1 }, select: 'createdAt' },
40
+ );
41
+ return (rows || []).map((row) => new Date(row.createdAt).toISOString());
42
+ }
43
+
44
+ const originFilter = (fromMe) => (fromMe ? { $in: OWN_ORIGINS } : { $ne: 'instruction' });
45
+
46
+ async function lastMessage(code, now, fromMe) {
47
+ const rows = await getMessages(
48
+ { numero: code, from_me: fromMe, origin: originFilter(fromMe), createdAt: { $lt: now } },
49
+ { sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
50
+ ) || [];
51
+ const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
52
+ if (!row) return null;
53
+ const text = String(row.plainBody || row.body || '').trim();
54
+ return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
55
+ }
56
+
57
+ async function recentExchange(code, now) {
58
+ const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
59
+ const [patient, own, ownToday] = await Promise.all([
60
+ lastMessage(code, now, false),
61
+ lastMessage(code, now, true),
62
+ getMessages({ numero: code, from_me: true, origin: originFilter(true), createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
63
+ ]);
64
+ return { patient, own, ownMessagesToday: (ownToday || []).length };
65
+ }
66
+
67
+ async function briefFor(code, now, checkIn) {
68
+ const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
69
+ return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
70
+ }
71
+
72
+ async function countOtherPlans(code, { planId = null, reminderId, nets = null }) {
73
+ try {
74
+ const [activeNets, followUps] = await Promise.all([nets || readActiveNets(code), readPendingFollowUpsForPatient({ code })]);
75
+ const otherNets = (activeNets || []).filter((candidate) => candidate.carePlan.planId !== planId && candidate.carePlan.status === 'armed');
76
+ const otherFollowUps = (followUps || []).filter((plan) => plan.reminderId !== reminderId);
77
+ return otherNets.length + otherFollowUps.length;
78
+ } catch (error) {
79
+ logger.warn('[checkInDue] other plans unreadable; stand-down left unverified', { reminderId, error: error.message });
80
+ return null;
81
+ }
82
+ }
83
+
84
+ async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
85
+ let checkIn;
86
+ if (type === 'contingencia') {
87
+ const planId = String(reminderId).replace(/-patient$/, '');
88
+ const nets = await readActiveNets(code);
89
+ const net = nets.find((candidate) => candidate.carePlan.planId === planId);
90
+ if (!net) return { mode: 'stale', reason: 'net_not_active' };
91
+ const urgency = escalationUrgencyOf(net);
92
+ const netQuestion = net.patientReminder?.message || question;
93
+ if (MANDATORY_URGENCIES.has(urgency)) {
94
+ return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
95
+ }
96
+ if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused', planId };
97
+ checkIn = {
98
+ type,
99
+ question: netQuestion,
100
+ concern: net.carePlan.concern,
101
+ awaiting: net.carePlan.awaitingCharacterization,
102
+ armedAt: net.carePlan.createdAt,
103
+ urgency,
104
+ otherPlans: await countOtherPlans(code, { planId, reminderId, nets }),
105
+ };
106
+ return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
107
+ }
108
+
109
+ const plan = await readPendingReminderForPatient({ code, reminderId });
110
+ if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
111
+ if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
112
+ checkIn = {
113
+ type,
114
+ question: plan.message || question,
115
+ concern: plan.windowReasoning,
116
+ awaiting: null,
117
+ armedAt: null,
118
+ urgency: null,
119
+ otherPlans: await countOtherPlans(code, { reminderId }),
120
+ };
121
+ return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
122
+ }
123
+
124
+ 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 };
@@ -2,12 +2,13 @@ const moment = require('moment-timezone');
2
2
 
3
3
  const { isShadowRun } = require('../helpers/shadowHelper');
4
4
  const { dispatchReminder } = require('../services/reminderDispatchService');
5
- const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp } = require('../services/clinicalAirtableService');
5
+ const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp, cancelPendingFollowUps } = require('../services/clinicalAirtableService');
6
6
  const { isWithinTriageProtectionWindow } = require('../services/outreachSweepService');
7
7
  const { UTILITY_BASES, sanitizeVariable } = require('../services/outreachCarrierService');
8
8
  const { logger } = require('../../utils/logger');
9
9
  const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
10
10
  const { botIsPaused } = require('../../helpers/pausedThreadHelper');
11
+ const { setCheckInsPausedUntil, checkInsPausedUntil } = require('../../services/threadService');
11
12
 
12
13
  const definition = {
13
14
  name: 'schedulePatientReminder',
@@ -31,8 +32,8 @@ const definition = {
31
32
  },
32
33
  reminder_action_type: {
33
34
  type: 'string',
34
- enum: ['create', 'update', 'cancel'],
35
- description: '\'create\' = new reminder. \'update\' = modify an existing reminder (change date/time/description) — pass its id in `reminder_id`. \'cancel\' = retire a pending seguimiento that the conversation already answered or made unnecessary — pass its id in `reminder_id`; the date and description are ignored.',
35
+ enum: ['create', 'update', 'cancel', 'pause_checkins'],
36
+ description: '\'create\' = new reminder. \'update\' = modify an existing reminder (change date/time/description) — pass its id in `reminder_id`. \'cancel\' = retire a pending seguimiento that the conversation already answered or made unnecessary — pass its id in `reminder_id`; the date and description are ignored. \'pause_checkins\' = the patient asked to receive fewer messages: no seguimiento or contingency check-in reaches the patient until `reminder_date` (at most 30 days ahead; 14 days if the patient gave no date), pending seguimientos are retired, and the patient can still write at any time; put the request in `reminder_description`. stat/asap escalation check-ins and the patient\'s own medication, appointment or exam reminders are not paused.',
36
37
  },
37
38
  reminder_id: {
38
39
  type: ['string', 'null'],
@@ -53,6 +54,8 @@ const REMINDER_TYPES = definition.parameters.properties.reminder_type.enum;
53
54
  const ACTION_TYPES = definition.parameters.properties.reminder_action_type.enum;
54
55
 
55
56
  const MAX_FOLLOW_UP_LEAD_HOURS = 48;
57
+ const DEFAULT_PAUSE_DAYS = 14;
58
+ const MAX_PAUSE_DAYS = 30;
56
59
  const ROUTINE_OUTREACH_START_HOUR = 11;
57
60
  const ROUTINE_OUTREACH_END_HOUR = 21;
58
61
  const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
@@ -84,6 +87,7 @@ async function handler(args = {}, context = {}) {
84
87
 
85
88
  const requestedAction = (args?.reminder_action_type || '').toLowerCase();
86
89
  if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
90
+ if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
87
91
 
88
92
  const reminderDate = (args?.reminder_date || '').trim();
89
93
  const description = sanitizeVariable(args?.reminder_description || '');
@@ -135,6 +139,12 @@ async function handler(args = {}, context = {}) {
135
139
  if (isRoutineOutreach && !isWithinHourWindow(fireMoment.toDate(), { timeZone, startHour: ROUTINE_OUTREACH_START_HOUR, endHour: ROUTINE_OUTREACH_END_HOUR })) {
136
140
  return JSON.stringify({ success: false, error: `routine outreach must go out between ${ROUTINE_OUTREACH_START_HOUR}:00 and ${ROUTINE_OUTREACH_END_HOUR}:00 patient time; choose a time in that range.`, data: {} });
137
141
  }
142
+ if (isRoutineOutreach && runtime.patientCode) {
143
+ const pausedUntil = await checkInsPausedUntil(runtime.patientCode);
144
+ if (pausedUntil && fireMoment.toDate() < pausedUntil) {
145
+ return JSON.stringify({ success: false, error: 'checkins_paused — the patient asked for fewer messages; do not schedule a seguimiento before the pause ends.', data: { paused_until: moment(pausedUntil).tz(timeZone).format('YYYY-MM-DDTHH:mm') } });
146
+ }
147
+ }
138
148
  if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
139
149
  if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
140
150
  return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
@@ -226,6 +236,30 @@ async function handler(args = {}, context = {}) {
226
236
  }
227
237
  }
228
238
 
239
+ async function pauseCheckIns(args, runtime) {
240
+ const { patientCode, trace } = runtime;
241
+ const now = moment.tz(DEFAULT_TIMEZONE);
242
+ const rawDate = String(args?.reminder_date || '').trim();
243
+ const until = rawDate
244
+ ? moment.tz(rawDate, ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD'], true, DEFAULT_TIMEZONE)
245
+ : now.clone().add(DEFAULT_PAUSE_DAYS, 'days');
246
+ if (!until.isValid() || !until.isAfter(now)) {
247
+ return JSON.stringify({ success: false, error: 'pause_checkins reminder_date must be a future patient-local date (YYYY-MM-DDTHH:mm), or empty for 14 days.', data: {} });
248
+ }
249
+ if (until.isAfter(now.clone().add(MAX_PAUSE_DAYS, 'days'))) {
250
+ return JSON.stringify({ success: false, error: `pause_checkins reminder_date must be at most ${MAX_PAUSE_DAYS} days ahead.`, data: {} });
251
+ }
252
+ if (patientCode && !isShadowRun()) {
253
+ await setCheckInsPausedUntil(patientCode, until.toDate());
254
+ if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused' })) {
255
+ logger.warn('[schedulePatientReminder] pending seguimientos were not retired on pause', { patientCode });
256
+ }
257
+ }
258
+ const existing = Array.isArray(trace.signals?.reminderIntents) ? trace.signals.reminderIntents : [];
259
+ trace.setSignals({ reminderIntents: [...existing, { reminderId: null, reminderType: 'seguimiento', actionType: 'pause_checkins', pausedUntil: until.toISOString(), channel: 'whatsapp' }] });
260
+ return JSON.stringify({ success: true, data: { action_type: 'pause_checkins', paused_until: until.format('YYYY-MM-DDTHH:mm'), time_zone: DEFAULT_TIMEZONE } });
261
+ }
262
+
229
263
  async function cancelSeguimiento(args, runtime) {
230
264
  const reminderId = typeof args?.reminder_id === 'string' ? args.reminder_id.trim() : '';
231
265
  if (!reminderId) {
@@ -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
  ];
@@ -84,6 +86,11 @@ async function handler(args = {}, context = {}) {
84
86
  holdReason = HOLD_REASONS.includes(raw) ? raw : 'other';
85
87
  }
86
88
 
89
+ const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
90
+ if (holdReason === 'contingency_already_armed' && !nextCheckAt && runtime.checkInOtherPlans === 0) {
91
+ return JSON.stringify({ success: false, error: 'contingency_already_armed needs another active net or pending seguimiento, and this check-in has none: write now, or schedule a seguimiento and hold with rescheduled_for_cadence.', data: {} });
92
+ }
93
+
87
94
  let utilityBasis = null;
88
95
  if (rawDecision === 'write') {
89
96
  const rawBasis = String(args?.utility_basis || '').trim().toLowerCase();
@@ -93,8 +100,6 @@ async function handler(args = {}, context = {}) {
93
100
  utilityBasis = rawBasis;
94
101
  }
95
102
 
96
- const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
97
-
98
103
  const decision = {
99
104
  decision: rawDecision,
100
105
  rationale: rationale.slice(0, 400),
@@ -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,63 @@ 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, requireActive: true });
1136
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1137
+ await completeSendClaim(claim.claimId);
1138
+ return { decision: 'skipped', holdReason: plan.reason, sent: false };
1139
+ }
1140
+ dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1141
+ if (!dispatched) {
1142
+ await completeSendClaim(claim.claimId);
1143
+ return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1144
+ }
1145
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1146
+
1147
+ const triggeredBy = checkInTriggeredBy(reminderId);
1148
+ let result;
1149
+ if (plan.mode === 'mandatory') {
1150
+ const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1151
+ const sent = outcome === 'sent' || outcome === 'unknown';
1152
+ result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1153
+ } else {
1154
+ const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1155
+ result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1156
+ }
1157
+
1158
+ const settled = result.sent
1159
+ ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1160
+ : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1161
+ if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1162
+ await completeSendClaim(claim.claimId);
1163
+ return result;
1164
+ } catch (error) {
1165
+ logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1166
+ if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1167
+ await releaseSendClaim(claim.claimId);
1168
+ throw error;
1169
+ }
1170
+ }
1171
+
1172
+ async _fireCheckInNet(code, planId, reminderId) {
1173
+ if (!planId) return;
1174
+ try {
1175
+ const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1176
+ if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1177
+ } catch (error) {
1178
+ logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1179
+ }
1180
+ }
1181
+
1122
1182
  async _retireSkippedFollowUp(code, reminderId, holdReason) {
1123
1183
  const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1124
1184
  if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
@@ -1348,6 +1408,10 @@ const processOutreach = async (code, options) => {
1348
1408
  return await requireDefaultInstance().processOutreach(code, options);
1349
1409
  };
1350
1410
 
1411
+ const processCheckInDue = async (code, options) => {
1412
+ return await requireDefaultInstance().processCheckInDue(code, options);
1413
+ };
1414
+
1351
1415
  const processScheduledFollowUp = async (code, options) => {
1352
1416
  return await requireDefaultInstance().processScheduledFollowUp(code, options);
1353
1417
  };
@@ -1356,6 +1420,8 @@ const processSystemMessage = async (code, messages, role, options) => {
1356
1420
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
1357
1421
  };
1358
1422
 
1423
+ const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1424
+
1359
1425
  const getEventBus = () => getDefaultInstance()?.getEventBus();
1360
1426
 
1361
1427
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -1369,8 +1435,10 @@ module.exports = {
1369
1435
  scheduleTemplateApproval,
1370
1436
  processInstruction,
1371
1437
  processOutreach,
1438
+ processCheckInDue,
1372
1439
  processScheduledFollowUp,
1373
1440
  processSystemMessage,
1441
+ isDraining,
1374
1442
  setDefaultInstance,
1375
1443
  getDefaultInstance,
1376
1444
  requireDefaultInstance,
package/lib/index.d.ts CHANGED
@@ -274,7 +274,8 @@ declare module '@peopl-health/nexus' {
274
274
  getWorkflowRunner(): WorkflowRunner;
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
- processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
277
+ processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: 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,17 @@ 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; otherPlans?: number | null } | null;
472
+ recentCheckIns?: string[];
473
+ exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number } | null;
474
+ asOf?: string | null;
475
+ }
476
+
477
+ export interface CheckInDueResult {
478
+ decision: 'write' | 'hold' | 'skipped';
479
+ holdReason: string | null;
480
+ nextCheckAt?: string | null;
481
+ sent: boolean;
470
482
  }
471
483
 
472
484
  export interface OutreachDecision {
@@ -11,6 +11,7 @@ const threadSchema = new mongoose.Schema({
11
11
  nombre: { type: String, default: null },
12
12
  stopped: { type: Boolean, default: false },
13
13
  outreachOptOut: { type: Boolean, default: false },
14
+ checkInsPausedUntil: { type: Date, default: null },
14
15
  pausedAt: { type: Date, default: null },
15
16
  deceasedAt: { type: Date, default: null },
16
17
  programStatusBeforeDeath: { type: String, default: null },
@@ -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,
@@ -51,6 +51,13 @@ const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } =
51
51
 
52
52
  const setThreadDoNotAlert = async (code, doNotAlert, through = null) => Thread.updateMany({ code }, { $set: { doNotAlertThrough: doNotAlert ? (through || new Date()) : null } });
53
53
 
54
+ const setCheckInsPausedUntil = async (code, until) => Thread.updateMany({ code }, { $set: { checkInsPausedUntil: until } });
55
+
56
+ const checkInsPausedUntil = async (code, now = new Date()) => {
57
+ const thread = await Thread.findOne({ code, checkInsPausedUntil: { $gt: now } }).select('checkInsPausedUntil').lean();
58
+ return thread?.checkInsPausedUntil || null;
59
+ };
60
+
54
61
  const setThreadPromptId = async (code, promptId) => {
55
62
  const updateFields = {};
56
63
  Thread.setAssistantId(updateFields, promptId);
@@ -110,5 +117,7 @@ module.exports = {
110
117
  ensureThreadExists,
111
118
  switchThreadStoppedStatus,
112
119
  setThreadDoNotAlert,
113
- setThreadPromptId
120
+ setThreadPromptId,
121
+ setCheckInsPausedUntil,
122
+ checkInsPausedUntil
114
123
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0-dev.15350",
3
+ "version": "5.75.0-dev.15396",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",