@peopl-health/nexus 6.4.1 → 6.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
1
  const { getTurnTraceModel } = require('../models/turnTraceModel');
2
2
  const { isToolFailure, toolFailureError } = require('../helpers/toolResultHelper');
3
3
  const { GUARD_REFUSAL_CODES } = require('../helpers/clinicalWorkflowGuard');
4
+ const { settleClaimedDelivery } = require('../services/deliverySettlementService');
4
5
  const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
5
6
  const { logger } = require('../../utils/logger');
6
- const { settleClaimedDelivery } = require('../services/deliverySettlementService');
7
7
  const { normalizeTurnKind, TURN_KIND } = require('./turnContext');
8
8
 
9
9
  const UNLISTED_REFUSAL = 'unlisted_refusal';
10
+
10
11
  function refusalCode(output) {
11
12
  const raw = toolFailureError(output, UNLISTED_REFUSAL);
12
13
  return GUARD_REFUSAL_CODES.has(raw) ? raw : UNLISTED_REFUSAL;
@@ -1,7 +1,5 @@
1
1
  const { ClinicalMention } = require('../../shared/dtos/ClinicalMention');
2
2
 
3
- const { readStructuredText } = require('./structuredTextHelper');
4
-
5
3
  function buildExtractorInput(text, detectedTags, curated, template, { priorTurns = null, patientContext = null } = {}) {
6
4
  const priorTurnsPayload = Array.isArray(priorTurns) && priorTurns.length ? { prior_turns: priorTurns } : {};
7
5
  const contextPayload = patientContext ? { patient_context: patientContext } : {};
@@ -40,6 +40,9 @@ const SENTINELS = [
40
40
  /^no (he recibido|tengo) (alguno|ningun[oa])( mas)?$/,
41
41
  ];
42
42
 
43
+ // A bare «Sí» to the allergy question says there is one, so it stays as an unnamed allergy.
44
+ const UNNAMED_ALLERGY = 'Alergia a medicamentos referida, sin especificar';
45
+
43
46
  const clean = (s) => sanitizeInlineText(s, Infinity);
44
47
  const fold = (s) => foldAccents(clean(s)).toLowerCase().replace(/[.;,]+$/, '');
45
48
  const isSentinel = (s) => SENTINELS.some((re) => re.test(fold(s)));
@@ -73,8 +76,9 @@ function candidatesFor(record) {
73
76
  // 394 patients hold both keys; written separately the second arbitrates the first into `alternates`.
74
77
  const perVariable = new Map();
75
78
  for (const [key, variableId] of Object.entries(FIELD_MAP)) {
76
- const value = clean(clinical[key]);
77
- if (!value) continue;
79
+ const written = clean(clinical[key]);
80
+ if (!written) continue;
81
+ const value = key === 'alergias_medicamentos' && fold(written) === 'si' ? UNNAMED_ALLERGY : written;
78
82
  if (isSentinel(value)) { out.sentinels[key] = (out.sentinels[key] || 0) + 1; continue; }
79
83
  const bucket = perVariable.get(variableId) || [];
80
84
  if (bucket.some((held) => fold(held) === fold(value))) continue;
@@ -51,20 +51,21 @@ function phrase(action, voice) {
51
51
 
52
52
  function opsSummary(finding) {
53
53
  switch (finding.type) {
54
- case 'false_negative':
55
- return `${phrase(finding.expectedAction, 'missed')} y pudo hacer falta.`;
56
- case 'tool_unavailable_when_needed':
57
- return `${phrase(finding.expectedAction, 'missed')}, pero la herramienta no estaba disponible.`;
58
- case 'false_positive':
59
- return `${phrase(finding.observedAction, 'taken')} y pudo no hacer falta.`;
60
- case 'wrong_action':
61
- return `${phrase(finding.observedAction, 'taken')} y pudo ser la acción equivocada.`;
62
- case 'execution_failure':
63
- return `${phrase(finding.observedAction, 'requested')} y no se ejecutó correctamente.`;
64
- default:
65
- return OPS_SUMMARIES[finding.type] || OPS_SUMMARIES.uncertain;
54
+ case 'false_negative':
55
+ return `${phrase(finding.expectedAction, 'missed')} y pudo hacer falta.`;
56
+ case 'tool_unavailable_when_needed':
57
+ return `${phrase(finding.expectedAction, 'missed')}, pero la herramienta no estaba disponible.`;
58
+ case 'false_positive':
59
+ return `${phrase(finding.observedAction, 'taken')} y pudo no hacer falta.`;
60
+ case 'wrong_action':
61
+ return `${phrase(finding.observedAction, 'taken')} y pudo ser la acción equivocada.`;
62
+ case 'execution_failure':
63
+ return `${phrase(finding.observedAction, 'requested')} y no se ejecutó correctamente.`;
64
+ default:
65
+ return OPS_SUMMARIES[finding.type] || OPS_SUMMARIES.uncertain;
66
66
  }
67
67
  }
68
+
68
69
  const ACTION_LABELS = {
69
70
  arm: 'activar el plan',
70
71
  resolve: 'dar de baja el plan',
@@ -19,6 +19,7 @@ const PROCESSING_LEASE_MS = 15 * 60 * 1000;
19
19
  const RECONCILE_BATCH_SIZE = 500;
20
20
  const MAX_EVALUATION_ATTEMPTS = 5;
21
21
  const SYNC_RETRY_STATUSES = ['pending', 'failed'];
22
+
22
23
  function syncBacklogFilter() {
23
24
  return {
24
25
  $or: [
@@ -8,9 +8,9 @@ const { checkInsPausedUntil } = require('../../services/threadService');
8
8
  const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
9
9
  const { readRecommendationPlans } = require('../../fhir');
10
10
  const { ARMED_BY } = require('../../shared/dtos/ContingencySafetyNet');
11
+ const { logger } = require('../../utils/logger');
11
12
  const { readActiveNets, escalationUrgencyOf, CHECK_IN_WINDOW } = require('./contingencyDispatchService');
12
13
  const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
13
- const { logger } = require('../../utils/logger');
14
14
 
15
15
  const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
16
16
  const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
@@ -1,8 +1,8 @@
1
- const { withTiming } = require('../../utils/tracingDecorator');
2
1
  const { getComposer } = require('../config/subAgentsConfig');
3
2
  const { getPromptBlocks } = require('../config/composerConfig');
4
3
 
5
4
  const { readStructuredText } = require('../helpers/structuredTextHelper');
5
+ const { withTiming } = require('../../utils/tracingDecorator');
6
6
  const { safeParse } = require('../../utils/jsonUtils');
7
7
  const { logger } = require('../../utils/logger');
8
8
 
@@ -1,5 +1,5 @@
1
- const { createLLMProvider } = require('../providers/createLLMProvider');
2
1
  const { readStructuredText } = require('../helpers/structuredTextHelper');
2
+ const { createLLMProvider } = require('../providers/createLLMProvider');
3
3
  const runtimeConfig = require('../../config/runtimeConfig');
4
4
  const { logger } = require('../../utils/logger');
5
5
 
@@ -1,12 +1,12 @@
1
1
  const crypto = require('crypto');
2
2
 
3
+ const { isShadowRun } = require('../helpers/shadowHelper');
3
4
  const { logger } = require('../../utils/logger');
4
5
  const { clampToHourWindow } = require('../../utils/scheduleUtils');
5
6
  const { readContingencies, readSymptomCases, storeContingency } = require('../../fhir');
6
7
  const { ContingencySafetyNet, ACTIVE_CARE_PLAN_STATUSES, RESOLVED_REASONS, RESOLVES_ON, ARMED_BY, isNetActive } = require('../../shared/dtos/ContingencySafetyNet');
7
- const { recordReminder, hasPendingContingencyRow, recordContingencyEscalation, cancelContingencyRows } = require('./clinicalAirtableService');
8
8
  const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
9
- const { isShadowRun } = require('../helpers/shadowHelper');
9
+ const { recordReminder, hasPendingContingencyRow, recordContingencyEscalation, cancelContingencyRows } = require('./clinicalAirtableService');
10
10
 
11
11
  const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
12
12
  // Net check-ins start an hour later: 08:00–09:00 is when the daily symptom forms reach patients.
@@ -1,11 +1,9 @@
1
1
  const { getEscalationDraft } = require('../config/subAgentsConfig');
2
2
 
3
- const { FORMULARY_VERSION, TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
4
-
5
- const { createLLMProvider } = require('../providers/createLLMProvider');
6
-
7
3
  const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
8
4
  const { readStructuredText } = require('../helpers/structuredTextHelper');
5
+ const { createLLMProvider } = require('../providers/createLLMProvider');
6
+ const { FORMULARY_VERSION, TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
9
7
 
10
8
  const { getEscalationContext } = require('../../services/escalationContextService');
11
9
 
@@ -1,5 +1,5 @@
1
- const { createProjectorRegistry } = require('../../helpers/projectorHelper');
2
1
  const { validateSeed } = require('../helpers/seedHelper');
2
+ const { createProjectorRegistry } = require('../../helpers/projectorHelper');
3
3
 
4
4
  const registry = createProjectorRegistry({
5
5
  label: 'seed projector',
@@ -1,8 +1,8 @@
1
1
  const moment = require('moment-timezone');
2
2
 
3
+ const { UTILITY_BASES } = require('../services/outreachCarrierService');
3
4
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
4
5
  const { logger } = require('../../utils/logger');
5
- const { UTILITY_BASES } = require('../services/outreachCarrierService');
6
6
 
7
7
  const DECISIONS = ['write', 'hold'];
8
8
 
@@ -2,10 +2,10 @@ const crypto = require('node:crypto');
2
2
 
3
3
  const { getSuspectedGradeDisplays, getSystems } = require('../config/fhirConfig');
4
4
  const { lookupValue, integerId, parseList, termKey } = require('../utils/normalizeUtils');
5
- const { codeSystemUrl } = require('./fhirHelper');
6
5
 
7
6
  const { safeParse } = require('../../utils/jsonUtils');
8
7
  const { logger } = require('../../utils/logger');
8
+ const { codeSystemUrl } = require('./fhirHelper');
9
9
 
10
10
  const DIMENSION_SCALES = {
11
11
  frequency: ['Nunca', 'Rara vez', 'A veces', 'A menudo', 'Casi siempre'],
@@ -271,6 +271,7 @@ function ordinalIn(options, answer) {
271
271
  }
272
272
 
273
273
  const AFFIRMATIVE = ['sí', 'si', 'yes', 'true', '1'];
274
+
274
275
  function affirmative(value) {
275
276
  return AFFIRMATIVE.includes(String(value).trim().toLowerCase());
276
277
  }
@@ -5,7 +5,6 @@ const {
5
5
  recipientReference,
6
6
  codeableConcept,
7
7
  extension,
8
- notes,
9
8
  toIso,
10
9
  } = require('../helpers/elementHelper');
11
10
  const {
@@ -47,6 +47,20 @@ const ensureWhatsAppFormat = (code) => {
47
47
  return trimmed;
48
48
  };
49
49
 
50
+ // Without its country code: 10 digits is Mexico (an old 044/045 prefix dropped; never 51, Peru's code), 9 starting with 9 a Peruvian mobile.
51
+ const withCountryCode = (digits) => {
52
+ const national = digits.replace(/^04[45](?=\d{10}$)/, '');
53
+ if (/^(?!51)[2-9]\d{9}$/.test(national)) return `+52${national}`;
54
+ if (/^9\d{8}$/.test(digits)) return `+51${digits}`;
55
+ return digits;
56
+ };
57
+
58
+ // A phone as typed in Airtable («55 1234 5678», «987 654 321», «+51 987…») as a WhatsApp code.
59
+ const whatsAppCodeFromPhone = (phone) => {
60
+ const written = String(phone ?? '').replace(/[^\d+]/g, '');
61
+ return ensureWhatsAppFormat(written.startsWith('+') ? written : withCountryCode(written));
62
+ };
63
+
50
64
  const stripWhatsAppFormat = (code) => {
51
65
  const raw = String(code).trim();
52
66
  const unprefixed = raw.startsWith('whatsapp:') ? raw.slice('whatsapp:'.length) : raw;
@@ -68,6 +82,7 @@ module.exports = {
68
82
  extractTitle,
69
83
  ensureWhatsAppFormat,
70
84
  stripWhatsAppFormat,
85
+ whatsAppCodeFromPhone,
71
86
  isArchivedPatientCode,
72
87
  mexicanMobileVariant
73
88
  };
@@ -310,7 +310,10 @@ async function lastChatMessage(code) {
310
310
  return last;
311
311
  }
312
312
 
313
- const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').includes('?'));
313
+ const LINK = /https?:\/\/\S+|www\.\S+/gi;
314
+
315
+ // A «?» inside a link («…?id=») is no question.
316
+ const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').replace(LINK, ' ').includes('?'));
314
317
 
315
318
  // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
316
319
  async function remindQuietPatient(review, clock, now) {
@@ -4,7 +4,7 @@ const { logger } = require('../utils/logger');
4
4
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
7
+ const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
8
8
 
9
9
  const { logPatientChange } = require('./patientService');
10
10
  const { listEscalationApprovers } = require('./physicianService');
@@ -34,7 +34,7 @@ const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
34
34
  // The approving doctor's WhatsApp, or null when there is none to send the digest to.
35
35
  async function digestRecipient() {
36
36
  const [approver] = await listEscalationApprovers();
37
- const code = ensureWhatsAppFormat(String(approver?.phone ?? '').replace(/[^\d+]/g, ''));
37
+ const code = whatsAppCodeFromPhone(approver?.phone);
38
38
  return PATIENT_CODE.test(code) ? code : null;
39
39
  }
40
40
 
@@ -26,7 +26,7 @@ const {
26
26
  } = require('../models/escalationReviewModel');
27
27
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
28
28
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
29
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
29
+ const { ensureWhatsAppFormat, whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
30
30
  const { DrainingError } = require('../core/BatchingManager');
31
31
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
32
32
  const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
@@ -403,7 +403,7 @@ async function blockForMissingIdentity({ review, missing, operator }) {
403
403
  }
404
404
 
405
405
  async function sendDoctorAlert({ message, approver, operator }) {
406
- const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
406
+ const doctorCode = whatsAppCodeFromPhone(approver.phone);
407
407
  if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
408
408
  const inWindow = await isWithin24HourWindow(doctorCode);
409
409
  const outgoing = inWindow
@@ -7,7 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
8
  const { withTimeout } = require('../utils/timeoutUtils');
9
9
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
10
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
10
+ const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
11
11
 
12
12
  const airtableService = require('./airtableService');
13
13
 
@@ -23,8 +23,6 @@ const ROSTER_READ_TIMEOUT_MS = 5000;
23
23
 
24
24
  const getMessaging = () => require('../core/NexusMessaging');
25
25
 
26
- const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').replace(/[^\d+]/g, ''));
27
-
28
26
  const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
29
27
 
30
28
  let roster = { members: null, readAt: 0 };
@@ -36,7 +34,7 @@ function configuredPhones() {
36
34
  .split(',')
37
35
  .map((phone) => phone.trim())
38
36
  .filter(Boolean)
39
- .map(whatsAppCodeOf)
37
+ .map(whatsAppCodeFromPhone)
40
38
  .filter((code) => PATIENT_CODE.test(code));
41
39
  }
42
40
 
@@ -44,9 +42,10 @@ function configuredPhones() {
44
42
  async function readRoster() {
45
43
  const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, `AND({activo}, ${programSourceFormula()})`, null, ROSTER_FIELDS);
46
44
  if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
47
- return rows
48
- .map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [], doctor: row.rol === DOCTOR_ROLE }))
49
- .filter((member) => PATIENT_CODE.test(member.code));
45
+ const members = rows.map((row) => ({ code: whatsAppCodeFromPhone(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [], doctor: row.rol === DOCTOR_ROLE }));
46
+ const usable = members.filter((member) => PATIENT_CODE.test(member.code));
47
+ if (usable.length < members.length) logger.warn('[TeamAlert] On-call members left out: their WhatsApp number is not usable', { leftOut: members.length - usable.length });
48
+ return usable;
50
49
  }
51
50
 
52
51
  async function refreshRoster(now) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.1",
3
+ "version": "6.4.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -55,7 +55,7 @@
55
55
  "dev": "tsc --watch",
56
56
  "test": "jest",
57
57
  "test:inband": "jest --runInBand",
58
- "lint": "eslint lib/**/*.js",
58
+ "lint": "eslint 'lib/**/*.js'",
59
59
  "prepublishOnly": "npm test && npm run lint",
60
60
  "version": "npm run prepublishOnly && git add -A lib",
61
61
  "postversion": "git push && git push --tags"