@peopl-health/nexus 6.0.13 → 6.0.14

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.
@@ -26,6 +26,7 @@ const { isPlainObject, safeParse, decodeLiteralUnicodeEscapes } = require('../..
26
26
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
27
27
 
28
28
  const EXCHANGE_LINE_LENGTH = 400;
29
+ const TRIAGE_LINE_LENGTH = 1600;
29
30
 
30
31
  const CONSUMER_SIGNALS_KEY = 'consumer';
31
32
 
@@ -400,7 +401,7 @@ class BaseLLMProvider {
400
401
  return [{ role: 'developer', content: parts.join('\n') }];
401
402
  }
402
403
 
403
- _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
404
+ _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, triage = null, asOf = null }, lines) {
404
405
  const ago = (at) => {
405
406
  const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
406
407
  if (!Number.isFinite(minutes) || minutes < 0) return '';
@@ -430,6 +431,17 @@ class BaseLLMProvider {
430
431
  '', '## Qué quedó pendiente', ...pending,
431
432
  ];
432
433
  if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
434
+ if (triage?.measured.length) {
435
+ parts.push(
436
+ '', '## Su triaje más reciente (cuestionario PRO-CTCAE)',
437
+ ...lines([
438
+ ['lo contestó', local(triage.at)],
439
+ ['lo que midió', triage.measured.map((card) => (card.grade === null ? card.name : `${card.name} (grado ${card.grade})`)).join('; '), TRIAGE_LINE_LENGTH],
440
+ ['lo que sus tarjetas ya le preguntaron', triage.asked.map((question) => `«${question}»`).join(' '), TRIAGE_LINE_LENGTH],
441
+ ]),
442
+ '- No le pidas confirmar lo que contestó en el cuestionario ni le repitas una pregunta de sus tarjetas que ya respondió en el chat. Si lo contestó hace menos de 3 h, tampoco le preguntes si tiene esos síntomas ni qué tan fuertes: pregunta lo que el cuestionario no mide, como si siguió lo que acordaron o si le funcionó.',
443
+ );
444
+ }
433
445
  parts.push(
434
446
  '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
435
447
  '',
@@ -1,11 +1,14 @@
1
1
  const moment = require('moment-timezone');
2
2
 
3
+ const { TRIAGE_RESULT_MARKER } = require('../helpers/triageResultMessageHelper');
3
4
  const { getMessages } = require('../../services/messageService');
4
5
  const { replyContactFor } = require('../../helpers/caregiverHelper');
5
6
  const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
6
7
  const { checkInsPausedUntil } = require('../../services/threadService');
7
- const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
8
- const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
8
+ const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
9
+ const { readRecommendationPlans } = require('../../fhir');
10
+ const { ARMED_BY } = require('../../shared/dtos/ContingencySafetyNet');
11
+ const { readActiveNets, escalationUrgencyOf, CHECK_IN_WINDOW } = require('./contingencyDispatchService');
9
12
  const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
10
13
  const { logger } = require('../../utils/logger');
11
14
 
@@ -15,6 +18,15 @@ const TRIGGERED_BY_PREFIX = 'send_reminder:';
15
18
  const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
16
19
  const EXCERPT_LENGTH = 160;
17
20
  const LAST_MESSAGE_SCAN = 5;
21
+ // 99.4% of post-triage exchanges end within 60 min of the cards, the longest at 127 min (1,049 triages, Oct 2026).
22
+ const TRIAGE_SETTLE_MS = 60 * 60 * 1000;
23
+ const TRIAGE_QUIET_MS = 30 * 60 * 1000;
24
+ const TRIAGE_WAIT_CAP_MS = 3 * 60 * 60 * 1000;
25
+ const TRIAGE_CONTEXT_MS = 24 * 60 * 60 * 1000;
26
+ // A triage plan is stored at most 59 min before its cards, never after (300 triages, Oct 2026).
27
+ const TRIAGE_PLAN_LEAD_MS = 60 * 60 * 1000;
28
+ // send_reminder fires up to 6 min before reminder_date, and only as the row enters that window.
29
+ const TRIGGER_LEAD_MS = 6 * 60 * 1000;
18
30
 
19
31
  const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
20
32
 
@@ -68,9 +80,63 @@ async function recentExchange(code, now) {
68
80
  return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
69
81
  }
70
82
 
83
+ async function lastTriageResultAt(code, now) {
84
+ const rows = await getMessages(
85
+ { numero: code, origin: 'system', plainBody: { $regex: TRIAGE_RESULT_MARKER }, createdAt: { $gte: new Date(now.getTime() - TRIAGE_CONTEXT_MS), $lt: now } },
86
+ { sort: { createdAt: -1 }, limit: 1, select: 'createdAt' },
87
+ );
88
+ return rows[0] ? new Date(rows[0].createdAt) : null;
89
+ }
90
+
91
+ async function triageCards(code, resultAt) {
92
+ const plans = await readRecommendationPlans({ patientId: code, since: new Date(resultAt.getTime() - TRIAGE_PLAN_LEAD_MS) });
93
+ const plan = plans.find((candidate) => candidate.origin === 'triage' && Date.parse(candidate.createdAt) <= resultAt.getTime());
94
+ if (!plan) return { measured: [], asked: [] };
95
+ const gradeOf = (element) => {
96
+ const grade = Math.max(...element.symptoms.map((symptom) => symptom.grade).filter(Number.isFinite));
97
+ return Number.isFinite(grade) ? grade : null;
98
+ };
99
+ return {
100
+ measured: plan.elements.filter((element) => element.nameShort).map((element) => ({ name: element.nameShort, grade: gradeOf(element) })),
101
+ asked: [plan.takeaways.safetyConfirmationQuestion, ...plan.elements.flatMap((element) => element.minCharacterizationVariables)].filter(Boolean),
102
+ };
103
+ }
104
+
105
+ async function triageSince(code, now) {
106
+ const resultAt = await lastTriageResultAt(code, now);
107
+ if (!resultAt) return null;
108
+ const cards = await triageCards(code, resultAt).catch((error) => {
109
+ logger.warn('[checkInDue] triage plan unreadable; the brief goes without it', { error: error.message });
110
+ return { measured: [], asked: [] };
111
+ });
112
+ return { at: resultAt.toISOString(), ...cards };
113
+ }
114
+
71
115
  async function briefFor(code, now, checkIn) {
72
- const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
73
- return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
116
+ const [sent, exchange, triage] = await Promise.all([
117
+ recentCheckIns(code, now),
118
+ recentExchange(code, now),
119
+ triageSince(code, now).catch((error) => {
120
+ logger.warn('[checkInDue] triage result unreadable; deciding without it', { reminderId: checkIn.reminderId, error: error.message });
121
+ return null;
122
+ }),
123
+ ]);
124
+ return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, ...(triage && { triage }), asOf: now.toISOString() };
125
+ }
126
+
127
+ function triageWaitUntil({ triage, exchange, asOf }, expiresAt) {
128
+ const now = Date.parse(asOf);
129
+ const resultAt = Date.parse(triage.at);
130
+ const lastWord = Math.max(0, ...[exchange.patient, exchange.own].filter(Boolean).map((message) => Date.parse(message.at)));
131
+ const settled = Math.max(resultAt + TRIAGE_SETTLE_MS, now - lastWord < TRIAGE_QUIET_MS ? lastWord + TRIAGE_QUIET_MS : 0);
132
+ const until = Math.min(settled, resultAt + TRIAGE_WAIT_CAP_MS);
133
+ if (until - now <= TRIGGER_LEAD_MS || (expiresAt && until >= Date.parse(expiresAt)) || !isWithinHourWindow(until, CHECK_IN_WINDOW)) return null;
134
+ return new Date(until).toISOString();
135
+ }
136
+
137
+ function waitOrDecide(planId, brief, { expiresAt, canWait = true }) {
138
+ const dueAt = canWait && brief.triage ? triageWaitUntil(brief, expiresAt) : null;
139
+ return dueAt ? { mode: 'defer', planId, reason: 'triage_conversation', dueAt, brief } : { mode: 'decide', planId, brief };
74
140
  }
75
141
 
76
142
  async function countOtherPlans(code, { planId = null, reminderId, nets = null }) {
@@ -110,7 +176,9 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
110
176
  urgency,
111
177
  otherPlans: await countOtherPlans(code, { planId, reminderId, nets }),
112
178
  };
113
- return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
179
+ return waitOrDecide(planId, await briefFor(code, now, checkIn), {
180
+ expiresAt: net.carePlan.expiresAt, canWait: net.carePlan.armedBy !== ARMED_BY.ESCALATION,
181
+ });
114
182
  }
115
183
 
116
184
  const plan = await readPendingReminderForPatient({ code, reminderId });
@@ -128,7 +196,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
128
196
  urgency: null,
129
197
  otherPlans: await countOtherPlans(code, { reminderId }),
130
198
  };
131
- return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
199
+ return waitOrDecide(null, await briefFor(code, now, checkIn), { expiresAt: plan.expiresAt });
132
200
  }
133
201
 
134
202
  module.exports = { checkInTriggeredBy, planCheckInDue };
@@ -600,6 +600,25 @@ async function settleCheckInRow({ code, reminderId, sent = false, reason = null,
600
600
  });
601
601
  }
602
602
 
603
+ async function deferCheckInRow({ code, reminderId, dueAt }) {
604
+ return auditedWrite({
605
+ code,
606
+ table: 'reminder',
607
+ meta: { reminderId, lifecycle: 'deferred', dueAt },
608
+ write: async () => {
609
+ const updated = await airtableService.updateRecordByFilter(
610
+ Monitoreo_ID,
611
+ 'reminder',
612
+ `AND(${fieldEquals('whatsapp_id', code)}, ${fieldEquals('schedule_id', reminderId)}, ${PENDING_ROW_FILTER})`,
613
+ { reminder_date: dueAt },
614
+ code,
615
+ );
616
+ if (!updated?.length) throw new Error(`check-in ${reminderId} was not deferred`);
617
+ return updated;
618
+ },
619
+ });
620
+ }
621
+
603
622
  async function recordContingencyEscalation({ code, trace, planId, dueAtUtc, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern, message, actionRequested, priority = null, isLive = null }) {
604
623
  return auditedWrite({
605
624
  trace,
@@ -748,6 +767,7 @@ module.exports = {
748
767
  hasCheckInNear,
749
768
  markReminderSent,
750
769
  settleCheckInRow,
770
+ deferCheckInRow,
751
771
  recordContingencyEscalation,
752
772
  cancelContingencyRows,
753
773
  standDownAllPendingRows,
@@ -48,6 +48,7 @@ const {
48
48
  cancelPendingFollowUps,
49
49
  markReminderSent,
50
50
  settleCheckInRow,
51
+ deferCheckInRow,
51
52
  cancelFollowUp,
52
53
  hasCheckInNear,
53
54
  } = require('../clinical/services/clinicalAirtableService');
@@ -1193,6 +1194,10 @@ class NexusMessaging {
1193
1194
  await completeSendClaim(claim.claimId);
1194
1195
  return { decision: 'skipped', holdReason: plan.reason, sent: false };
1195
1196
  }
1197
+ if (plan.mode === 'defer' && await deferCheckInRow({ code, reminderId, dueAt: plan.dueAt })) {
1198
+ await releaseSendClaim(claim.claimId);
1199
+ return { decision: 'deferred', holdReason: plan.reason, nextCheckAt: plan.dueAt, sent: false };
1200
+ }
1196
1201
  dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1197
1202
  if (!dispatched) {
1198
1203
  await completeSendClaim(claim.claimId);
@@ -136,16 +136,16 @@ async function readActiveRecommendations({ patientId, ctcaeTerm = null, includeI
136
136
  };
137
137
  }
138
138
 
139
- async function readRecommendationPlans({ patientId, limit = null }) {
139
+ async function readRecommendationPlans({ patientId, limit = null, since = null }) {
140
140
  const store = getFhirStore();
141
141
  const patient = `Patient/${fhirId(patientId)}`;
142
- const plans = await store.find({ patient, resourceType: 'CarePlan', identifierSlug: RECOMMENDATION_PLAN_SLUG });
142
+ const plans = await store.find({ patient, resourceType: 'CarePlan', identifierSlug: RECOMMENDATION_PLAN_SLUG, since });
143
143
  const wanted = limit === null ? plans : plans.slice(0, limit);
144
144
  if (!wanted.length) return [];
145
145
 
146
146
  const [elements, tasks] = await Promise.all([
147
- store.find({ patient, resourceType: 'ClinicalImpression', identifierSlug: RECOMMENDATION_ELEMENTS_SLUG }),
148
- store.find({ patient, resourceType: 'Task', identifierSlug: RECOMMENDATION_REC_SLUG }),
147
+ store.find({ patient, resourceType: 'ClinicalImpression', identifierSlug: RECOMMENDATION_ELEMENTS_SLUG, since }),
148
+ store.find({ patient, resourceType: 'Task', identifierSlug: RECOMMENDATION_REC_SLUG, since }),
149
149
  ]);
150
150
  return fromFhir([...wanted, ...elements, ...tasks], { patientId });
151
151
  }
package/lib/index.d.ts CHANGED
@@ -485,7 +485,7 @@ declare module '@peopl-health/nexus' {
485
485
  }
486
486
 
487
487
  export interface CheckInDueResult {
488
- decision: 'write' | 'hold' | 'skipped';
488
+ decision: 'write' | 'hold' | 'skipped' | 'deferred';
489
489
  holdReason: string | null;
490
490
  nextCheckAt?: string | null;
491
491
  sent: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.13",
3
+ "version": "6.0.14",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",