@peopl-health/nexus 6.0.0-dev.718 → 6.0.0

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.
Files changed (438) hide show
  1. package/README.md +104 -0
  2. package/lib/adapters/BaileysProvider.js +8 -37
  3. package/lib/adapters/MessageAdapter.js +3 -1
  4. package/lib/adapters/MessageProvider.js +0 -11
  5. package/lib/adapters/TwilioProvider.js +44 -77
  6. package/lib/clinical/AssistantProcessor.js +414 -19
  7. package/lib/clinical/assistants/BaseAssistant.js +0 -15
  8. package/lib/clinical/config/checkInConfig.js +3 -0
  9. package/lib/clinical/config/cohortConfig.js +3 -3
  10. package/lib/clinical/config/composerConfig.js +42 -0
  11. package/lib/clinical/config/divergenceConfig.js +80 -50
  12. package/lib/clinical/config/llmConfig.js +11 -2
  13. package/lib/clinical/config/safetyNetConfig.js +108 -0
  14. package/lib/clinical/config/subAgentsConfig.js +61 -2
  15. package/lib/clinical/context/ToolRuntimeContext.js +121 -6
  16. package/lib/clinical/context/turnContext.js +50 -0
  17. package/lib/clinical/flags/bridgeConfig.js +31 -0
  18. package/lib/clinical/flags/clinicalContextFlags.js +46 -0
  19. package/lib/clinical/flags/composerFlags.js +14 -0
  20. package/lib/clinical/flags/contingencyFlags.js +19 -0
  21. package/lib/clinical/flags/escalationFlags.js +43 -0
  22. package/lib/clinical/flags/flagSnapshot.js +58 -0
  23. package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
  24. package/lib/clinical/flags/llmAuditConfig.js +7 -0
  25. package/lib/clinical/flags/llmMonitorConfig.js +18 -0
  26. package/lib/clinical/flags/patternConsultFlags.js +10 -0
  27. package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
  28. package/lib/clinical/flags/supportLightFlags.js +7 -0
  29. package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
  30. package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
  31. package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
  32. package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
  33. package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
  34. package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
  35. package/lib/clinical/helpers/chemoContextHelper.js +217 -0
  36. package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
  37. package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
  38. package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
  39. package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
  40. package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
  41. package/lib/clinical/helpers/cohortHelper.js +3 -1
  42. package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
  43. package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
  44. package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
  45. package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
  46. package/lib/clinical/helpers/encodedPairHelper.js +12 -0
  47. package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
  48. package/lib/clinical/helpers/factAssertionHelper.js +300 -0
  49. package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
  50. package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
  51. package/lib/clinical/helpers/legacyContextHelper.js +122 -0
  52. package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
  53. package/lib/clinical/helpers/llmsHelper.js +170 -87
  54. package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
  55. package/lib/clinical/helpers/medicationNamingRule.js +5 -0
  56. package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
  57. package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
  58. package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
  59. package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
  60. package/lib/clinical/helpers/resultsHelper.js +56 -0
  61. package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
  62. package/lib/clinical/helpers/shadowHelper.js +1 -13
  63. package/lib/clinical/helpers/skillActivationHelper.js +53 -0
  64. package/lib/clinical/helpers/structuredTextHelper.js +13 -0
  65. package/lib/clinical/helpers/toolResultHelper.js +35 -0
  66. package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
  67. package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
  68. package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
  69. package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
  70. package/lib/clinical/index.js +4 -0
  71. package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
  72. package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
  73. package/lib/clinical/models/llmCallModel.js +19 -0
  74. package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
  75. package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
  76. package/lib/clinical/models/patternConsultModel.js +37 -0
  77. package/lib/clinical/models/riskWarmupEventModel.js +23 -0
  78. package/lib/clinical/models/supportCandidateModel.js +90 -0
  79. package/lib/clinical/models/supportLightModel.js +95 -0
  80. package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
  81. package/lib/clinical/models/turnTraceModel.js +24 -7
  82. package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
  83. package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
  84. package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
  85. package/lib/clinical/promptPlacement.js +5 -0
  86. package/lib/clinical/protocols/treatmentFormulary.js +387 -0
  87. package/lib/clinical/providers/AnthropicProvider.js +459 -31
  88. package/lib/clinical/providers/BaseLLMProvider.js +689 -52
  89. package/lib/clinical/providers/GatewayProvider.js +14 -4
  90. package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
  91. package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
  92. package/lib/clinical/providers/OpenRouterProvider.js +9 -2
  93. package/lib/clinical/services/assistantService.js +51 -7
  94. package/lib/clinical/services/bridgeService.js +93 -0
  95. package/lib/clinical/services/checkInDueService.js +134 -0
  96. package/lib/clinical/services/clinicalAirtableService.js +752 -0
  97. package/lib/clinical/services/clinicalContextReadService.js +47 -0
  98. package/lib/clinical/services/clinicalExtractionService.js +156 -23
  99. package/lib/clinical/services/composerService.js +78 -0
  100. package/lib/clinical/services/conceptVerifierService.js +127 -0
  101. package/lib/clinical/services/conditionCloseService.js +138 -0
  102. package/lib/clinical/services/contextCleanupService.js +85 -0
  103. package/lib/clinical/services/contextMirrorService.js +72 -0
  104. package/lib/clinical/services/contextSyncRunner.js +20 -0
  105. package/lib/clinical/services/contextSyncService.js +258 -0
  106. package/lib/clinical/services/contingencyDispatchService.js +496 -0
  107. package/lib/clinical/services/ctcaeLadderService.js +70 -0
  108. package/lib/clinical/services/ctcaeTermService.js +44 -0
  109. package/lib/clinical/services/currentRegimenService.js +60 -0
  110. package/lib/clinical/services/deliverySettlementService.js +39 -0
  111. package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
  112. package/lib/clinical/services/dispatcherService.js +142 -0
  113. package/lib/clinical/services/escalationDraftService.js +229 -0
  114. package/lib/clinical/services/escalationNoteFactsService.js +131 -0
  115. package/lib/clinical/services/escalationQuestionsService.js +131 -0
  116. package/lib/clinical/services/gradeAnchorService.js +85 -0
  117. package/lib/clinical/services/gradeClaimService.js +73 -0
  118. package/lib/clinical/services/gradeSourceService.js +138 -0
  119. package/lib/clinical/services/impressionValidationService.js +19 -0
  120. package/lib/clinical/services/legacyContextSyncService.js +255 -0
  121. package/lib/clinical/services/llmAuditService.js +23 -0
  122. package/lib/clinical/services/nutritionPlanService.js +97 -0
  123. package/lib/clinical/services/outreachCarrierService.js +88 -0
  124. package/lib/clinical/services/outreachSweepRunner.js +8 -0
  125. package/lib/clinical/services/outreachSweepService.js +644 -0
  126. package/lib/clinical/services/patientHistoryService.js +203 -0
  127. package/lib/clinical/services/patientIdentityService.js +43 -0
  128. package/lib/clinical/services/patientProfileService.js +145 -0
  129. package/lib/clinical/services/patternConsultService.js +127 -0
  130. package/lib/clinical/services/pausedSafetyNetService.js +387 -0
  131. package/lib/clinical/services/promptComposerService.js +74 -21
  132. package/lib/clinical/services/radiotherapyContextService.js +40 -0
  133. package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
  134. package/lib/clinical/services/recommendationRankService.js +180 -0
  135. package/lib/clinical/services/recommendationRecoveryService.js +241 -0
  136. package/lib/clinical/services/recommendationValidationService.js +206 -0
  137. package/lib/clinical/services/regimenCloserService.js +205 -0
  138. package/lib/clinical/services/reminderDispatchService.js +36 -0
  139. package/lib/clinical/services/riskAssessmentService.js +469 -0
  140. package/lib/clinical/services/riskHeadlineService.js +56 -0
  141. package/lib/clinical/services/safetyNetPledgeService.js +231 -0
  142. package/lib/clinical/services/shadowMessageService.js +30 -12
  143. package/lib/clinical/services/shadowService.js +8 -4
  144. package/lib/clinical/services/skillService.js +117 -0
  145. package/lib/clinical/services/supportActionService.js +122 -0
  146. package/lib/clinical/services/supportCandidateService.js +607 -0
  147. package/lib/clinical/services/supportInvitability.js +86 -0
  148. package/lib/clinical/services/supportLightEvaluationService.js +231 -0
  149. package/lib/clinical/services/supportLightService.js +277 -0
  150. package/lib/clinical/services/supportRoutingAgentService.js +118 -0
  151. package/lib/clinical/services/symptomLandscapeService.js +153 -0
  152. package/lib/clinical/services/treatmentProposalService.js +136 -0
  153. package/lib/clinical/services/triageRecommendationService.js +1226 -0
  154. package/lib/clinical/services/turnRiskBriefService.js +217 -0
  155. package/lib/clinical/services/writeClaimStore.js +126 -0
  156. package/lib/clinical/stores/CtcaeCatalog.js +21 -0
  157. package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
  158. package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
  159. package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
  160. package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
  161. package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
  162. package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
  163. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
  164. package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
  165. package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
  166. package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
  167. package/lib/clinical/tools/openConditionTool.js +198 -0
  168. package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
  169. package/lib/clinical/tools/recordInterventionTool.js +138 -0
  170. package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
  171. package/lib/clinical/tools/registerClinicalTools.js +51 -6
  172. package/lib/clinical/tools/reportCrisisTool.js +193 -0
  173. package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
  174. package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
  175. package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
  176. package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
  177. package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
  178. package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
  179. package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
  180. package/lib/clinical/tools/skillTool.js +81 -0
  181. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
  182. package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
  183. package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
  184. package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
  185. package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
  186. package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
  187. package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
  188. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
  189. package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
  190. package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
  191. package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
  192. package/lib/config/airtableArchiveConfig.js +177 -0
  193. package/lib/config/airtableConfig.js +24 -1
  194. package/lib/config/instructionConfig.js +5 -0
  195. package/lib/config/lifecycle.js +36 -1
  196. package/lib/config/programConfig.js +20 -0
  197. package/lib/controllers/assistantController.js +67 -11
  198. package/lib/controllers/contextSyncController.js +30 -0
  199. package/lib/controllers/contingencyController.js +28 -0
  200. package/lib/controllers/conversationController.js +7 -7
  201. package/lib/controllers/dashboardController.js +7 -4
  202. package/lib/controllers/escalationReviewController.js +299 -0
  203. package/lib/controllers/healthController.js +16 -0
  204. package/lib/controllers/interactionController.js +1 -1
  205. package/lib/controllers/messageController.js +67 -19
  206. package/lib/controllers/officeAssistantController.js +57 -0
  207. package/lib/controllers/patientController.js +216 -48
  208. package/lib/controllers/prescriptionController.js +10 -3
  209. package/lib/controllers/templateController.js +8 -17
  210. package/lib/controllers/traceController.js +26 -0
  211. package/lib/controllers/triageRecommendationController.js +41 -0
  212. package/lib/controllers/uploadController.js +2 -2
  213. package/lib/core/BatchingManager.js +146 -11
  214. package/lib/core/DeferredWorkRunner.js +257 -0
  215. package/lib/core/MessageParser.js +2 -2
  216. package/lib/core/NexusMessaging.js +948 -146
  217. package/lib/core/PhiProcessor.js +198 -17
  218. package/lib/core/ProcessingPipeline.js +49 -4
  219. package/lib/core/interactiveRouteService.js +64 -0
  220. package/lib/core/runtimeToolPolicy.js +3 -0
  221. package/lib/eval/EvalProvider.js +72 -25
  222. package/lib/fhir/config/catalogConfig.js +9 -14
  223. package/lib/fhir/config/fhirConfig.js +16 -12
  224. package/lib/fhir/constants/escalationCaseStatus.js +31 -0
  225. package/lib/fhir/constants/extensionSlugs.js +195 -0
  226. package/lib/fhir/constants/gradeMethods.js +12 -0
  227. package/lib/fhir/constants/projectionSlugs.js +69 -1
  228. package/lib/fhir/constants/severityPriority.js +8 -0
  229. package/lib/fhir/constants/variableRegistry.js +60 -0
  230. package/lib/fhir/helpers/compositeHelper.js +65 -12
  231. package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
  232. package/lib/fhir/helpers/elementHelper.js +39 -0
  233. package/lib/fhir/helpers/fhirHelper.js +4 -1
  234. package/lib/fhir/helpers/fhirReadHelper.js +62 -0
  235. package/lib/fhir/helpers/recommendationIds.js +44 -0
  236. package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
  237. package/lib/fhir/helpers/resourceHelper.js +46 -0
  238. package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
  239. package/lib/fhir/helpers/termMatchHelper.js +42 -0
  240. package/lib/fhir/helpers/terminologyHelper.js +92 -5
  241. package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
  242. package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
  243. package/lib/fhir/index.js +75 -0
  244. package/lib/fhir/models/envelopeModel.js +22 -0
  245. package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
  246. package/lib/fhir/projections/clusterProjection.js +124 -0
  247. package/lib/fhir/projections/contextFactProjection.js +380 -0
  248. package/lib/fhir/projections/contingencyProjection.js +224 -0
  249. package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
  250. package/lib/fhir/projections/interventionProjection.js +245 -0
  251. package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
  252. package/lib/fhir/projections/palliativeProjection.js +175 -0
  253. package/lib/fhir/projections/proctcaeProjection.js +62 -15
  254. package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
  255. package/lib/fhir/projections/registerProjectors.js +10 -2
  256. package/lib/fhir/projections/reminderProjection.js +20 -0
  257. package/lib/fhir/projections/riskProjection.js +16 -0
  258. package/lib/fhir/projections/routingProjection.js +285 -0
  259. package/lib/fhir/projections/safetyGateProjection.js +42 -0
  260. package/lib/fhir/projections/symptomCaseProjection.js +324 -0
  261. package/lib/fhir/resources/CommunicationRequest.js +91 -0
  262. package/lib/fhir/resources/Condition.js +2 -24
  263. package/lib/fhir/resources/Encounter.js +30 -0
  264. package/lib/fhir/resources/Observation.js +22 -69
  265. package/lib/fhir/resources/Patient.js +57 -6
  266. package/lib/fhir/resources/Provenance.js +48 -12
  267. package/lib/fhir/resources/RiskAssessment.js +184 -0
  268. package/lib/fhir/resources/Task.js +102 -0
  269. package/lib/fhir/services/clinicalContextService.js +161 -0
  270. package/lib/fhir/services/clinicalMentionService.js +3 -5
  271. package/lib/fhir/services/clusterService.js +30 -0
  272. package/lib/fhir/services/contingencyService.js +47 -0
  273. package/lib/fhir/services/encounterService.js +16 -0
  274. package/lib/fhir/services/escalationService.js +85 -0
  275. package/lib/fhir/services/fhirService.js +20 -0
  276. package/lib/fhir/services/interventionService.js +50 -0
  277. package/lib/fhir/services/palliativeService.js +74 -0
  278. package/lib/fhir/services/patientService.js +41 -0
  279. package/lib/fhir/services/recommendationService.js +336 -0
  280. package/lib/fhir/services/resultObservationService.js +53 -0
  281. package/lib/fhir/services/riskService.js +202 -0
  282. package/lib/fhir/services/routingService.js +86 -0
  283. package/lib/fhir/services/snapshotService.js +18 -3
  284. package/lib/fhir/services/symptomCaseService.js +33 -0
  285. package/lib/fhir/services/terminologyService.js +16 -21
  286. package/lib/fhir/services/triageService.js +8 -4
  287. package/lib/fhir/stores/fhirStore.js +42 -19
  288. package/lib/fhir/utils/normalizeUtils.js +12 -0
  289. package/lib/helpers/airtableArchiveHelper.js +51 -0
  290. package/lib/helpers/airtableFormulaHelper.js +25 -0
  291. package/lib/helpers/caregiverHelper.js +136 -0
  292. package/lib/helpers/channelErrorHelper.js +31 -0
  293. package/lib/helpers/channelRetryHelper.js +156 -0
  294. package/lib/helpers/conversationWindowHelper.js +2 -2
  295. package/lib/helpers/deliveryAttemptHelper.js +14 -2
  296. package/lib/helpers/filesHelper.js +3 -3
  297. package/lib/helpers/healthHelper.js +40 -0
  298. package/lib/helpers/messageHelper.js +16 -6
  299. package/lib/helpers/messageStatusHelper.js +16 -22
  300. package/lib/helpers/metaSignatureHelper.js +6 -6
  301. package/lib/helpers/nerHelper.js +24 -0
  302. package/lib/helpers/outboundAllowlistHelper.js +51 -0
  303. package/lib/helpers/patientInformationHelper.js +20 -16
  304. package/lib/helpers/patientMessageHelper.js +79 -0
  305. package/lib/helpers/patientTaskRulesHelper.js +57 -0
  306. package/lib/helpers/pausedThreadHelper.js +37 -0
  307. package/lib/helpers/processHelper.js +47 -16
  308. package/lib/helpers/sendClaimHelper.js +126 -0
  309. package/lib/helpers/staffSendHelper.js +4 -0
  310. package/lib/helpers/templateFlowControllerHelper.js +1 -1
  311. package/lib/helpers/templateRecoveryHelper.js +66 -8
  312. package/lib/helpers/triageRecordHelper.js +124 -0
  313. package/lib/helpers/twilioHelper.js +7 -79
  314. package/lib/helpers/twilioMediaHelper.js +1 -1
  315. package/lib/helpers/whatsappHelper.js +3 -1
  316. package/lib/index.d.ts +844 -34
  317. package/lib/index.js +169 -11
  318. package/lib/jobs/ScheduledMessageJob.js +44 -0
  319. package/lib/jobs/TemplateApprovalJob.js +200 -33
  320. package/lib/models/agendaMessageModel.js +5 -0
  321. package/lib/models/airtableArchiveModel.js +225 -0
  322. package/lib/models/contactGateDecisionModel.js +27 -0
  323. package/lib/models/contextSyncStateModel.js +26 -0
  324. package/lib/models/deferredWorkModel.js +24 -0
  325. package/lib/models/deliveryAttemptModel.js +5 -1
  326. package/lib/models/escalationReviewModel.js +341 -0
  327. package/lib/models/flowRoutingModel.js +1 -1
  328. package/lib/models/messageModel.js +21 -1
  329. package/lib/models/patientProfileModel.js +24 -0
  330. package/lib/models/safetyNetPledgeModel.js +31 -0
  331. package/lib/models/sendClaimModel.js +18 -0
  332. package/lib/models/templateModel.js +1 -2
  333. package/lib/models/threadModel.js +7 -0
  334. package/lib/models/tokenMapModel.js +2 -1
  335. package/lib/models/writeClaimModel.js +14 -0
  336. package/lib/observability/telemetry.js +7 -7
  337. package/lib/providers/NerClient.js +2 -2
  338. package/lib/queue/QueueAdapter.js +1 -0
  339. package/lib/queue/RedisQueueAdapter.js +104 -7
  340. package/lib/routes/index.js +132 -2
  341. package/lib/services/airtableArchivePlanService.js +197 -0
  342. package/lib/services/airtableArchiveReadService.js +48 -0
  343. package/lib/services/airtableArchiveService.js +561 -0
  344. package/lib/services/airtableMirrorService.js +223 -0
  345. package/lib/services/airtableService.js +198 -18
  346. package/lib/services/assistantMessageService.js +140 -0
  347. package/lib/services/carePlanHistoryService.js +610 -0
  348. package/lib/services/characterizationOutcomeService.js +294 -0
  349. package/lib/services/contactGateService.js +178 -0
  350. package/lib/services/conversationService.js +66 -20
  351. package/lib/services/dashboard-provider-registry.js +38 -0
  352. package/lib/services/dashboardService.js +31 -4
  353. package/lib/services/escalationCaseTaskService.js +134 -0
  354. package/lib/services/escalationContextService.js +92 -0
  355. package/lib/services/escalationReviewService.js +2214 -0
  356. package/lib/services/flowDataExchangeService.js +1 -1
  357. package/lib/services/globalEntityService.js +1 -1
  358. package/lib/services/gravePendingService.js +41 -0
  359. package/lib/services/healthService.js +252 -0
  360. package/lib/services/heldMessageService.js +141 -0
  361. package/lib/services/inboundRecoveryService.js +354 -0
  362. package/lib/services/instructionInFlightService.js +17 -0
  363. package/lib/services/officeAssistantService.js +217 -0
  364. package/lib/services/orbisService.js +44 -0
  365. package/lib/services/patientClinicalStatusService.js +189 -0
  366. package/lib/services/patientResourceService.js +24 -0
  367. package/lib/services/patientService.js +28 -16
  368. package/lib/services/patientTaskService.js +221 -0
  369. package/lib/services/patientTaskSummaryService.js +93 -0
  370. package/lib/services/physicianService.js +31 -0
  371. package/lib/services/preprocessingService.js +18 -6
  372. package/lib/services/queueReconciliationService.js +161 -0
  373. package/lib/services/recommendationCarouselService.js +398 -0
  374. package/lib/services/reviewAlertSweepService.js +99 -0
  375. package/lib/services/reviewBoardService.js +75 -0
  376. package/lib/services/reviewDeadlineService.js +116 -0
  377. package/lib/services/reviewDraftSweepService.js +85 -0
  378. package/lib/services/teamAlertService.js +140 -0
  379. package/lib/services/templateService.js +1 -2
  380. package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
  381. package/lib/services/tokenMapService.js +119 -22
  382. package/lib/services/toolRegistryService.js +43 -2
  383. package/lib/services/triageHistoryService.js +128 -0
  384. package/lib/services/twilioMediaService.js +79 -0
  385. package/lib/services/undeliverableService.js +36 -0
  386. package/lib/services/untakenAlertService.js +210 -0
  387. package/lib/shared/dtos/ClinicalAssertion.js +21 -0
  388. package/lib/shared/dtos/ClinicalMention.js +4 -0
  389. package/lib/shared/dtos/ClusterImpression.js +16 -5
  390. package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
  391. package/lib/shared/dtos/DispatchedEscalation.js +4 -8
  392. package/lib/shared/dtos/GradedSymptom.js +2 -0
  393. package/lib/shared/dtos/Intervention.js +10 -3
  394. package/lib/shared/dtos/ManagedSymptom.js +40 -11
  395. package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
  396. package/lib/shared/dtos/PalliativeAssessment.js +62 -0
  397. package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
  398. package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
  399. package/lib/shared/dtos/RecommendationPlan.js +102 -0
  400. package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
  401. package/lib/shared/dtos/Reminder.js +2 -2
  402. package/lib/shared/dtos/RoutingDecision.js +2 -1
  403. package/lib/shared/dtos/SupportAction.js +28 -0
  404. package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
  405. package/lib/shared/dtos/TriageCompletion.js +50 -0
  406. package/lib/shared/dtos/TriageResponse.js +7 -1
  407. package/lib/storage/MongoStorage.js +10 -1
  408. package/lib/templates/predefinedTemplates.js +1 -1
  409. package/lib/templates/templateStructure.js +15 -2
  410. package/lib/utils/MapCache.js +1 -1
  411. package/lib/utils/coercionUtils.js +11 -0
  412. package/lib/utils/concurrencyUtils.js +13 -0
  413. package/lib/utils/dateUtils.js +114 -6
  414. package/lib/utils/errorUtils.js +26 -1
  415. package/lib/utils/formatUtils.js +43 -37
  416. package/lib/utils/httpErrorUtils.js +9 -0
  417. package/lib/utils/intervalSweeper.js +75 -0
  418. package/lib/utils/jsonUtils.js +51 -0
  419. package/lib/utils/logger.js +8 -6
  420. package/lib/utils/paginationUtils.js +30 -0
  421. package/lib/utils/retryUtils.js +9 -1
  422. package/lib/utils/sanitizerUtils.js +87 -1
  423. package/lib/utils/scheduleUtils.js +70 -1
  424. package/lib/utils/shadowScope.js +13 -0
  425. package/lib/utils/statsUtils.js +21 -0
  426. package/lib/utils/textMatchUtils.js +76 -0
  427. package/lib/utils/timeoutUtils.js +16 -0
  428. package/lib/utils/tokenMapUtils.js +3 -3
  429. package/package.json +11 -11
  430. package/lib/clinical/helpers/divergenceHelper.js +0 -100
  431. package/lib/clinical/models/divergenceModel.js +0 -41
  432. package/lib/clinical/services/clinicalAgentService.js +0 -18
  433. package/lib/clinical/services/divergenceService.js +0 -90
  434. package/lib/core/workflowRunner.js +0 -35
  435. package/lib/fhir/resources/Appointment.js +0 -28
  436. package/lib/fhir/resources/MedicationStatement.js +0 -42
  437. package/lib/fhir/resources/Procedure.js +0 -30
  438. package/lib/services/twilioService.js +0 -13
@@ -4,36 +4,115 @@ const { airtable } = require('../config/airtableConfig');
4
4
  const { connect } = require('../config/mongoConfig');
5
5
  const { setMetaConfig } = require('../config/metaConfig');
6
6
  const runtimeConfig = require('../config/runtimeConfig');
7
+ const { DEFAULT_INSTRUCTION_SETTLE_MS, PENDING_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig');
8
+ const { decodeUnicodeEscapes, decodeUnicodeEscapesDeep } = require('../utils/sanitizerUtils');
9
+ const { runInShadowScope } = require('../utils/shadowScope');
7
10
 
8
11
  const { logger } = require('../utils/logger');
9
12
 
13
+ const { createEvent, safeEmit } = require('../utils/eventUtils');
14
+ const { withTimeout } = require('../utils/timeoutUtils');
10
15
  const { Message } = require('../models/messageModel');
11
16
  const { Thread } = require('../models/threadModel');
12
17
 
13
- const { ensureThreadExists } = require('../helpers/threadHelper');
14
18
  const { storeRunMetrics } = require('../helpers/metricsHelper');
15
19
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
20
+ const { maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
16
21
  const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
17
22
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
23
+ const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
24
+ const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
25
+ const { isStaffSend } = require('../helpers/staffSendHelper');
26
+ const { isOutboundAllowed } = require('../helpers/outboundAllowlistHelper');
18
27
 
19
28
  const { createMessagingProvider } = require('../adapters/registry');
29
+ const { ensureThreadExists } = require('../services/threadService');
30
+ const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
20
31
 
21
- const { hasPreprocessingHandler, invokePreprocessingHandler } = require('../services/preprocessingService');
32
+ const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
22
33
  const { getMessages, updateMessage } = require('../services/messageService');
34
+ const { processAssistantSystemMessage } = require('../services/assistantMessageService');
35
+ const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
36
+ const { QueueReconciliationService } = require('../services/queueReconciliationService');
37
+ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
23
38
 
24
- const { BatchingManager } = require('../core/BatchingManager');
39
+ const { BatchingManager, DrainingError } = require('../core/BatchingManager');
25
40
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
26
- const { preProcessMessages, configureOpenAIProvider, AssistantProcessor } = require('../clinical');
41
+ const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
42
+ const { deliveryOutcome } = require('../clinical/AssistantProcessor');
43
+ const { UNASSIGNED, alertOpsForClaimedMessage, coverIfUnassigned, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
44
+ const { buildOutreachCarrier, validateAgentText } = require('../clinical/services/outreachCarrierService');
45
+ const { routineOutreachCollisionReason, isWithinTriageProtectionWindow } = require('../clinical/services/outreachSweepService');
46
+ const {
47
+ readPendingReminderForPatient,
48
+ cancelPendingFollowUps,
49
+ markReminderSent,
50
+ settleCheckInRow,
51
+ cancelFollowUp,
52
+ hasCheckInNear,
53
+ } = require('../clinical/services/clinicalAirtableService');
54
+ const { cancelContingencies, applyContingencyEvent } = require('../clinical/services/contingencyDispatchService');
55
+ const { checkInTriggeredBy, planCheckInDue } = require('../clinical/services/checkInDueService');
56
+ const { isContingencyCancelOnReplyLive } = require('../clinical/flags/contingencyFlags');
57
+ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
27
58
 
28
59
  const { createQueueAdapter } = require('../queue');
29
60
  const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
30
61
  const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
62
+ const { WorkflowRunner } = require('./DeferredWorkRunner');
63
+ const { invokeInteractiveRoute } = require('./interactiveRouteService');
31
64
 
32
65
  const { PhiProcessor } = require('./PhiProcessor');
33
66
 
67
+ const FOLLOW_UP_SPACING_MIN = 180;
68
+
69
+ // A refused send is saved as `undelivered` so memory and the safety net skip it.
70
+ const unsentStatusInfo = (result) => (deliveryOutcome(result) === 'known_not_sent'
71
+ ? { statusInfo: { status: 'undelivered', updatedAt: new Date() } }
72
+ : {});
73
+
74
+ async function followUpCollisionReason(code, reminderId, now) {
75
+ if (!reminderId.startsWith('followup_')) return routineOutreachCollisionReason(code, { now });
76
+ return isWithinTriageProtectionWindow(now) ? 'triage_protection_window' : null;
77
+ }
78
+
79
+ const unbatchedRoutes = {
80
+ __proto__: null,
81
+ flow: 'handleFlow',
82
+ interactive: 'handleInteractive',
83
+ command: 'handleCommand',
84
+ keyword: 'handleKeyword',
85
+ };
86
+
87
+ function loadDefaultLlmMonitor() {
88
+ const { LlmMonitorService } = require('../clinical/monitoring/LlmMonitorService');
89
+ const { contingencyMonitorSpec } = require('../clinical/monitoring/contingencyMonitorSpec');
90
+ return { LlmMonitorService, contingencyMonitorSpec };
91
+ }
92
+
93
+ function normalizeLlmMonitorConfig(value) {
94
+ if (typeof value === 'boolean') return { enabled: value };
95
+ return value && typeof value === 'object' ? value : {};
96
+ }
97
+
98
+ function createDefaultLlmMonitor(options, loader = loadDefaultLlmMonitor) {
99
+ if (!options.enabled) return null;
100
+ try {
101
+ const { LlmMonitorService, contingencyMonitorSpec } = loader();
102
+ return new LlmMonitorService({ ...options, specs: [contingencyMonitorSpec] });
103
+ } catch (error) {
104
+ logger.warn('[llmMonitor] construction failed; patient messaging remains available', {
105
+ error: error?.message || String(error),
106
+ });
107
+ return null;
108
+ }
109
+ }
110
+
34
111
  /**
35
112
  * Core messaging orchestrator for providers, storage, and assistant processing.
36
113
  */
114
+ const NOT_SENT_DECEASED = { success: false, messageId: null, status: 'patient_deceased', delivered: false, deferred: false };
115
+
37
116
  class NexusMessaging {
38
117
  constructor(config = {}) {
39
118
  this.config = config;
@@ -57,12 +136,17 @@ class NexusMessaging {
57
136
  abortOnNewMessage: config.messageBatching?.abortOnNewMessage ?? true,
58
137
  immediateRestart: config.messageBatching?.immediateRestart ?? true,
59
138
  typingIndicator: config.messageBatching?.typingIndicator ?? false,
139
+ instructionSettleMs: config.messageBatching?.instructionSettleMs ?? DEFAULT_INSTRUCTION_SETTLE_MS,
60
140
  hooks: config.messageBatching?.hooks || {},
61
141
  };
62
142
 
63
143
  this.batchingManager = new BatchingManager({
64
144
  config: this.batchingConfig
65
145
  });
146
+ this.batchingManager.onRefused = (chatId) =>
147
+ safeEmit(this.events, 'turn:deferred', createEvent('turn:deferred', { chatId, reason: 'draining' }));
148
+ this.batchingManager.onAbandoned = (payload) =>
149
+ safeEmit(this.events, 'turn:abandoned', createEvent('turn:abandoned', payload));
66
150
 
67
151
  this.pipeline = new ProcessingPipeline(this.batchingConfig.hooks);
68
152
 
@@ -70,6 +154,18 @@ class NexusMessaging {
70
154
  const queueConfig = config.queue?.config || {};
71
155
  this.queueAdapter = createQueueAdapter(queueType, queueConfig);
72
156
 
157
+ const monitorConfig = normalizeLlmMonitorConfig(config.llmMonitor);
158
+ const monitorEnabled = Object.prototype.hasOwnProperty.call(monitorConfig, 'enabled')
159
+ ? monitorConfig.enabled === true
160
+ : isLlmMonitorEnabled();
161
+ this.llmMonitor = monitorConfig.service || createDefaultLlmMonitor({
162
+ ...monitorConfig,
163
+ enabled: monitorEnabled,
164
+ queueAdapter: this.queueAdapter,
165
+ });
166
+
167
+ this.workflowRunner = new WorkflowRunner({ queueAdapter: this.queueAdapter });
168
+
73
169
  this.phiProcessor = new PhiProcessor({
74
170
  encode: config.phi?.encode || false,
75
171
  ner: config.phi?.ner || null,
@@ -82,6 +178,8 @@ class NexusMessaging {
82
178
  sendMessage: this.sendAssistantReply.bind(this),
83
179
  phiProcessor: this.phiProcessor,
84
180
  storeRunMetrics,
181
+ llmMonitor: this.llmMonitor,
182
+ toolRuntimeRepos: config.assistant?.toolRuntimeRepos || {},
85
183
  });
86
184
 
87
185
  this.scheduledMessageJob = new ScheduledMessageJob({
@@ -100,6 +198,13 @@ class NexusMessaging {
100
198
  }
101
199
  });
102
200
 
201
+ this.queueReconciliation = new QueueReconciliationService({
202
+ ...(config.queueReconciliation || {}),
203
+ scheduleMessage: (options) => this.scheduledMessageJob.schedule(options),
204
+ scheduleTemplateApproval: (options) => this.scheduleTemplateApproval(options),
205
+ sweepHeldMessages: () => sweepHeldMessages()
206
+ });
207
+
103
208
  this._providerStores = false;
104
209
  this._saveFn = null;
105
210
  this._saveMessageFn = async () => null;
@@ -116,8 +221,26 @@ class NexusMessaging {
116
221
  return null;
117
222
  }
118
223
 
224
+ async _repairOutbound(messageData) {
225
+ const [body, variables] = await Promise.all([
226
+ this.phiProcessor.repairOutbound(messageData.body, messageData.code),
227
+ this.phiProcessor.repairOutbound(messageData.variables, messageData.code),
228
+ ]);
229
+ if (body === messageData.body && variables === messageData.variables) return messageData;
230
+ const repaired = { ...messageData };
231
+ if (body !== messageData.body) repaired.body = body;
232
+ if (variables !== messageData.variables) repaired.variables = variables;
233
+ return repaired;
234
+ }
235
+
119
236
  async _transport(messageData) {
120
- const result = await this.provider.sendMessage(messageData);
237
+ let result;
238
+ try {
239
+ result = await this.provider.sendMessage(await this._repairOutbound(messageData));
240
+ } catch (error) {
241
+ await this._markSendFailed(messageData, error);
242
+ throw error;
243
+ }
121
244
 
122
245
  if (messageData.parentMessageId && result?.finalize && this.messageStorage?.finalizePendingMessage) {
123
246
  await this.messageStorage.finalizePendingMessage(messageData.parentMessageId, result.finalize.sid, {
@@ -127,10 +250,32 @@ class NexusMessaging {
127
250
  }
128
251
 
129
252
  if (messageData.code) ensureThreadExists(messageData.code);
253
+ if (result?.success === true) observeSend(messageData);
130
254
 
131
255
  return result;
132
256
  }
133
257
 
258
+ async _markSendFailed(messageData, error) {
259
+ if (!messageData.parentMessageId || !this.messageStorage?.finalizePendingMessage) return;
260
+ if (error?.acceptedChunks > 0) {
261
+ logger.warn('[NexusMessaging] A long reply reached the patient only in part', {
262
+ code: messageData.code, acceptedChunks: error.acceptedChunks, error: error.message,
263
+ });
264
+ return;
265
+ }
266
+ try {
267
+ await this.messageStorage.finalizePendingMessage(messageData.parentMessageId, null, {
268
+ status: 'failed',
269
+ errorMessage: String(error?.message || error).slice(0, 500),
270
+ updatedAt: new Date(),
271
+ });
272
+ } catch (markError) {
273
+ logger.warn('[NexusMessaging] A failed send could not be marked failed', {
274
+ code: messageData.code, error: markError.message,
275
+ });
276
+ }
277
+ }
278
+
134
279
  async initialize(options = {}) {
135
280
  const { provider, providerConfig, mongoUri, messageStorage, llm, llmConfig, meta } = options;
136
281
 
@@ -150,9 +295,23 @@ class NexusMessaging {
150
295
  this.setMessageStorage(messageStorage);
151
296
  }
152
297
 
298
+ await this.initializeLlmMonitor();
299
+ this.queueReconciliation.start();
300
+
153
301
  return this;
154
302
  }
155
303
 
304
+ async initializeLlmMonitor() {
305
+ try {
306
+ return await this.llmMonitor?.start();
307
+ } catch (error) {
308
+ logger.warn('[llmMonitor] startup failed; patient messaging remains available', {
309
+ error: error?.message || String(error),
310
+ });
311
+ return { enabled: false, error: error?.message || String(error) };
312
+ }
313
+ }
314
+
156
315
  async initializeMongoDB(mongoUri = runtimeConfig.get('MONGODB_URI')) {
157
316
  try {
158
317
  this.mongodb = await connect(mongoUri);
@@ -217,7 +376,9 @@ class NexusMessaging {
217
376
  getBatchingManager() { return this.batchingManager; }
218
377
  getPipeline() { return this.pipeline; }
219
378
  getAssistantProcessor() { return this.assistantProcessor; }
379
+ getLlmMonitor() { return this.llmMonitor; }
220
380
  getQueueAdapter() { return this.queueAdapter; }
381
+ getWorkflowRunner() { return this.workflowRunner; }
221
382
  getPhiProcessor() { return this.phiProcessor; }
222
383
  isConnected() { return this.provider?.getConnectionStatus() ?? false; }
223
384
  isProcessing(chatId) { return this.batchingManager.isProcessing(chatId); }
@@ -227,8 +388,44 @@ class NexusMessaging {
227
388
  */
228
389
 
229
390
  async sendMessage(messageData) {
391
+ // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
392
+ const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
393
+ if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
394
+ const claim = await acquireSendClaim(messageData);
395
+ if (!claim.acquired) {
396
+ return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
397
+ }
398
+
399
+ let gate = null;
400
+ try {
401
+ gate = await reserveSend(messageData);
402
+ if (gate?.blocked) {
403
+ await releaseSendClaim(claim.claimId);
404
+ return { success: false, messageId: null, status: 'contact_capped', reason: gate.reason, category: gate.category, delivered: false, deferred: false };
405
+ }
406
+ const result = await this._sendMessage(gate ? { ...messageData, contactGateDecisionId: gate.decisionId } : messageData);
407
+ // A deferred send is recorded when it actually leaves, so its reservation must not also count.
408
+ if (result?.success !== true || result?.deferred === true) await releaseSend(gate?.decisionId);
409
+ if (result?.success === true && result?.deferred !== true && !await completeSendClaim(claim.claimId)) {
410
+ logger.error('[NexusMessaging] send claim completion failed; a retry after the claim expires may send again', {
411
+ code: messageData.code,
412
+ claimId: String(claim.claimId),
413
+ });
414
+ }
415
+ return result;
416
+ } catch (error) {
417
+ await releaseSend(gate?.decisionId);
418
+ await releaseSendClaim(claim.claimId);
419
+ throw error;
420
+ }
421
+ }
422
+
423
+ async _sendMessage(messageData) {
230
424
  if (!this.provider) throw new Error('No provider initialized');
231
425
 
426
+ if (messageData.body) messageData.body = decodeUnicodeEscapes(messageData.body);
427
+ if (messageData.variables) messageData.variables = decodeUnicodeEscapesDeep(messageData.variables);
428
+
232
429
  if (messageData.fileUrl && this._providerStores) await prepareMessageMedia(messageData);
233
430
 
234
431
  if (messageData.contentSid && !messageData.body && this.provider.renderTemplate) {
@@ -236,30 +433,8 @@ class NexusMessaging {
236
433
  if (rendered) messageData.body = rendered;
237
434
  }
238
435
 
239
- if (messageData._fromConversationReply) messageData.processed = true;
240
-
241
- if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code))) {
242
- if (messageData.parentMessageId) {
243
- const [found] = await getMessages({ _id: messageData.parentMessageId }, { limit: 1 });
244
- if (!found) return { success: false, delivered: false, deferred: true };
245
- await triggerTemplateRecovery(found, { source: 'preemptive' });
246
- return { success: true, messageId: String(found._id), status: 'queued', preemptive: true, delivered: false, deferred: true };
247
- }
248
- const saveFn = this.messageStorage.savePendingMessage.bind(this.messageStorage);
249
- return this.phiProcessor.outDataFromPlain(
250
- {
251
- ...messageData,
252
- provider: 'twilio',
253
- fromMe: true,
254
- processed: messageData.processed ?? false,
255
- },
256
- saveFn,
257
- async ({ body, _id }) => {
258
- await triggerTemplateRecovery({ _id, body, numero: messageData.code }, { source: 'preemptive' });
259
- return { success: true, messageId: String(_id), status: 'queued', preemptive: true, delivered: false, deferred: true };
260
- },
261
- { onSaved: messageData.onParentMessageId },
262
- );
436
+ if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
437
+ return this._routeThroughTemplateRecovery(messageData);
263
438
  }
264
439
 
265
440
  if (messageData.parentMessageId) {
@@ -273,7 +448,7 @@ class NexusMessaging {
273
448
  await this.messageStorage.saveMessage({
274
449
  ...messageData, body: encodedBody,
275
450
  messageId: result?.messageId, provider: result?.provider,
276
- fromMe: true, processed: true,
451
+ fromMe: true, processed: true, ...unsentStatusInfo(result),
277
452
  });
278
453
  }
279
454
  return result;
@@ -293,21 +468,97 @@ class NexusMessaging {
293
468
  );
294
469
  }
295
470
 
471
+ // Builds a one-off approved template from THIS message's own text and sends it once Meta approves.
472
+ // The window decides the transport, never the wording.
473
+ async _routeThroughTemplateRecovery(messageData) {
474
+ if (messageData.parentMessageId) {
475
+ const [found] = await getMessages({ _id: messageData.parentMessageId }, { limit: 1 });
476
+ if (!found) return { success: false, delivered: false, deferred: true };
477
+ await triggerTemplateRecovery(found, { source: 'preemptive' });
478
+ return { success: true, messageId: String(found._id), status: 'queued', preemptive: true, delivered: false, deferred: true };
479
+ }
480
+ const saveFn = this.messageStorage.savePendingMessage.bind(this.messageStorage);
481
+ return this.phiProcessor.outDataFromPlain(
482
+ {
483
+ ...messageData,
484
+ provider: 'twilio',
485
+ fromMe: true,
486
+ processed: messageData.processed ?? false,
487
+ },
488
+ saveFn,
489
+ async ({ body, _id }) => {
490
+ // triggerTemplateRecovery swallows its own errors and returns undefined. Reporting "queued"
491
+ // regardless is how a template that was never created still counts as an outreach, and the
492
+ // weekly guard then stops us ever trying again.
493
+ const queued = await triggerTemplateRecovery({ _id, body, numero: messageData.code, media: messageData.media }, { source: 'preemptive' });
494
+ if (!queued?.deferred) {
495
+ logger.error('[NexusMessaging] template recovery setup failed; message not queued', { code: messageData.code, messageId: String(_id) });
496
+ return { success: false, messageId: String(_id), status: 'failed', preemptive: true, delivered: false, deferred: false };
497
+ }
498
+ return { success: true, messageId: String(_id), status: 'queued', preemptive: true, delivered: false, deferred: true };
499
+ },
500
+ { onSaved: messageData.onParentMessageId },
501
+ );
502
+ }
503
+
296
504
  async sendAssistantReply(messageData) {
505
+ if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
506
+ if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
507
+ const contact = await replyContactFor(messageData.code);
508
+ if (contact) messageData = { ...messageData, ...contact };
509
+ }
510
+ if (messageData.outreachStartedAt) {
511
+ const patientActivity = await getMessages({
512
+ numero: messageData.code,
513
+ from_me: false,
514
+ createdAt: { $gte: new Date(messageData.outreachStartedAt) },
515
+ }, { limit: 1 });
516
+ if (patientActivity?.length) {
517
+ logger.info('[NexusMessaging] proactive send cancelled — patient became active', { code: messageData.code });
518
+ return { success: false, messageId: null, status: 'patient_active', delivered: false, deferred: false };
519
+ }
520
+ if (await botIsPaused(messageData.code, { label: '[NexusMessaging]' })) {
521
+ logger.info('[NexusMessaging] proactive send cancelled — bot paused by the team', { code: messageData.code });
522
+ return { success: false, messageId: null, status: 'bot_paused', delivered: false, deferred: false };
523
+ }
524
+ }
297
525
  if (!this.provider) throw new Error('No provider initialized');
298
526
 
299
527
  if (messageData.parentMessageId) {
300
528
  return this._transport(messageData);
301
529
  }
302
530
 
531
+ // Proactive outreach lands days after the patient last wrote, so the session is usually closed.
532
+ // Waiting for Twilio 63016 to bounce would delay every message in the batch by a round-trip.
533
+ if (messageData.preemptiveWindowRoute && this._needsTemplateRoute(messageData)
534
+ && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
535
+ try {
536
+ messageData = await buildOutreachCarrier(messageData, {
537
+ provider: this.provider,
538
+ config: this.config.outreach || {},
539
+ });
540
+ } catch (error) {
541
+ logger.error('[NexusMessaging] outreach carrier rejected; message not sent', {
542
+ code: messageData.code,
543
+ reason: error.message,
544
+ });
545
+ return { success: false, messageId: null, status: 'carrier_rejected', delivered: false, deferred: false, reason: error.message };
546
+ }
547
+ }
548
+
303
549
  if (!this._providerStores) {
304
550
  const decodedBody = await this.phiProcessor.decodeBody(messageData.body, messageData.code);
551
+ const stores = Boolean(this.messageStorage?.saveMessage);
552
+ const encodedBody = stores
553
+ ? await this.phiProcessor.encodeAroundTokens(messageData.body, messageData.code)
554
+ : null;
305
555
  const result = await this._transport({ ...messageData, body: decodedBody });
306
- if (this.messageStorage?.saveMessage) {
556
+ if (stores) {
307
557
  await this.messageStorage.saveMessage({
308
- ...messageData,
558
+ ...messageData, body: encodedBody, plainBody: decodedBody,
309
559
  messageId: result?.messageId, provider: result?.provider,
310
560
  fromMe: true, processed: true, origin: messageData.origin || 'assistant',
561
+ ...unsentStatusInfo(result),
311
562
  });
312
563
  }
313
564
  return result;
@@ -330,6 +581,7 @@ class NexusMessaging {
330
581
  if (!this._providerStores) return false;
331
582
  if (messageData.contentSid) return false;
332
583
  if (!messageData.code) return false;
584
+ if (!isOutboundAllowed(messageData.contactCode || messageData.code)) return false;
333
585
  return true;
334
586
  }
335
587
 
@@ -347,12 +599,13 @@ class NexusMessaging {
347
599
  return { ...(job || {}), delivered: false, deferred: true };
348
600
  }
349
601
 
350
- async scheduleTemplateApproval({ templateSid, messageId, originalMessageSid = null, attempt = 0 }) {
602
+ async scheduleTemplateApproval({ templateSid, messageId, originalMessageSid = null, attempt = 0, delayMs }) {
351
603
  return await this.templateApprovalJob.schedule({
352
604
  templateSid,
353
605
  messageId,
354
606
  originalMessageSid,
355
- attempt
607
+ attempt,
608
+ ...(delayMs != null && { delayMs })
356
609
  });
357
610
  }
358
611
 
@@ -360,7 +613,14 @@ class NexusMessaging {
360
613
  * INBOUND MESSAGE PROCESSING
361
614
  */
362
615
 
363
- async processIncomingMessage(messageData) {
616
+ async processIncomingMessage(messageData, { onSaved = null } = {}) {
617
+ await remapCaregiverSender(messageData);
618
+ if (messageData.contactName) {
619
+ messageData.contactLabel = await maskCaregiverLabel(messageData.contactName, messageData.code, this.phiProcessor).catch((error) => {
620
+ logger.error('[processIncomingMessage] Caregiver name could not be masked; the model sees the role only', { error: error.message });
621
+ return null;
622
+ });
623
+ }
364
624
  const chatId = messageData.code;
365
625
 
366
626
  if (chatId) {
@@ -376,29 +636,58 @@ class NexusMessaging {
376
636
  messageData,
377
637
  this._saveMessageFn,
378
638
  async ({ body }) => {
639
+ const plainText = messageData.body;
379
640
  messageData = { ...messageData, body };
641
+ if (chatId) {
642
+ // This is the common ingress for text, media, buttons, lists, and flows. Retire turn-loss
643
+ // recovery here, before specialized handlers split off, so all patient activity counts.
644
+ await cancelPendingFollowUps({ code: chatId, recoveryOnly: true }).catch(error =>
645
+ logger.error('[processIncomingMessage] Follow-up stand-down failed', { code: chatId, error: error.message })
646
+ );
647
+ if (isContingencyCancelOnReplyLive()) {
648
+ await cancelContingencies({ patientCode: chatId }).catch(error =>
649
+ logger.error('[processIncomingMessage] Contingency stand-down failed', { code: chatId, error: error.message })
650
+ );
651
+ }
652
+ await releaseHeldMessages(chatId, { contactCode: messageData.contactCode || null }).catch(error =>
653
+ logger.error('[processIncomingMessage] Held message release failed', { code: chatId, error: error.message })
654
+ );
655
+ }
380
656
  if (chatId && hasPreprocessingHandler()) {
381
- const stop = await invokePreprocessingHandler({ code: chatId, context: 'incomingMessage', message: messageData });
382
- if (stop) return;
657
+ const claim = await runPreprocessingHandler({ code: chatId, context: 'incomingMessage', message: messageData });
658
+ if (claim.handled) {
659
+ if (claim.alert) await alertOpsForClaimedMessage({ code: chatId, alert: claim.alert, text: plainText });
660
+ return;
661
+ }
383
662
  }
384
663
 
385
- if (messageData.flow) return this.handleFlow(messageData);
386
- if (messageData.interactive) return this.handleInteractive(messageData);
387
- if (messageData.command) return this.handleCommand(messageData);
388
- if (messageData.keyword) return this.handleKeyword(messageData);
664
+ const route = unbatchedRoutes[messageData.type];
665
+ if (route) return this[route](messageData);
389
666
 
390
667
  if (this.batchingConfig.enabled && chatId) return this._handleWithCheckAfter(chatId);
391
- return messageData.media ? this.handleMedia(messageData) : this.handleMessage(messageData);
668
+ return messageData.type === 'media' ? this.handleMedia(messageData) : this.handleMessage(messageData);
392
669
  },
670
+ { onSaved: typeof onSaved === 'function' ? (messageId) => this._notifySaved(onSaved, messageId, chatId) : null },
393
671
  );
394
672
  }
395
673
 
674
+ async _notifySaved(onSaved, messageId, chatId) {
675
+ try {
676
+ await onSaved(messageId);
677
+ } catch (error) {
678
+ logger.warn('[processIncomingMessage] The saved-message callback failed; the turn continues', {
679
+ code: chatId, error: error?.message ?? String(error),
680
+ });
681
+ }
682
+ }
683
+
396
684
  async handleMessage(messageData) {
397
685
  if (this.handlers.onMessage) return await this.handlers.onMessage(messageData, this);
398
686
  return await this.handleMessageWithAssistant(messageData);
399
687
  }
400
688
 
401
689
  async handleInteractive(messageData) {
690
+ await invokeInteractiveRoute(messageData);
402
691
  if (this.handlers.onInteractive) return await this.handlers.onInteractive(messageData, this);
403
692
  }
404
693
 
@@ -417,8 +706,6 @@ class NexusMessaging {
417
706
 
418
707
  async handleFlow(messageData) {
419
708
  if (this.handlers.onFlow) return await this.handlers.onFlow(messageData, this);
420
- // Backward compatibility for consumers who don't have onFlow handler
421
- if (this.handlers.onInteractive) return await this.handlers.onInteractive(messageData, this);
422
709
  }
423
710
 
424
711
  /*
@@ -426,11 +713,12 @@ class NexusMessaging {
426
713
  */
427
714
 
428
715
  async handleMessageWithAssistant(messageData) {
429
- const { from, body, isInteractive } = messageData;
430
- if (isInteractive || !from || !body) return;
716
+ const { from, body } = messageData;
717
+ if (!from || !body) return;
718
+ if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
431
719
 
432
720
  try {
433
- const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
721
+ const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
434
722
  await this.assistantProcessor.sendResponse(from, result);
435
723
  } catch (error) {
436
724
  logger.error('Error in handleMessageWithAssistant', { error: error.message });
@@ -440,9 +728,10 @@ class NexusMessaging {
440
728
  async handleMediaWithAssistant(messageData) {
441
729
  const { from } = messageData;
442
730
  if (!from) return;
731
+ if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
443
732
 
444
733
  try {
445
- const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
734
+ const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
446
735
  await this.assistantProcessor.sendResponse(from, result);
447
736
  } catch (error) {
448
737
  logger.error('Error in handleMediaWithAssistant', { error: error.message });
@@ -453,160 +742,621 @@ class NexusMessaging {
453
742
  * PROCESSING PIPELINE
454
743
  */
455
744
 
456
- async _executeWithPipeline(chatId, type, mode, executeFn) {
745
+ async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSendSettled = null } = {}) {
457
746
  let capturedResult = null;
747
+ const discardResponseFn = async (result) => {
748
+ await this.assistantProcessor.discardResponse(chatId, result);
749
+ };
458
750
 
459
751
  const processingFn = async (runId) => {
460
752
  const shouldContinue = () => this.batchingManager.isActiveRun(chatId, runId);
461
753
  capturedResult = await this.pipeline.run(
462
754
  { chatId, runId, type },
463
755
  executeFn,
464
- shouldContinue
756
+ shouldContinue,
757
+ discardResponseFn,
465
758
  );
466
759
  return capturedResult;
467
760
  };
468
761
 
469
762
  const sendResponseFn = async (result) => {
470
- await this.assistantProcessor.sendResponse(chatId, result);
763
+ if (!sendResponse) return;
764
+ if (result?.turnId && !this.batchingManager.isActiveRun(chatId, result.turnId)) {
765
+ await discardResponseFn(result);
766
+ return;
767
+ }
768
+ try {
769
+ await this.assistantProcessor.sendResponse(chatId, result);
770
+ } catch (error) {
771
+ await onSendSettled?.('threw');
772
+ throw error;
773
+ }
774
+ await onSendSettled?.(result?.delivery ? deliveryOutcome(result.delivery) : 'not_sent');
471
775
  };
472
776
 
473
- if (mode === 'queue') {
474
- await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn);
475
- } else {
476
- await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
477
- }
777
+ const admission = mode === 'queue'
778
+ ? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn)
779
+ : await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn);
780
+
781
+ if (admission?.accepted === false) return { deferred: true, reason: admission.reason };
478
782
 
479
783
  return capturedResult;
480
784
  }
481
785
 
482
786
  async _handleWithCheckAfter(chatId) {
483
- await this._executeWithPipeline(chatId, 'message', 'preempt',
484
- async (preProcessResult, shouldContinue, runId) => {
485
- return await this._processMessages(chatId, async () => {
486
- const resolved = await this.assistantProcessor.resolveThread(chatId);
487
- if (!resolved) return null;
488
-
489
- const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
490
-
491
- await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
492
- this.phiProcessor.inData(
493
- { body: u.processedContent, code: chatId },
494
- ({ body: encoded }) => updateMessage(
495
- { message_id: u.message_id },
496
- { $set: {
497
- assistant_id: u.assistantId,
498
- thread_id: u.threadId,
499
- 'media.metadata.processedContent': encoded,
500
- }}
501
- ),
502
- () => null,
503
- )
504
- ));
505
-
506
- if (!preProcessed.shouldProcess) return null;
507
-
508
- const result = await this.assistantProcessor.executeLLM(
509
- resolved.thread, resolved.assistant,
510
- { prePromptResult: preProcessResult, shouldContinue, runId },
511
- preProcessed.messages[0]
512
- );
787
+ return await this._executeWithPipeline(chatId, 'message', 'preempt',
788
+ async (preProcessResult, shouldContinue, runId) =>
789
+ this._runPatientTurn(chatId, preProcessResult, shouldContinue, runId)
790
+ );
791
+ }
513
792
 
514
- if (storeRunMetrics) await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
515
- return { ...result, timings: preProcessed.timings };
516
- }, shouldContinue);
517
- }
793
+ async recoverInboundTurn(code, { confirmStillUnanswered = null } = {}) {
794
+ return await this._executeWithPipeline(code, 'message', 'queue',
795
+ async (preProcessResult, shouldContinue, runId) =>
796
+ this._runPatientTurn(code, preProcessResult, shouldContinue, runId, { confirmStillUnanswered })
518
797
  );
519
798
  }
520
799
 
521
- async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
800
+ async _runPatientTurn(chatId, preProcessResult, shouldContinue, runId, { confirmStillUnanswered = null } = {}) {
801
+ return await this._processMessages(chatId, async () => {
802
+ const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
803
+ logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
804
+ return null;
805
+ });
806
+ if (!resolved) {
807
+ await coverUnansweredPatient({ code: chatId, reason: UNASSIGNED });
808
+ return null;
809
+ }
810
+
811
+ await coverIfUnassigned({ code: chatId, thread: resolved.thread });
812
+
813
+ const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
814
+
815
+ await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
816
+ this.phiProcessor.inData(
817
+ { body: u.processedContent, code: chatId },
818
+ ({ body: encoded }) => updateMessage(
819
+ { message_id: u.message_id },
820
+ { $set: {
821
+ assistant_id: u.assistantId,
822
+ thread_id: u.threadId,
823
+ 'media.metadata.processedContent': encoded,
824
+ }}
825
+ ),
826
+ () => null,
827
+ )
828
+ ));
829
+
830
+ if (!preProcessed.shouldProcess) return null;
831
+
832
+ if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
833
+ logger.info('[inboundRecovery] a reply landed while the replay was queued; standing down', { code: chatId });
834
+ return null;
835
+ }
836
+
837
+ const result = await this.assistantProcessor.executeLLM(
838
+ resolved.thread, resolved.assistant,
839
+ { prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
840
+ preProcessed.messages[0]
841
+ );
842
+
843
+ if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
844
+ logger.info('[inboundRecovery] a reply landed while the replay was generating; discarding it', { code: chatId });
845
+ await this.assistantProcessor.discardResponse?.(chatId, result);
846
+ return null;
847
+ }
848
+
849
+ try {
850
+ if (storeRunMetrics) {
851
+ await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
852
+ }
853
+ } catch (error) {
854
+ await this.assistantProcessor.discardResponse?.(chatId, result);
855
+ throw error;
856
+ }
857
+ return { ...result, timings: preProcessed.timings };
858
+ }, shouldContinue, runId);
859
+ }
860
+
861
+ /*
862
+ * `beforeRun`, when given, is asked under the chat lock right before the turn (and before every retry);
863
+ * a truthy reason vetoes the turn. Such a gated instruction never rides along in another instruction's
864
+ * batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
865
+ * run behind its own gate.
866
+ */
867
+ async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0 } = {}) {
868
+ if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs)) {
869
+ logger.info('[processInstruction] Identical instruction already answered; skipping the resend', { code, triggeredBy: triggeredBy || null });
870
+ return { outcome: 'duplicate' };
871
+ }
872
+ const receivedAt = Date.now();
522
873
  const messageData = {
523
874
  pushName: 'Instruction',
524
875
  code,
525
876
  body: instruction,
526
877
  messageId: `instruction_${Date.now()}_${Math.random().toString(36).substring(7)}`,
527
878
  fromMe: true,
528
- processed: true,
879
+ processed: false,
529
880
  origin: 'instruction',
530
- raw: { role },
881
+ raw: beforeRun ? { role, gated: true } : { role },
531
882
  triggeredBy: triggeredBy || null,
532
883
  silent: true,
533
884
  };
534
885
 
535
- const result = await this.phiProcessor.inData(
536
- messageData,
537
- this._saveMessageFn,
538
- ({ body }) => this._executeWithPipeline(code, 'instruction', 'queue',
539
- async (preProcessResult, _shouldContinue, runId) => this.assistantProcessor.process({
540
- code,
541
- runOptions: {
542
- prePromptResult: preProcessResult,
543
- additionalInstructions: body,
544
- toolChoice: 'none',
545
- runId,
886
+ beginInstruction(code);
887
+ try {
888
+ return await this.phiProcessor.inData(
889
+ messageData,
890
+ this._saveMessageFn,
891
+ async ({ body, _id }) => {
892
+ if (this.batchingConfig.instructionSettleMs > 0 && !this.batchingManager.isDraining()) {
893
+ await new Promise(resolve => setTimeout(resolve, this.batchingConfig.instructionSettleMs));
546
894
  }
547
- }),
548
- ),
549
- );
895
+ const markOwnProcessed = async () => {
896
+ if (!_id) return;
897
+ try {
898
+ await updateMessage({ _id }, { $set: { processed: true } });
899
+ } catch (err) {
900
+ logger.error('[processInstruction] Could not mark a gated instruction processed', { error: err.message, code });
901
+ }
902
+ };
903
+ let batchIds = [];
904
+ let outcome = null;
905
+ let runId = null;
906
+ let gate = null;
907
+ let alreadyAnswered = false;
908
+ let duplicate = false;
909
+ const answerPending = () => {
910
+ batchIds = [];
911
+ outcome = null;
912
+ runId = null;
913
+ gate = null;
914
+ alreadyAnswered = false;
915
+ duplicate = false;
916
+ return this._executeWithPipeline(code, 'instruction', 'queue',
917
+ async (preProcessResult, shouldContinue, currentRunId) => {
918
+ runId = currentRunId;
919
+ if (beforeRun) {
920
+ try {
921
+ const reason = await beforeRun();
922
+ if (reason) gate = { outcome: 'gated', reason };
923
+ } catch (err) {
924
+ gate = { outcome: 'gate_error', error: err.message };
925
+ }
926
+ if (gate) {
927
+ await markOwnProcessed();
928
+ return null;
929
+ }
930
+ }
931
+ if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id)) {
932
+ logger.info('[processInstruction] Identical instruction answered while this one waited; skipping it', { code, triggeredBy: triggeredBy || null });
933
+ duplicate = true;
934
+ await markOwnProcessed();
935
+ return null;
936
+ }
937
+ const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
938
+ if (!batch.length) {
939
+ logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
940
+ alreadyAnswered = true;
941
+ return null;
942
+ }
943
+ batchIds = batch.map(m => m._id).filter(Boolean);
944
+ return this.assistantProcessor.process({
945
+ code,
946
+ runOptions: {
947
+ prePromptResult: preProcessResult,
948
+ additionalInstructions: batch.map(m => m.body).join('\n\n'),
949
+ toolChoice: 'none',
950
+ turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
951
+ runId,
952
+ shouldContinue,
953
+ signal: this.batchingManager.getAbortSignal(runId),
954
+ }
955
+ });
956
+ },
957
+ {
958
+ onSendSettled: async (settled) => {
959
+ outcome = settled;
960
+ if (!batchIds.length || (settled !== 'sent' && settled !== 'unknown')) return;
961
+ try {
962
+ await updateMessage({ _id: { $in: batchIds } }, { $set: { processed: true } });
963
+ } catch (err) {
964
+ logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
965
+ }
966
+ },
967
+ },
968
+ );
969
+ };
970
+ const needsAnotherTurn = () => batchIds.length > 0
971
+ && ((outcome === null && this.batchingManager.isAbandoned(runId)) || outcome === 'known_not_sent');
972
+
973
+ const answer = async () => {
974
+ try {
975
+ return await answerPending();
976
+ } catch (err) {
977
+ if (beforeRun && err instanceof DrainingError) await markOwnProcessed();
978
+ throw err;
979
+ }
980
+ };
981
+ await answer();
982
+ if (needsAnotherTurn()) {
983
+ logger.warn('[processInstruction] Instruction reply was not sent; queueing one more turn', { code, outcome });
984
+ await answer();
985
+ }
986
+ if (batchIds.length && outcome !== 'sent' && outcome !== 'unknown') {
987
+ logger.error('[processInstruction] Instruction left unanswered', { code, outcome, instructionIds: batchIds.map(String) });
988
+ }
989
+ // Only the send outcome goes back: the turn's output was already delivered, and handing it to
990
+ // the caller would invite a second send.
991
+ if (gate) return gate;
992
+ if (duplicate) return { outcome: 'duplicate' };
993
+ return { outcome: outcome === null && alreadyAnswered ? 'already_answered' : outcome };
994
+ },
995
+ );
996
+ } finally {
997
+ endInstruction(code);
998
+ }
999
+ }
550
1000
 
551
- return result?.output || null;
1001
+ async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null) {
1002
+ try {
1003
+ const rows = await getMessages(
1004
+ {
1005
+ numero: code,
1006
+ origin: 'instruction',
1007
+ message_id: /^instruction_/,
1008
+ plainBody: instruction,
1009
+ processed: true,
1010
+ 'raw.gated': { $ne: true },
1011
+ createdAt: { $gte: new Date(Date.now() - windowMs) },
1012
+ ...(ownId ? { _id: { $ne: ownId } } : {}),
1013
+ },
1014
+ { sort: { _id: -1 }, limit: 1, select: '_id' },
1015
+ );
1016
+ return Array.isArray(rows) && rows.length > 0;
1017
+ } catch (err) {
1018
+ logger.error('[processInstruction] Could not check for an answered duplicate', { error: err.message, code });
1019
+ return false;
1020
+ }
552
1021
  }
553
1022
 
554
- async processSystemMessage(code, messages, role = 'system', { triggeredBy, reply = true } = {}) {
555
- const thread = await Thread.findOne({ code }).lean();
556
- if (!thread) return null;
1023
+ async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
1024
+ if (!ownId) return [{ _id: null, body: ownBody }];
1025
+ try {
1026
+ const rows = await getMessages(
1027
+ {
1028
+ numero: code,
1029
+ origin: 'instruction',
1030
+ message_id: /^instruction_/,
1031
+ $or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
1032
+ },
1033
+ { sort: { _id: 1 }, select: '_id body processed' },
1034
+ );
1035
+ const own = rows.find(m => String(m._id) === String(ownId));
1036
+ if (own?.processed) return [];
1037
+ const batch = rows.filter(m => m === own || !m.processed).map(m => (m === own ? { _id: ownId, body: ownBody } : m));
1038
+ return own ? batch : [...batch, { _id: ownId, body: ownBody }];
1039
+ } catch (err) {
1040
+ logger.error('[processInstruction] Could not read pending instructions', { error: err.message, code });
1041
+ return [{ _id: ownId, body: ownBody }];
1042
+ }
1043
+ }
1044
+
1045
+ /*
1046
+ * A turn nobody asked for: no inbound message, and no obligation to produce an outbound.
1047
+ * Unlike processInstruction this keeps the full clinical toolset and lets the agent end in a hold,
1048
+ * so the decision of whether the patient hears from us is the agent's, not the scheduler's.
1049
+ * Returns the decision record and never the message text — the send already happened downstream
1050
+ * (see the duplicate-send contract on processInstruction).
1051
+ */
1052
+ async processOutreach(code, {
1053
+ brief = null,
1054
+ triggeredBy = null,
1055
+ reason = null,
1056
+ firstName = null,
1057
+ reminderType = 'seguimiento',
1058
+ reminderPrefix = null,
1059
+ replyToContact = false,
1060
+ allowFollowUp = true,
1061
+ dryRun = false,
1062
+ } = {}) {
1063
+ const outreachStartedAt = new Date().toISOString();
1064
+ const messageData = {
1065
+ pushName: 'Outreach',
1066
+ code,
1067
+ body: JSON.stringify({ reason, brief }),
1068
+ messageId: `outreach_${Date.now()}_${Math.random().toString(36).substring(7)}`,
1069
+ fromMe: true,
1070
+ processed: false,
1071
+ // 'instruction' is the one origin DefaultMemoryManager excludes from context, so this row is an
1072
+ // audit record only: a weekly brief must never come back as a standing rule in later turns.
1073
+ origin: 'instruction',
1074
+ raw: { role: 'developer', kind: 'proactive_outreach' },
1075
+ triggeredBy: triggeredBy || null,
1076
+ silent: true,
1077
+ };
1078
+
1079
+ let runResult = null;
1080
+ const executeTurn = () => this._executeWithPipeline(code, 'outreach', 'queue',
1081
+ async (preProcessResult, shouldContinue, runId) => this.assistantProcessor.process({
1082
+ code,
1083
+ runOptions: {
1084
+ prePromptResult: preProcessResult,
1085
+ shouldContinue,
1086
+ signal: this.batchingManager.getAbortSignal(runId),
1087
+ toolChoice: 'auto',
1088
+ turnKind: TURN_KIND.PROACTIVE_OUTREACH,
1089
+ outreachBrief: brief,
1090
+ preemptiveWindowRoute: true,
1091
+ outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1092
+ outreachAllowsFollowUp: allowFollowUp,
1093
+ outreachStartedAt,
1094
+ // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1095
+ triggeredBy: triggeredBy || null,
1096
+ shadow: dryRun,
1097
+ runId,
1098
+ }
1099
+ }),
1100
+ { sendResponse: !dryRun });
557
1101
 
558
- const normalizedMessages = Array.isArray(messages) ? messages : [messages];
1102
+ if (dryRun) {
1103
+ runResult = await runInShadowScope(executeTurn);
1104
+ } else {
1105
+ await this.phiProcessor.inData(
1106
+ messageData,
1107
+ this._saveMessageFn,
1108
+ async ({ _id }) => {
1109
+ runResult = await executeTurn();
1110
+ if (_id) {
1111
+ try {
1112
+ await updateMessage({ _id }, { $set: { processed: true } });
1113
+ } catch (err) {
1114
+ logger.error('[processOutreach] Could not mark outreach processed', { error: err.message, code });
1115
+ }
1116
+ }
1117
+ return runResult;
1118
+ },
1119
+ );
1120
+ }
559
1121
 
560
- for (let i = 0; i < normalizedMessages.length; i++) {
1122
+ // The pipeline returns null when the turn was superseded or a preProcess hook skipped it. That is
1123
+ // not the agent choosing to stay quiet, and counting it as a hold would flatter the hold rate.
1124
+ if (!runResult) {
1125
+ return { decision: 'skipped', rationale: '', holdReason: 'turn_not_run', nextCheckAt: null, delivered: false, turnId: null, traceId: null };
1126
+ }
1127
+ if (runResult.skipped) {
1128
+ return { decision: 'skipped', rationale: '', holdReason: runResult.skipped, nextCheckAt: null, delivered: false, turnId: runResult.turnId || null, traceId: runResult.traceId || null };
1129
+ }
1130
+
1131
+ const decision = runResult.signals?.outreachDecision || null;
1132
+ if (!decision) throw new Error('OUTREACH_DECISION_MISSING');
1133
+
1134
+ // What reached her is a fact about the send, not about the tool call. A `write` whose delivery
1135
+ // was deferred or failed has not been written, and a `hold` that still delivered has. Callers
1136
+ // stamp their records off `delivered`; `decision` records only what the agent said it intended.
1137
+ //
1138
+ // Fail closed: this requires a positive `success` from the transport rather than the absence of a
1139
+ // failure, so a provider that returns nothing or a malformed result reads as not delivered. The
1140
+ // recovery path reports `success: true, delivered: false` for a queued template, which is not a
1141
+ // send either.
1142
+ const delivery = runResult.delivery || null;
1143
+ if (delivery?.status === 'patient_active') {
1144
+ return { decision: 'skipped', rationale: 'la paciente escribió durante la decisión', holdReason: 'patient_active', nextCheckAt: null, draft: null, accepted: false, delivered: false, deferred: false, deliveryStatus: 'patient_active', turnId: runResult.turnId || null, traceId: runResult.traceId || null };
1145
+ }
1146
+ if (delivery?.status === 'bot_paused') {
1147
+ return { decision: 'skipped', rationale: 'el equipo pausó el bot durante la decisión', holdReason: 'bot_paused', nextCheckAt: null, draft: null, accepted: false, delivered: false, deferred: false, deliveryStatus: 'bot_paused', turnId: runResult.turnId || null, traceId: runResult.traceId || null };
1148
+ }
1149
+ const accepted = Boolean(runResult.output) && delivery?.success === true && delivery?.deferred !== true;
1150
+ const delivered = ['delivered', 'read'].includes(String(delivery?.status || '').toLowerCase());
1151
+ let carrierRejection = null;
1152
+ if (dryRun && decision.decision === 'write') {
561
1153
  try {
562
- const messageData = {
563
- pushName: 'System',
564
- code,
565
- body: normalizedMessages[i],
566
- messageId: `system_${Date.now()}_${i}_${Math.random().toString(36).substring(7)}`,
567
- fromMe: true,
568
- processed: true,
569
- origin: 'system',
570
- raw: { role },
571
- triggeredBy: triggeredBy || null,
572
- silent: true,
573
- };
574
- await this.phiProcessor.inData(messageData, this._saveMessageFn, () => {});
575
- } catch (err) {
576
- logger.error('[processSystemMessage] Error saving system message', { error: err.message, code, index: i });
1154
+ validateAgentText(runResult.output, firstName);
1155
+ } catch (error) {
1156
+ carrierRejection = error.message;
1157
+ }
1158
+ }
1159
+ if (!dryRun && (decision.decision === 'write') !== accepted) {
1160
+ logger.warn('[processOutreach] decision and delivery disagree', {
1161
+ code, decision: decision.decision, accepted, status: delivery?.status || null,
1162
+ });
1163
+ }
1164
+
1165
+ return {
1166
+ decision: decision.decision,
1167
+ rationale: decision.rationale || '',
1168
+ holdReason: decision.holdReason || null,
1169
+ nextCheckAt: decision.nextCheckAt || null,
1170
+ draft: dryRun ? (runResult.output || '') : null,
1171
+ carrierRejection,
1172
+ accepted,
1173
+ delivered,
1174
+ deferred: Boolean(delivery?.deferred),
1175
+ deliveryStatus: delivery?.status || null,
1176
+ turnId: runResult.turnId || null,
1177
+ traceId: runResult.traceId || null,
1178
+ };
1179
+ }
1180
+
1181
+ async processCheckInDue(code, { reminderId, type, question = '', firstName = null } = {}) {
1182
+ if (!code || !reminderId) throw new Error('code and reminderId are required');
1183
+ const claim = await acquireSendClaim({ idempotencyKey: `checkin-due:${reminderId}`, code });
1184
+ if (!claim.acquired) return { decision: 'skipped', holdReason: 'duplicate', sent: false };
1185
+
1186
+ let plan = null;
1187
+ let dispatched = false;
1188
+ try {
1189
+ plan = await planCheckInDue({ code, reminderId, type, question, firstName });
1190
+ if (plan.mode === 'stale') {
1191
+ await settleCheckInRow({ code, reminderId, reason: plan.reason, requireActive: true });
1192
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1193
+ await completeSendClaim(claim.claimId);
1194
+ return { decision: 'skipped', holdReason: plan.reason, sent: false };
577
1195
  }
1196
+ dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1197
+ if (!dispatched) {
1198
+ await completeSendClaim(claim.claimId);
1199
+ return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1200
+ }
1201
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1202
+
1203
+ const triggeredBy = checkInTriggeredBy(reminderId);
1204
+ let result;
1205
+ if (plan.mode === 'mandatory') {
1206
+ const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1207
+ const sent = outcome === 'sent' || outcome === 'unknown';
1208
+ result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1209
+ } else {
1210
+ const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1211
+ result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1212
+ }
1213
+
1214
+ const settled = result.sent
1215
+ ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1216
+ : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1217
+ if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1218
+ await completeSendClaim(claim.claimId);
1219
+ return result;
1220
+ } catch (error) {
1221
+ logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1222
+ if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1223
+ await releaseSendClaim(claim.claimId);
1224
+ throw error;
578
1225
  }
1226
+ }
579
1227
 
580
- if (!reply) return null;
1228
+ async _fireCheckInNet(code, planId, reminderId) {
1229
+ if (!planId) return;
1230
+ try {
1231
+ const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1232
+ if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1233
+ } catch (error) {
1234
+ logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1235
+ }
1236
+ }
581
1237
 
582
- const result = await this._executeWithPipeline(code, 'system', 'queue',
583
- async (preProcessResult, _shouldContinue, runId) => {
584
- return await this.assistantProcessor.process({
1238
+ async _retireSkippedFollowUp(code, reminderId, holdReason) {
1239
+ const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1240
+ if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
1241
+ return { decision: 'skipped', holdReason, accepted: false, delivered: false, retired };
1242
+ }
1243
+
1244
+ /*
1245
+ * Delivers a message the agent previously authored and scheduled with schedulePatientReminder.
1246
+ * The clock only wakes this method; it does not choose copy or timing. Running inside the same
1247
+ * patient queue as inbound WhatsApp traffic prevents an already-received message from crossing
1248
+ * the follow-up.
1249
+ */
1250
+ async processScheduledFollowUp(code, { reminderId, firstName, now = new Date() } = {}) {
1251
+ if (!code || !reminderId) throw new Error('code and reminderId are required');
1252
+ if (typeof firstName !== 'string' || !firstName.trim()) throw new Error('firstName is required');
1253
+ const startedAt = new Date(now);
1254
+ if (Number.isNaN(startedAt.getTime())) throw new Error('now must be a valid date');
1255
+
1256
+ let result = null;
1257
+ await this._executeWithPipeline(code, 'outreach', 'queue', async () => {
1258
+ const plan = await readPendingReminderForPatient({ code, reminderId });
1259
+ if (!plan) {
1260
+ result = { decision: 'skipped', holdReason: 'plan_not_pending', accepted: false, delivered: false };
1261
+ return result;
1262
+ }
1263
+
1264
+ const fireAt = plan.fireAt ? new Date(plan.fireAt) : null;
1265
+ if (fireAt && !Number.isNaN(fireAt.getTime()) && fireAt.getTime() > startedAt.getTime() + 60000) {
1266
+ result = { decision: 'skipped', holdReason: 'not_due', accepted: false, delivered: false };
1267
+ return result;
1268
+ }
1269
+ const expiresAt = plan.expiresAt ? new Date(plan.expiresAt) : null;
1270
+ if (expiresAt && !Number.isNaN(expiresAt.getTime()) && expiresAt.getTime() <= startedAt.getTime()) {
1271
+ result = await this._retireSkippedFollowUp(code, reminderId, 'expired');
1272
+ return result;
1273
+ }
1274
+
1275
+ const holdReason = await hasCheckInNear({ code, withinMinutes: FOLLOW_UP_SPACING_MIN, excludeReminderId: reminderId, fireAt: plan.fireAt })
1276
+ ? 'check_in_near'
1277
+ : await followUpCollisionReason(code, reminderId, startedAt);
1278
+ if (holdReason) {
1279
+ result = await this._retireSkippedFollowUp(code, reminderId, holdReason);
1280
+ return result;
1281
+ }
1282
+
1283
+ const claim = await acquireSendClaim({ idempotencyKey: `followup:${reminderId}`, code });
1284
+ if (!claim.acquired) {
1285
+ if (!claim.completed) {
1286
+ result = { decision: 'skipped', holdReason: 'send_in_progress', accepted: false, delivered: false };
1287
+ return result;
1288
+ }
1289
+ const lifecycleUpdated = await markReminderSent({ code, reminderId });
1290
+ if (!lifecycleUpdated) logger.warn('[processScheduledFollowUp] reminder lifecycle update failed', { reminderId });
1291
+ result = { decision: 'write', holdReason: null, accepted: true, delivered: false, deliveryStatus: 'duplicate_suppressed', idempotent: true };
1292
+ return result;
1293
+ }
1294
+
1295
+ let delivery;
1296
+ try {
1297
+ delivery = await this.sendAssistantReply({
585
1298
  code,
586
- runOptions: {
587
- prePromptResult: preProcessResult,
588
- toolChoice: 'none',
589
- runId,
590
- }
1299
+ body: plan.message,
1300
+ processed: true,
1301
+ origin: 'assistant',
1302
+ triggeredBy: reminderId,
1303
+ idempotencyKey: `followup:${reminderId}`,
1304
+ preemptiveWindowRoute: true,
1305
+ outreachCarrier: { reminderType: plan.reminderType, firstName: firstName.trim(), utilityBasis: plan.windowReasoning },
1306
+ outreachStartedAt: startedAt.toISOString(),
591
1307
  });
1308
+ } catch (error) {
1309
+ await releaseSendClaim(claim.claimId);
1310
+ throw error;
592
1311
  }
593
- );
594
1312
 
595
- return result?.output || null;
1313
+ if (delivery?.success !== true) await releaseSendClaim(claim.claimId);
1314
+ const accepted = delivery?.success === true;
1315
+ if (accepted && !await completeSendClaim(claim.claimId)) {
1316
+ logger.warn('[processScheduledFollowUp] send claim completion failed', { reminderId });
1317
+ }
1318
+ const lifecycleUpdated = accepted ? await markReminderSent({ code, reminderId }) : false;
1319
+ if (accepted && !lifecycleUpdated) logger.warn('[processScheduledFollowUp] reminder lifecycle update failed', { reminderId });
1320
+ result = {
1321
+ decision: accepted ? 'write' : 'skipped',
1322
+ holdReason: accepted ? null : (delivery?.status || 'send_failed'),
1323
+ accepted,
1324
+ delivered: ['delivered', 'read'].includes(String(delivery?.status || '').toLowerCase()),
1325
+ deferred: delivery?.deferred === true,
1326
+ deliveryStatus: delivery?.status || null,
1327
+ };
1328
+ return result;
1329
+ }, { sendResponse: false });
1330
+
1331
+ return result;
1332
+ }
1333
+
1334
+ async processSystemMessage(code, messages, role = 'system', options = {}) {
1335
+ return processAssistantSystemMessage(code, messages, role, options, {
1336
+ messageStorage: this.messageStorage,
1337
+ saveMessage: this._saveMessageFn.bind(this),
1338
+ phiProcessor: this.phiProcessor,
1339
+ executeWithPipeline: this._executeWithPipeline.bind(this),
1340
+ assistantProcessor: this.assistantProcessor,
1341
+ getAbortSignal: this.batchingManager.getAbortSignal.bind(this.batchingManager),
1342
+ });
596
1343
  }
597
1344
 
598
- async _processMessages(chatId, processingFn, shouldFinalize = () => true) {
1345
+ async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
599
1346
  const query = { numero: chatId, from_me: false, processed: false };
600
1347
  const unprocessed = await getMessages(query, { select: '_id' });
1348
+ let result = null;
601
1349
 
602
1350
  try {
603
- const result = await processingFn();
1351
+ result = await processingFn();
604
1352
  if (unprocessed.length > 0 && shouldFinalize()) {
605
- await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: { processed: true } });
606
- logger.info('[_processMessages] Marked messages as processed', { count: unprocessed.length, chatId });
1353
+ const marks = runId ? { processed: true, processedByTurnId: runId } : { processed: true };
1354
+ await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: marks });
1355
+ logger.info('[_processMessages] Marked messages as processed', { count: unprocessed.length, chatId, runId });
607
1356
  }
608
1357
  return result;
609
1358
  } catch (error) {
1359
+ if (result) await this.assistantProcessor.discardResponse?.(chatId, result);
610
1360
  logger.debug('[_processMessages] Processing failed', { chatId });
611
1361
  throw error;
612
1362
  }
@@ -616,10 +1366,43 @@ class NexusMessaging {
616
1366
  * LIFECYCLE
617
1367
  */
618
1368
 
619
- async disconnect() {
620
- if (this.provider) await this.provider.disconnect();
621
- if (this.queueAdapter) await this.queueAdapter.shutdown();
1369
+ async shutdown({ drainMs, abortGraceMs, teardownMs = 5000 } = {}) {
1370
+ if (this._shutdownPromise) return this._shutdownPromise;
1371
+ this.batchingManager.draining = true;
1372
+ this._reconciliationStopped = Promise.resolve(this.queueReconciliation?.stop())
1373
+ .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle', { error: error.message }));
1374
+ this._shutdownPromise = this._shutdown({ drainMs, abortGraceMs, teardownMs });
1375
+ return this._shutdownPromise;
1376
+ }
1377
+
1378
+ async _shutdown({ drainMs, abortGraceMs, teardownMs }) {
1379
+ const result = await this.batchingManager.drain({
1380
+ ...(drainMs === undefined ? {} : { timeoutMs: drainMs }),
1381
+ ...(abortGraceMs === undefined ? {} : { abortGraceMs }),
1382
+ });
1383
+
1384
+ await withTimeout(this._reconciliationStopped, teardownMs, 'queueReconciliation.stop')
1385
+ .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle in time', { error: error.message }));
1386
+
1387
+ if (this.workflowRunner) this.workflowRunner.stop();
1388
+
1389
+ if (this.queueAdapter) {
1390
+ await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
1391
+ .catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
1392
+ }
1393
+
1394
+ if (typeof this.provider?.disconnect === 'function') {
1395
+ const disconnecting = Promise.resolve().then(() => this.provider.disconnect());
1396
+ await withTimeout(disconnecting, teardownMs, 'provider.disconnect')
1397
+ .catch(error => logger.warn('[NexusMessaging] Provider disconnect skipped', { error: error.message }));
1398
+ }
1399
+
622
1400
  this.events.removeAllListeners();
1401
+ return result;
1402
+ }
1403
+
1404
+ async disconnect(options = {}) {
1405
+ return this.shutdown(options);
623
1406
  }
624
1407
  }
625
1408
 
@@ -677,10 +1460,24 @@ const processInstruction = async (code, instruction, role, options) => {
677
1460
  return await requireDefaultInstance().processInstruction(code, instruction, role, options);
678
1461
  };
679
1462
 
1463
+ const processOutreach = async (code, options) => {
1464
+ return await requireDefaultInstance().processOutreach(code, options);
1465
+ };
1466
+
1467
+ const processCheckInDue = async (code, options) => {
1468
+ return await requireDefaultInstance().processCheckInDue(code, options);
1469
+ };
1470
+
1471
+ const processScheduledFollowUp = async (code, options) => {
1472
+ return await requireDefaultInstance().processScheduledFollowUp(code, options);
1473
+ };
1474
+
680
1475
  const processSystemMessage = async (code, messages, role, options) => {
681
1476
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
682
1477
  };
683
1478
 
1479
+ const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1480
+
684
1481
  const getEventBus = () => getDefaultInstance()?.getEventBus();
685
1482
 
686
1483
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -693,7 +1490,11 @@ module.exports = {
693
1490
  sendScheduledMessage,
694
1491
  scheduleTemplateApproval,
695
1492
  processInstruction,
1493
+ processOutreach,
1494
+ processCheckInDue,
1495
+ processScheduledFollowUp,
696
1496
  processSystemMessage,
1497
+ isDraining,
697
1498
  setDefaultInstance,
698
1499
  getDefaultInstance,
699
1500
  requireDefaultInstance,
@@ -701,5 +1502,6 @@ module.exports = {
701
1502
  getPhiProcessor,
702
1503
  requireProvider,
703
1504
  getEventBus,
1505
+ _test: { createDefaultLlmMonitor },
704
1506
  _resetDefaultInstance
705
1507
  };