@peopl-health/nexus 5.56.38 → 5.56.41

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.
@@ -67,7 +67,8 @@ class BaileysProvider extends MessageProvider {
67
67
  }
68
68
 
69
69
  formatCode(code) {
70
- return code.includes('@s.whatsapp.net') ? code : `${code}@s.whatsapp.net`;
70
+ if (code.includes('@s.whatsapp.net')) return code;
71
+ return `${code.replace(/^whatsapp:/, '').replace(/^\+/, '')}@s.whatsapp.net`;
71
72
  }
72
73
 
73
74
  formatMessage(message) {
@@ -89,7 +90,7 @@ class BaileysProvider extends MessageProvider {
89
90
  throw new Error('Message or file URL is required');
90
91
  }
91
92
 
92
- const formattedCode = this.formatCode(code);
93
+ const formattedCode = this.formatCode(messageData.contactCode || code);
93
94
  let sendOptions = {};
94
95
  let formattedMessage = this.formatMessage(body || '');
95
96
 
@@ -71,7 +71,7 @@ class TwilioProvider extends MessageProvider {
71
71
  const { code, body, fileUrl, fileType, variables, contentSid } = messageData;
72
72
 
73
73
  const formattedFrom = ensureWhatsAppFormat(this.whatsappNumber);
74
- const formattedCode = ensureWhatsAppFormat(code);
74
+ const formattedCode = ensureWhatsAppFormat(messageData.contactCode || code);
75
75
 
76
76
  if (!formattedFrom || !formattedCode) {
77
77
  throw new Error('Invalid sender or recipient number');
@@ -24,6 +24,7 @@ const DEFAULT_CONTEXT_ANCHOR_STEP = 50;
24
24
  const OPERATOR_TURN_PREFIX = '[sistema]';
25
25
  const TEAM_TURN_PREFIX = '[equipo]';
26
26
  const PLATFORM_TURN_PREFIX = '[plataforma]';
27
+ const CAREGIVER_TURN_PREFIX = '[cuidador]';
27
28
  const CURRENT_TURN_GAP_MS = 15 * 60 * 1000;
28
29
  const CURRENT_TURN_MAX_MESSAGES = 15;
29
30
  const OUTBOUND_TAIL_MAX_MESSAGES = 10;
@@ -95,9 +96,9 @@ class DefaultMemoryManager extends MemoryManager {
95
96
  });
96
97
 
97
98
  const turnLines = currentTurn
98
- .flatMap(msg => formatMessage(msg).filter(Boolean))
99
- .map(line => line
100
- .replace(TURN_TIMESTAMP_PREFIX_RX, ''))
99
+ .flatMap(msg => formatMessage(msg)
100
+ .filter(Boolean)
101
+ .map(line => `${this._speakerPrefix(msg, 'user')}${line.replace(TURN_TIMESTAMP_PREFIX_RX, '')}`))
101
102
  .map(escapePatientMessageMarkers);
102
103
  if (turnLines.length) {
103
104
  context.push({
@@ -173,6 +174,7 @@ class DefaultMemoryManager extends MemoryManager {
173
174
 
174
175
  _speakerPrefix(msg, role) {
175
176
  if (this._isInlineOperatorTurn(msg, role)) return `${OPERATOR_TURN_PREFIX} `;
177
+ if (msg.origin === 'patient' && msg.contact_role === 'caregiver') return `${CAREGIVER_TURN_PREFIX} `;
176
178
  if (msg.origin !== 'whatsapp_platform') return '';
177
179
  // The send API records the authenticated sender; without one the send was automated.
178
180
  return msg.triggeredBy ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
@@ -4,6 +4,7 @@ const { OPERATOR_TURN_PREFIX } = require('../memory/DefaultMemoryManager');
4
4
  const { ROUTING_SKILL } = require('../helpers/clinicalWorkflowGuard');
5
5
  const { appendCall } = require('../services/llmAuditService');
6
6
  const { composePrompt } = require('../services/promptComposerService');
7
+ const { RISK_HEADLINE_MARKER, RISK_HEADLINE_DISCLAIMER } = require('../services/riskHeadlineService');
7
8
  const { isConversationalDraftReuseLive } = require('../flags/turnEfficiencyFlags');
8
9
  const { retryWithBackoff } = require('../../utils/retryUtils');
9
10
  const { withTiming } = require('../../utils/tracingDecorator');
@@ -475,9 +476,8 @@ class AnthropicProvider extends BaseLLMProvider {
475
476
  // turn persists once tool results are appended after it on multi-round turns.
476
477
  _buildInput({ additionalInstructions, ...rest }) {
477
478
  const input = super._buildInput({ additionalInstructions, ...rest });
478
- // Tail items move behind the history so they stop rewriting the cached prefix, but ahead of the
479
- // operator copy below, which is placed last precisely to hold recency.
480
- const ordered = [...input.filter(i => !i[TAIL_PLACEMENT]), ...input.filter(i => i[TAIL_PLACEMENT])];
479
+ const pinned = { role: 'developer', content: `${RISK_HEADLINE_MARKER}\n${RISK_HEADLINE_DISCLAIMER}` };
480
+ const ordered = [...input.filter(i => !i[TAIL_PLACEMENT]), pinned, ...input.filter(i => i[TAIL_PLACEMENT])];
481
481
  if (!additionalInstructions) return ordered;
482
482
  const { content } = this._operatorInstructionTurn(additionalInstructions);
483
483
  return [...ordered, { role: 'user', content: `${OPERATOR_TURN_PREFIX} ${content}`, type: 'message' }];
@@ -429,7 +429,9 @@ class BaseLLMProvider {
429
429
  parts.push(`## Síntomas recientes\n${symptoms}`);
430
430
  }
431
431
  if (parts.length === 0) return [];
432
- return [{ role: 'developer', content: parts.join('\n\n') }];
432
+ // Refreshed most turns (symptoms, risks); ahead of the history it rewrote the whole cached
433
+ // conversation. Informational only, so it rides behind it like the clock. Directives stay in system.
434
+ return [{ role: 'developer', content: parts.join('\n\n'), [TAIL_PLACEMENT]: true }];
433
435
  }
434
436
 
435
437
  _clinicalText(value, field) {
@@ -52,4 +52,5 @@ async function assembleRiskHeadline(patientId) {
52
52
  module.exports = {
53
53
  assembleRiskHeadline,
54
54
  RISK_HEADLINE_MARKER,
55
+ RISK_HEADLINE_DISCLAIMER,
55
56
  };
@@ -4,7 +4,7 @@ const { logger } = require('../../utils/logger');
4
4
 
5
5
  const definition = {
6
6
  'name': 'reportUnresolvedRequestv2',
7
- 'description': '**Does:** Escalates ADMINISTRATIVE / OPERATIVE matters — and non-clinical referrals to other services (psico-oncología, paliativos, non-oncology medical) — to the appropriate team queue. Records what was left pending, why it needs the team, operational urgency, and what was already communicated to the patient. It carries NO clinical-escalation semantics for the patient\'s oncology condition — those go to `reportMedicalEscalation`.\n\n**Required inputs:** `unresolved_question`, `category` (operational routing — REQUIRED for the queue), `urgency` (`routine` | `soon` | `urgent`; default `routine`), `escalation_details`, `resolution_attempted` (bool), `for_doctor_office` (bool: `true` only for a request your instructions route to the treating doctor or their office, otherwise `false`).\n\n**When to call:**\n- Administrative matter the team has to act on (insurance / authorisations / letters / transport), including scheduling or rescheduling a session of the AUNA accompaniment program (psico-oncología, nutrición).\n- Patient request that needs human (non-clinical) intervention.\n- Outside the agent\'s scope or knowledge (non-clinical).\n- A routine referral (psico-oncología, paliativos).\n- Callback from a specific team member (`category=contact_team_member`), or enrollment in a program / workshop / support group (`category=program_enrollment`).\n- Something the patient\'s own doctor or their office has to answer or do — a report or letter, a prescription or premedication that needs the doctor\'s indication, a non-urgent question or update for the doctor: keep the category that describes it and set `for_doctor_office: true` when your instructions route it to that office. Asking for a prescription or an indication is an administrative request, not a treatment concern; a symptom or a problem with the treatment still goes to `reportMedicalEscalation`. Never tell the patient to write to the doctor or the secretary themselves.\nAlways pair with a `DeliverPatientMessage` acknowledging the escalation.\n\n**When NOT to call:**\n- ANY medical escalation — confirmed emergency, same-day evaluation, OR an asynchronous clinical concern (a symptom persisting >72h, a worrying trend, a treatment concern, stale clinical context) — use `reportMedicalEscalation` (urgency_level stat | asap | urgent | routine).\n- Active mental-health crisis — use `reportCrisis`.\n- Patient SHARED results / values / files — use `reportResultsReceived`.\n- Booking, rescheduling or cancelling a doctor appointment, a treatment session (chemo / radiotherapy / infusion) or a lab / imaging study — these are not booked through this channel; answer the patient directly with where to book, as your instructions describe. When that turn carries no clinical content, declare it with `non_clinical_request` in `extractClinicalInfo`.\n- Questions answerable from the CTCAE catalog or skill protocols — answer directly.\n\n**Returns:** an ack ({} on the happy path). Out-of-enum `urgency`/`category` are coerced (to `routine`/`other`) and disclosed via `coerced_urgency`/`coerced_category`; inputs over 500 chars are truncated and disclosed via `truncated_fields`. If the escalation could not be queued to the team it comes back with `queued: false` — do NOT tell the patient the team was notified in that case; acknowledge and say you are still working on it.\n\n**Side effects:** Emits `OUT_OF_SCOPE_LOGGED` to the appropriate team queue.',
7
+ 'description': '**Does:** Escalates ADMINISTRATIVE / OPERATIVE matters — and non-clinical referrals to other services (psico-oncología, paliativos, non-oncology medical) — to the appropriate team queue. Records what was left pending, why it needs the team, operational urgency, and what was already communicated to the patient. It carries NO clinical-escalation semantics for the patient\'s oncology condition — those go to `reportMedicalEscalation`.\n\n**Required inputs:** `unresolved_question`, `category` (operational routing — REQUIRED for the queue), `urgency` (`routine` | `soon` | `urgent`; default `routine`), `escalation_details`, `resolution_attempted` (bool), `for_doctor_office` (bool: `true` only for a request your instructions route to the treating doctor or their office, otherwise `false`).\n\n**When to call:**\n- Administrative matter the team has to act on (insurance / authorisations / letters / transport), including scheduling or rescheduling a session of the AUNA accompaniment program (psico-oncología, nutrición).\n- Patient request that needs human (non-clinical) intervention.\n- Outside the agent\'s scope or knowledge (non-clinical).\n- A routine referral (psico-oncología, paliativos).\n- Callback from a specific team member (`category=contact_team_member`), or enrollment in a program / workshop / support group (`category=program_enrollment`).\n- Something the patient\'s own doctor or their office has to answer or do that is not symptom care — a report, letter or insurance form, a prescription or premedication the doctor already indicated, a payment receipt, an administrative question for the office: keep the category that describes it and set `for_doctor_office: true` when your instructions route it to that office. Asking for a prescription or an indication the doctor already gave is an administrative request, not a treatment concern. Symptom management belongs to the accompaniment program, not to the office: a symptom, a side effect, whether or how to take a medication, or a prescription or study the patient wants because of a symptom still goes to `reportMedicalEscalation` — never here with `for_doctor_office: true` — even when the patient asks for their doctor to see, review or answer it. A study, result, image or file the patient shares still goes to `reportResultsReceived`, even when they ask for it to reach the doctor. Never tell the patient to write to the doctor or the secretary themselves.\nAlways pair with a `DeliverPatientMessage` acknowledging the escalation.\n\n**When NOT to call:**\n- ANY medical escalation — confirmed emergency, same-day evaluation, OR an asynchronous clinical concern (a symptom persisting >72h, a worrying trend, a treatment concern, stale clinical context) — use `reportMedicalEscalation` (urgency_level stat | asap | urgent | routine).\n- Active mental-health crisis — use `reportCrisis`.\n- Patient SHARED results / values / files — use `reportResultsReceived`.\n- Booking, rescheduling or cancelling a doctor appointment, a treatment session (chemo / radiotherapy / infusion) or a lab / imaging study — these are not booked through this channel; answer the patient directly with where to book, as your instructions describe. When that turn carries no clinical content, declare it with `non_clinical_request` in `extractClinicalInfo`.\n- Questions answerable from the CTCAE catalog or skill protocols — answer directly.\n\n**Returns:** an ack ({} on the happy path). Out-of-enum `urgency`/`category` are coerced (to `routine`/`other`) and disclosed via `coerced_urgency`/`coerced_category`; inputs over 500 chars are truncated and disclosed via `truncated_fields`. If the escalation could not be queued to the team it comes back with `queued: false` — do NOT tell the patient the team was notified in that case; acknowledge and say you are still working on it.\n\n**Side effects:** Emits `OUT_OF_SCOPE_LOGGED` to the appropriate team queue.',
8
8
  'strict': true,
9
9
  'parameters': {
10
10
  'type': 'object',
@@ -49,7 +49,7 @@ const definition = {
49
49
  'anyOf': [
50
50
  {
51
51
  'type': 'boolean',
52
- 'description': 'true cuando el pendiente lo tiene que responder o hacer el médico tratante o su consultorio (un informe o carta, una receta o premedicación que necesita su indicación, una pregunta o un aviso no urgente para el médico) y tus instrucciones lo mandan a ese consultorio. La categoría sigue describiendo el pendiente.'
52
+ 'description': 'true cuando el pendiente lo tiene que responder o hacer el médico tratante o su consultorio y no es manejo de síntomas (un informe, carta o formato de aseguradora, una receta o premedicación que el médico ya indicó, un comprobante de pago, una pregunta administrativa para el consultorio) y tus instrucciones lo mandan a ese consultorio. Un síntoma, un efecto adverso, una duda sobre si o cómo tomar un medicamento, o una receta o estudio que el paciente pide por un síntoma son del programa de acompañamiento y van por `reportMedicalEscalation`, aunque el paciente pida que lo vea o le conteste su médico. La categoría sigue describiendo el pendiente.'
53
53
  },
54
54
  {
55
55
  'type': 'null'
@@ -16,6 +16,7 @@ const { Thread } = require('../models/threadModel');
16
16
 
17
17
  const { storeRunMetrics } = require('../helpers/metricsHelper');
18
18
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
19
+ const { remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
19
20
  const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
20
21
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
21
22
  const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
@@ -392,7 +393,7 @@ class NexusMessaging {
392
393
  if (rendered) messageData.body = rendered;
393
394
  }
394
395
 
395
- if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code))) {
396
+ if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
396
397
  return this._routeThroughTemplateRecovery(messageData);
397
398
  }
398
399
 
@@ -461,6 +462,10 @@ class NexusMessaging {
461
462
  }
462
463
 
463
464
  async sendAssistantReply(messageData) {
465
+ if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
466
+ const contact = await replyContactFor(messageData.code);
467
+ if (contact) messageData = { ...messageData, ...contact };
468
+ }
464
469
  if (messageData.outreachStartedAt) {
465
470
  const patientActivity = await getMessages({
466
471
  numero: messageData.code,
@@ -562,6 +567,7 @@ class NexusMessaging {
562
567
  */
563
568
 
564
569
  async processIncomingMessage(messageData, { onSaved = null } = {}) {
570
+ await remapCaregiverSender(messageData);
565
571
  const chatId = messageData.code;
566
572
 
567
573
  if (chatId) {
@@ -590,7 +596,7 @@ class NexusMessaging {
590
596
  logger.error('[processIncomingMessage] Contingency stand-down failed', { code: chatId, error: error.message })
591
597
  );
592
598
  }
593
- await releaseHeldMessages(chatId).catch(error =>
599
+ await releaseHeldMessages(chatId, { contactCode: messageData.contactCode || null }).catch(error =>
594
600
  logger.error('[processIncomingMessage] Held message release failed', { code: chatId, error: error.message })
595
601
  );
596
602
  }
@@ -0,0 +1,101 @@
1
+ const { Monitoreo_ID } = require('../config/airtableConfig');
2
+
3
+ const { logger } = require('../utils/logger');
4
+ const { MapCache } = require('../utils/MapCache');
5
+
6
+ const { getRecordByFilter } = require('../services/airtableService');
7
+ const { getMessages } = require('../services/messageService');
8
+
9
+ const { ensureWhatsAppFormat, stripWhatsAppFormat } = require('./twilioHelper');
10
+ const { escapeFormulaValue } = require('./airtableFormulaHelper');
11
+
12
+ const CAREGIVERS_FIELD = 'cuidadores_whatsapp';
13
+ const CAREGIVER_ROLE = 'caregiver';
14
+
15
+ const caregiverCache = new MapCache({ maxSize: 1000, ttl: 5 * 60 * 1000 });
16
+
17
+ const listedNumbers = (value) => String(value || '')
18
+ .split(/[,;\n]/)
19
+ .map((entry) => stripWhatsAppFormat(entry.replace(/[^\d+]/g, '')))
20
+ .filter(Boolean);
21
+
22
+ async function lookupCaregiver(code) {
23
+ const digits = stripWhatsAppFormat(code);
24
+ if (!/^\d+$/.test(digits)) return null;
25
+
26
+ const safeCode = escapeFormulaValue(code);
27
+ const records = await getRecordByFilter(
28
+ Monitoreo_ID,
29
+ 'estado_general',
30
+ `OR({whatsapp_id}='${safeCode}', FIND('${digits}', {${CAREGIVERS_FIELD}}))`,
31
+ );
32
+ if (!records?.length) return null;
33
+ if (records.some((row) => row.whatsapp_id === code)) return null;
34
+
35
+ const patients = records.filter((row) => row.whatsapp_id && listedNumbers(row[CAREGIVERS_FIELD]).includes(digits));
36
+ if (patients.length > 1) {
37
+ logger.warn('[caregiverHelper] number listed as caregiver of several patients; not remapping', { count: patients.length });
38
+ return null;
39
+ }
40
+ if (!patients.length) return null;
41
+ return { patientCode: ensureWhatsAppFormat(patients[0].whatsapp_id) };
42
+ }
43
+
44
+ async function resolveCaregiver(code) {
45
+ if (!code) return null;
46
+ const cached = caregiverCache.get(code);
47
+ if (cached !== undefined) return cached;
48
+
49
+ let resolved = null;
50
+ try {
51
+ resolved = await lookupCaregiver(code);
52
+ } catch (error) {
53
+ logger.error('[caregiverHelper] caregiver lookup failed', { error: error.message });
54
+ }
55
+ caregiverCache.set(code, resolved);
56
+ return resolved;
57
+ }
58
+
59
+ async function remapCaregiverSender(messageData) {
60
+ if (!messageData?.code || messageData.fromMe !== false || messageData.contactCode) return messageData;
61
+ const caregiver = await resolveCaregiver(messageData.code);
62
+ if (!caregiver) return messageData;
63
+ messageData.contactCode = messageData.code;
64
+ messageData.contactRole = CAREGIVER_ROLE;
65
+ messageData.code = caregiver.patientCode;
66
+ messageData.from = caregiver.patientCode;
67
+ return messageData;
68
+ }
69
+
70
+ async function replyContactFor(code) {
71
+ if (!code) return null;
72
+ try {
73
+ const [latest] = await getMessages(
74
+ { numero: code, from_me: false },
75
+ { sort: { createdAt: -1 }, limit: 1, select: 'contact_code contact_role' },
76
+ ) || [];
77
+ if (!latest?.contact_code) return null;
78
+ return { contactCode: latest.contact_code, contactRole: latest.contact_role };
79
+ } catch (error) {
80
+ logger.error('[caregiverHelper] reply contact lookup failed; replying to the patient', { error: error.message });
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function contactOf(message) {
86
+ return message?.contact_code ? { contactCode: message.contact_code, contactRole: message.contact_role } : {};
87
+ }
88
+
89
+ function _clearCaregiverCache() {
90
+ caregiverCache.clear();
91
+ }
92
+
93
+ module.exports = {
94
+ CAREGIVERS_FIELD,
95
+ CAREGIVER_ROLE,
96
+ contactOf,
97
+ remapCaregiverSender,
98
+ replyContactFor,
99
+ resolveCaregiver,
100
+ _clearCaregiverCache,
101
+ };
@@ -2,11 +2,11 @@ const { getMessages } = require('../services/messageService');
2
2
 
3
3
  const WINDOW_MS = 24 * 60 * 60 * 1000;
4
4
 
5
- async function isWithin24HourWindow(code) {
5
+ async function isWithin24HourWindow(code, { contactCode = null } = {}) {
6
6
  if (!code) return false;
7
7
  const cutoff = new Date(Date.now() - WINDOW_MS);
8
8
  const [recent] = await getMessages(
9
- { numero: code, from_me: false, createdAt: { $gte: cutoff } },
9
+ { numero: code, from_me: false, contact_code: contactCode, createdAt: { $gte: cutoff } },
10
10
  { select: '_id', limit: 1 }
11
11
  );
12
12
  return !!recent;
package/lib/index.d.ts CHANGED
@@ -6,6 +6,8 @@ declare module '@peopl-health/nexus' {
6
6
  message_id?: string;
7
7
  from: string;
8
8
  code?: string;
9
+ contactCode?: string | null;
10
+ contactRole?: 'caregiver' | null;
9
11
  body?: string;
10
12
  message?: string;
11
13
  timestamp?: string | Date;
@@ -8,6 +8,7 @@ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
8
8
 
9
9
  const { alertUndeliverable } = require('../helpers/channelRetryHelper');
10
10
 
11
+ const { contactOf } = require('../helpers/caregiverHelper');
11
12
  const { getMessages } = require('../services/messageService');
12
13
  const { recordUndeliverable } = require('../services/undeliverableService');
13
14
 
@@ -251,6 +252,7 @@ class TemplateApprovalJob extends BaseJob {
251
252
  try {
252
253
  result = await this.sendMessage({
253
254
  code: message.numero,
255
+ ...contactOf(message),
254
256
  contentSid,
255
257
  variables: {},
256
258
  kind: 'window_reopen_nudge',
@@ -289,6 +291,7 @@ class TemplateApprovalJob extends BaseJob {
289
291
  try {
290
292
  sendResult = await this.sendMessage({
291
293
  code: message.numero,
294
+ ...contactOf(message),
292
295
  contentSid: templateSid,
293
296
  variables: {},
294
297
  parentMessageId: message._id,
@@ -26,6 +26,8 @@ const messageSchema = new mongoose.Schema({
26
26
  enum: ['whatsapp_platform', 'assistant', 'patient', 'system', 'instruction'],
27
27
  default: 'whatsapp_platform'
28
28
  },
29
+ contact_code: { type: String, default: null },
30
+ contact_role: { type: String, enum: [null, 'caregiver'], default: null },
29
31
  tools_executed: {
30
32
  type: [{
31
33
  tool_name: { type: String, required: true },
@@ -4,6 +4,7 @@ const { isWithinHourWindow, contactHoursBetween } = require('../utils/scheduleUt
4
4
  const { Message } = require('../models/messageModel');
5
5
 
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
+ const { contactOf } = require('../helpers/caregiverHelper');
7
8
  const { cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi } = require('../helpers/templateRecoveryHelper');
8
9
 
9
10
  const { getMessages } = require('./messageService');
@@ -63,6 +64,7 @@ async function releaseOne(message, now) {
63
64
  try {
64
65
  result = await getMessaging().sendMessage({
65
66
  code: message.numero,
67
+ ...contactOf(message),
66
68
  body,
67
69
  parentMessageId: message._id,
68
70
  kind: 'freeform',
@@ -95,7 +97,7 @@ async function releaseOne(message, now) {
95
97
  return true;
96
98
  }
97
99
 
98
- async function releaseHeldMessages(code) {
100
+ async function releaseHeldMessages(code, { contactCode = null } = {}) {
99
101
  if (!code) return { released: 0, reason: 'no_code' };
100
102
 
101
103
  const now = new Date();
@@ -103,7 +105,7 @@ async function releaseHeldMessages(code) {
103
105
  return { released: 0, reason: 'quiet_hours' };
104
106
  }
105
107
 
106
- const held = await getMessages(heldQuery({ numero: code }), { sort: { createdAt: 1 }, limit: MAX_RELEASE_BATCH });
108
+ const held = await getMessages(heldQuery({ numero: code, contact_code: contactCode }), { sort: { createdAt: 1 }, limit: MAX_RELEASE_BATCH });
107
109
  if (!held.length) return { released: 0, reason: 'none_held' };
108
110
 
109
111
  let released = 0;
@@ -118,15 +120,15 @@ async function sweepHeldMessages() {
118
120
  if (!isWithinHourWindow(new Date(), PATIENT_CONTACT_WINDOW)) return 0;
119
121
 
120
122
  const recent = await getMessages(heldQuery(), {
121
- select: 'numero', sort: { createdAt: -1 }, limit: MAX_SWEEP_CANDIDATES
123
+ select: 'numero contact_code', sort: { createdAt: -1 }, limit: MAX_SWEEP_CANDIDATES
122
124
  });
123
- const codes = [...new Set(recent.map(doc => doc.numero))];
125
+ const phones = new Map(recent.map(doc => [`${doc.numero}|${doc.contact_code || ''}`, { code: doc.numero, contactCode: doc.contact_code || null }]));
124
126
  let released = 0;
125
127
 
126
- for (const code of codes) {
128
+ for (const { code, contactCode } of phones.values()) {
127
129
  try {
128
- if (!(await isWithin24HourWindow(code))) continue;
129
- const outcome = await releaseHeldMessages(code);
130
+ if (!(await isWithin24HourWindow(code, { contactCode }))) continue;
131
+ const outcome = await releaseHeldMessages(code, { contactCode });
130
132
  released += outcome.released;
131
133
  } catch (error) {
132
134
  logger.error('[HeldMessage] Sweep failed for one conversation', { code, error: error.message });
@@ -128,7 +128,11 @@ class MongoStorage {
128
128
  traceId: messageData.traceId || undefined,
129
129
  statusInfo: messageData.statusInfo,
130
130
  clinical_context: messageData.clinicalContext || null,
131
- triggeredBy: messageData.triggeredBy || null
131
+ triggeredBy: messageData.triggeredBy || null,
132
+ ...(messageData.contactCode && {
133
+ contact_code: ensureWhatsAppFormat(messageData.contactCode),
134
+ contact_role: messageData.contactRole || null
135
+ })
132
136
  };
133
137
  return values;
134
138
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.38",
3
+ "version": "5.56.41",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",