@peopl-health/nexus 6.4.0 → 6.4.2

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 } : {};
@@ -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
 
@@ -85,6 +85,8 @@ const unbatchedRoutes = {
85
85
  command: 'handleCommand',
86
86
  keyword: 'handleKeyword',
87
87
  };
88
+ // A command or keyword that no handler takes («!me duele») is still the patient talking.
89
+ const DECLINABLE_ROUTES = new Set(['command', 'keyword']);
88
90
 
89
91
  function loadDefaultLlmMonitor() {
90
92
  const { LlmMonitorService } = require('../clinical/monitoring/LlmMonitorService');
@@ -676,7 +678,11 @@ class NexusMessaging {
676
678
  }
677
679
 
678
680
  const route = unbatchedRoutes[messageData.type];
679
- if (route) return this[route](messageData);
681
+ if (route) {
682
+ const result = await this[route](messageData);
683
+ if (result !== false || !DECLINABLE_ROUTES.has(messageData.type)) return result;
684
+ messageData = { ...messageData, type: 'message' };
685
+ }
680
686
 
681
687
  if (this.batchingConfig.enabled && chatId) return this._handleWithCheckAfter(chatId);
682
688
  return messageData.type === 'media' ? this.handleMedia(messageData) : this.handleMessage(messageData);
@@ -711,11 +717,13 @@ class NexusMessaging {
711
717
  }
712
718
 
713
719
  async handleCommand(messageData) {
714
- if (this.handlers.onCommand) return await this.handlers.onCommand(messageData, this);
720
+ if (!this.handlers.onCommand) return false;
721
+ return await this.handlers.onCommand(messageData, this);
715
722
  }
716
723
 
717
724
  async handleKeyword(messageData) {
718
- if (this.handlers.onKeyword) return await this.handlers.onKeyword(messageData, this);
725
+ if (!this.handlers.onKeyword) return false;
726
+ return await this.handlers.onKeyword(messageData, this);
719
727
  }
720
728
 
721
729
  async handleFlow(messageData) {
@@ -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 {
package/lib/index.d.ts CHANGED
@@ -115,8 +115,10 @@ declare module '@peopl-health/nexus' {
115
115
  export type MessageHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
116
116
  export type InteractiveHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
117
117
  export type MediaHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
118
- export type CommandHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
119
- export type KeywordHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
118
+ /** Resolve `false` to decline: the message then goes on to the assistant as a normal message. */
119
+ export type CommandHandler = (messageData: MessageData, nexus: Nexus) => Promise<void | boolean>;
120
+ /** Resolve `false` to decline: the message then goes on to the assistant as a normal message. */
121
+ export type KeywordHandler = (messageData: MessageData, nexus: Nexus) => Promise<void | boolean>;
120
122
  export type FlowHandler = (messageData: MessageData, nexus: Nexus) => Promise<void>;
121
123
 
122
124
  export interface MessageHandlers {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.0",
3
+ "version": "6.4.2",
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"