@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.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
package/lib/index.js
CHANGED
|
@@ -20,19 +20,55 @@ const {
|
|
|
20
20
|
} = require('./clinical');
|
|
21
21
|
const { initialize: initializeFhir } = require('./fhir');
|
|
22
22
|
const { logger } = require('./utils/logger');
|
|
23
|
+
const { withTimeout } = require('./utils/timeoutUtils');
|
|
23
24
|
const runtimeConfig = require('./config/runtimeConfig');
|
|
24
25
|
const { setModelDatabases, setModelDatabase, getModelDatabase, connect: mongoConnect, disconnect: mongoDisconnect, getConnection: mongoGetConnection } = require('./config/mongoConfig');
|
|
25
26
|
const { TwilioProvider } = require('./adapters/TwilioProvider');
|
|
26
27
|
const { BaileysProvider } = require('./adapters/BaileysProvider');
|
|
27
28
|
const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHandler } = require('./services/preprocessingService');
|
|
29
|
+
const { registerInteractiveRoute, clearInteractiveRoutes } = require('./core/interactiveRouteService');
|
|
30
|
+
const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
|
|
31
|
+
const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
|
|
32
|
+
const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
|
+
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
|
+
const { configureProgram } = require('./config/programConfig');
|
|
35
|
+
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
36
|
+
const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
|
|
37
|
+
const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
|
|
38
|
+
const { startPatientProfileSync } = require('./clinical/services/patientProfileService');
|
|
39
|
+
const { profileSyncOn } = require('./clinical/flags/clinicalContextFlags');
|
|
28
40
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
29
41
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
30
|
-
const {
|
|
42
|
+
const { DrainingError } = require('./core/BatchingManager');
|
|
31
43
|
const routes = require('./routes');
|
|
32
|
-
const { resetAll } = require('./config/lifecycle');
|
|
44
|
+
const { resetAll, stopAllSweeps } = require('./config/lifecycle');
|
|
33
45
|
const { EvalProvider } = require('./eval/EvalProvider');
|
|
46
|
+
const { syncContextFacts } = require('./clinical/services/contextSyncService');
|
|
47
|
+
const { retractContentlessFacts } = require('./clinical/services/contextCleanupService');
|
|
48
|
+
const { syncLegacyContext } = require('./clinical/services/legacyContextSyncService');
|
|
49
|
+
const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
|
|
50
|
+
const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
|
|
51
|
+
const { currentRegimen } = require('./clinical/services/currentRegimenService');
|
|
52
|
+
const { closeStoppedRegimens, dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
|
|
53
|
+
const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
|
|
34
54
|
const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
|
|
35
|
-
const MapCache = require('./utils/MapCache');
|
|
55
|
+
const { MapCache } = require('./utils/MapCache');
|
|
56
|
+
const supportCandidateService = require('./clinical/services/supportCandidateService');
|
|
57
|
+
const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
|
|
58
|
+
const { registerContactCategories } = require('./services/contactGateService');
|
|
59
|
+
const supportActionService = require('./clinical/services/supportActionService');
|
|
60
|
+
const supportLightService = require('./clinical/services/supportLightService');
|
|
61
|
+
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
62
|
+
const supportLightEvaluationService = require('./clinical/services/supportLightEvaluationService');
|
|
63
|
+
const {
|
|
64
|
+
NutritionSafetyDecision,
|
|
65
|
+
FINDING_CODES,
|
|
66
|
+
FINDING_VALUES,
|
|
67
|
+
FINDING_TO_QUESTION,
|
|
68
|
+
QUESTION_CODES,
|
|
69
|
+
EVIDENCE_SOURCE_TYPES,
|
|
70
|
+
DISPOSITIONS,
|
|
71
|
+
} = require('./shared/dtos/NutritionSafetyDecision');
|
|
36
72
|
|
|
37
73
|
class Nexus {
|
|
38
74
|
constructor(config = {}) {
|
|
@@ -124,6 +160,13 @@ class Nexus {
|
|
|
124
160
|
if (options.airtable && options.airtable.apiKey) {
|
|
125
161
|
runtimeConfig.set('AIRTABLE_API_KEY', options.airtable.apiKey);
|
|
126
162
|
}
|
|
163
|
+
|
|
164
|
+
if (options.outboundAllowlist) {
|
|
165
|
+
runtimeConfig.set('OUTBOUND_ALLOWLIST', options.outboundAllowlist);
|
|
166
|
+
}
|
|
167
|
+
if (options.program) {
|
|
168
|
+
configureProgram(options.program);
|
|
169
|
+
}
|
|
127
170
|
} catch (cfgErr) {
|
|
128
171
|
logger.warn('[Nexus] convenience config warning:', cfgErr?.message || cfgErr);
|
|
129
172
|
}
|
|
@@ -165,6 +208,69 @@ class Nexus {
|
|
|
165
208
|
logger.warn('Warning: failed to register clinical tools:', e?.message || e);
|
|
166
209
|
}
|
|
167
210
|
|
|
211
|
+
ensureOnePledgePerContact().catch((e) => logger.warn('Warning: failed to enforce one pledge per contact:', e?.message || e));
|
|
212
|
+
|
|
213
|
+
try {
|
|
214
|
+
configureSafetyNet(options.safetyNet || {});
|
|
215
|
+
if (registerSafetyNetRoutes()) {
|
|
216
|
+
startSafetyNetSweep();
|
|
217
|
+
logger.info('[Nexus] paused-thread safety net armed');
|
|
218
|
+
}
|
|
219
|
+
} catch (e) {
|
|
220
|
+
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
if (options.reviewDrafts?.enabled === true) {
|
|
225
|
+
startReviewDraftSweep({ intervalMs: options.reviewDrafts.intervalMs });
|
|
226
|
+
logger.info('[Nexus] clinical review draft sweep armed');
|
|
227
|
+
}
|
|
228
|
+
} catch (e) {
|
|
229
|
+
logger.warn('Warning: failed to arm the clinical review draft sweep:', e?.message || e);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
if (profileSyncOn()) {
|
|
234
|
+
startPatientProfileSync();
|
|
235
|
+
logger.info('[Nexus] patient profile sync armed');
|
|
236
|
+
}
|
|
237
|
+
} catch (e) {
|
|
238
|
+
logger.warn('Warning: failed to arm the patient profile sync:', e?.message || e);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
if (options.reviewAlerts?.enabled === true) {
|
|
243
|
+
startReviewAlertSweep({ intervalMs: options.reviewAlerts.intervalMs });
|
|
244
|
+
logger.info('[Nexus] clinical review doctor alert sweep armed');
|
|
245
|
+
}
|
|
246
|
+
} catch (e) {
|
|
247
|
+
logger.warn('Warning: failed to arm the clinical review doctor alert sweep:', e?.message || e);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
if (options.inboundRecovery?.enabled === true) {
|
|
252
|
+
startInboundRecoverySweep({
|
|
253
|
+
recover: (code, opts) => this.messaging.recoverInboundTurn(code, opts),
|
|
254
|
+
isProcessing: (code) => this.messaging.isProcessing(code),
|
|
255
|
+
intervalMs: options.inboundRecovery.intervalMs,
|
|
256
|
+
});
|
|
257
|
+
logger.info('[Nexus] inbound recovery sweep armed');
|
|
258
|
+
}
|
|
259
|
+
} catch (e) {
|
|
260
|
+
logger.warn('Warning: failed to arm the inbound recovery sweep:', e?.message || e);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
try {
|
|
264
|
+
if (options.recommendationRecovery?.enabled === true) {
|
|
265
|
+
startRecommendationRecoverySweep({ intervalMs: options.recommendationRecovery.intervalMs });
|
|
266
|
+
logger.info('[Nexus] recommendation recovery sweep armed');
|
|
267
|
+
}
|
|
268
|
+
} catch (e) {
|
|
269
|
+
logger.warn('Warning: failed to arm the recommendation recovery sweep:', e?.message || e);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
await this.messaging.initializeLlmMonitor();
|
|
273
|
+
|
|
168
274
|
this.isInitialized = true;
|
|
169
275
|
}
|
|
170
276
|
|
|
@@ -186,7 +292,14 @@ class Nexus {
|
|
|
186
292
|
return await this.messaging.sendScheduledMessage(scheduledMessage);
|
|
187
293
|
}
|
|
188
294
|
|
|
189
|
-
async
|
|
295
|
+
async processScheduledFollowUp(code, options) {
|
|
296
|
+
if (!this.isInitialized) {
|
|
297
|
+
throw new Error('Nexus not initialized. Call initialize() first.');
|
|
298
|
+
}
|
|
299
|
+
return await this.messaging.processScheduledFollowUp(code, options);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async processMessage(rawMessage, { onSaved = null } = {}) {
|
|
190
303
|
if (!this.isInitialized) {
|
|
191
304
|
throw new Error('Nexus not initialized. Call initialize() first.');
|
|
192
305
|
}
|
|
@@ -194,18 +307,38 @@ class Nexus {
|
|
|
194
307
|
const provider = this.messaging.getProvider();
|
|
195
308
|
const normalizedMessage = await provider.normalize(rawMessage);
|
|
196
309
|
const messageData = await this.messageParser.parseMessage(normalizedMessage);
|
|
197
|
-
return await this.messaging.processIncomingMessage(messageData);
|
|
310
|
+
return await this.messaging.processIncomingMessage(messageData, { onSaved });
|
|
198
311
|
}
|
|
199
312
|
|
|
200
313
|
isConnected() {
|
|
201
314
|
return this.messaging.isConnected();
|
|
202
315
|
}
|
|
203
316
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
317
|
+
beginDrain() {
|
|
318
|
+
this.messaging.getBatchingManager().draining = true;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
isDraining() {
|
|
322
|
+
return this.messaging.getBatchingManager().isDraining();
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async shutdown({ drainMs, abortGraceMs, teardownMs, sweepStopMs = 2000, closeStorage = true } = {}) {
|
|
326
|
+
if (this._shutdownPromise) return this._shutdownPromise;
|
|
327
|
+
const sweepsSettled = stopAllSweeps({ timeoutMs: sweepStopMs, label: '[Nexus]' });
|
|
328
|
+
this._shutdownPromise = (async () => {
|
|
329
|
+
const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
|
|
330
|
+
await sweepsSettled;
|
|
331
|
+
if (closeStorage && this.storage) {
|
|
332
|
+
await withTimeout(this.storage.disconnect(), teardownMs ?? 5000, 'storage.disconnect')
|
|
333
|
+
.catch(error => logger.warn('[Nexus] Storage disconnect did not finish', { error: error.message }));
|
|
334
|
+
}
|
|
335
|
+
return result;
|
|
336
|
+
})();
|
|
337
|
+
return this._shutdownPromise;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async disconnect(options = {}) {
|
|
341
|
+
return this.shutdown(options);
|
|
209
342
|
}
|
|
210
343
|
|
|
211
344
|
getMessaging() { return this.messaging; }
|
|
@@ -215,8 +348,8 @@ class Nexus {
|
|
|
215
348
|
}
|
|
216
349
|
|
|
217
350
|
module.exports = {
|
|
218
|
-
createWorkflowRunner,
|
|
219
351
|
Nexus,
|
|
352
|
+
DrainingError,
|
|
220
353
|
TwilioProvider,
|
|
221
354
|
BaileysProvider,
|
|
222
355
|
MongoStorage,
|
|
@@ -233,7 +366,18 @@ module.exports = {
|
|
|
233
366
|
setPreprocessingHandler,
|
|
234
367
|
hasPreprocessingHandler,
|
|
235
368
|
invokePreprocessingHandler,
|
|
369
|
+
registerInteractiveRoute,
|
|
370
|
+
clearInteractiveRoutes,
|
|
236
371
|
routes,
|
|
372
|
+
syncClinicalContext,
|
|
373
|
+
runProactiveOutreachSweep,
|
|
374
|
+
currentRegimen,
|
|
375
|
+
dryRunRegimenClosures,
|
|
376
|
+
closeStoppedRegimens,
|
|
377
|
+
readRecordedChemo,
|
|
378
|
+
syncContextFacts,
|
|
379
|
+
retractContentlessFacts,
|
|
380
|
+
syncLegacyContext,
|
|
237
381
|
setupDefaultRoutes: routes.setupDefaultRoutes,
|
|
238
382
|
createRouter: routes.createRouter,
|
|
239
383
|
requestIdMiddleware,
|
|
@@ -258,4 +402,18 @@ module.exports = {
|
|
|
258
402
|
DefaultMemoryManager,
|
|
259
403
|
EnhancedMemoryManager,
|
|
260
404
|
MapCache,
|
|
405
|
+
supportCandidateService,
|
|
406
|
+
registerDashboardProvider,
|
|
407
|
+
registerContactCategories,
|
|
408
|
+
supportActionService,
|
|
409
|
+
supportLightService,
|
|
410
|
+
supportInvitability,
|
|
411
|
+
supportLightEvaluationService,
|
|
412
|
+
NutritionSafetyDecision,
|
|
413
|
+
FINDING_CODES,
|
|
414
|
+
FINDING_VALUES,
|
|
415
|
+
FINDING_TO_QUESTION,
|
|
416
|
+
QUESTION_CODES,
|
|
417
|
+
EVIDENCE_SOURCE_TYPES,
|
|
418
|
+
DISPOSITIONS,
|
|
261
419
|
};
|
|
@@ -110,6 +110,7 @@ class ScheduledMessageJob extends BaseJob {
|
|
|
110
110
|
hidePreview: msg.hidePreview,
|
|
111
111
|
triggeredBy: msg.triggeredBy,
|
|
112
112
|
processed: true,
|
|
113
|
+
idempotencyKey: `scheduled:${scheduledMessageId}`,
|
|
113
114
|
...(parentMessageId ? { parentMessageId } : {
|
|
114
115
|
onParentMessageId: async (id) => {
|
|
115
116
|
if (!id) return;
|
|
@@ -118,6 +119,49 @@ class ScheduledMessageJob extends BaseJob {
|
|
|
118
119
|
}),
|
|
119
120
|
});
|
|
120
121
|
|
|
122
|
+
if (result?.duplicate) {
|
|
123
|
+
// The claim is a 30s lock on an equivalent send in flight, so this one is deferred, not dead.
|
|
124
|
+
await ScheduledMessage.updateOne(
|
|
125
|
+
{ _id: scheduledMessageId },
|
|
126
|
+
{
|
|
127
|
+
$set: {
|
|
128
|
+
status: 'pending',
|
|
129
|
+
errorCode: 'duplicate_suppressed',
|
|
130
|
+
errorMessage: 'An equivalent send was already in flight'
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
);
|
|
134
|
+
logger.warn('[ScheduledMessageJob] Send suppressed as a duplicate, left pending', { scheduledMessageId });
|
|
135
|
+
return { success: false, reason: 'duplicate_suppressed' };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (result?.status === 'patient_deceased') {
|
|
139
|
+
await ScheduledMessage.updateOne(
|
|
140
|
+
{ _id: scheduledMessageId },
|
|
141
|
+
{ $set: { status: 'cancelled', errorCode: result.status, errorMessage: 'The patient is deceased' } }
|
|
142
|
+
);
|
|
143
|
+
logger.info('[ScheduledMessageJob] Not sent to a deceased patient', { scheduledMessageId });
|
|
144
|
+
return { success: false, reason: result.status };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (result?.status === 'outbound_blocked') {
|
|
148
|
+
await ScheduledMessage.updateOne(
|
|
149
|
+
{ _id: scheduledMessageId },
|
|
150
|
+
{ $set: { status: 'cancelled', errorCode: result.status, errorMessage: 'The outbound allowlist refused the number' } }
|
|
151
|
+
);
|
|
152
|
+
logger.info('[ScheduledMessageJob] Not sent: the outbound allowlist refused the number', { scheduledMessageId });
|
|
153
|
+
return { success: false, reason: result.status };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (result?.status === 'contact_capped') {
|
|
157
|
+
await ScheduledMessage.updateOne(
|
|
158
|
+
{ _id: scheduledMessageId },
|
|
159
|
+
{ $set: { status: 'cancelled', errorCode: result.status, errorMessage: `Contact limit reached: ${result.reason}` } }
|
|
160
|
+
);
|
|
161
|
+
logger.info('[ScheduledMessageJob] Not sent, the patient reached her contact limit', { scheduledMessageId, reason: result.reason });
|
|
162
|
+
return { success: false, reason: result.status };
|
|
163
|
+
}
|
|
164
|
+
|
|
121
165
|
const messageId = result?.messageId || result?.sid || null;
|
|
122
166
|
|
|
123
167
|
await ScheduledMessage.updateOne(
|
|
@@ -1,14 +1,34 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
|
|
1
3
|
const { logger } = require('../utils/logger');
|
|
4
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
5
|
+
const { createEvent, safeEmit } = require('../utils/eventUtils');
|
|
2
6
|
const { Message } = require('../models/messageModel');
|
|
3
7
|
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
4
8
|
|
|
9
|
+
const { alertUndeliverable } = require('../helpers/channelRetryHelper');
|
|
10
|
+
|
|
11
|
+
const { contactOf } = require('../helpers/caregiverHelper');
|
|
5
12
|
const { getMessages } = require('../services/messageService');
|
|
13
|
+
const { recordUndeliverable } = require('../services/undeliverableService');
|
|
6
14
|
|
|
7
15
|
const { BaseJob } = require('./BaseJob');
|
|
8
16
|
|
|
17
|
+
const getMessaging = () => require('../core/NexusMessaging');
|
|
18
|
+
|
|
9
19
|
const QUEUE_NAME = 'template-approval';
|
|
10
20
|
const DEFAULT_DELAY_MS = 15 * 60 * 1000;
|
|
11
|
-
const MAX_ATTEMPTS =
|
|
21
|
+
const MAX_ATTEMPTS = 108;
|
|
22
|
+
const APPROVAL_CHECK_TIMEOUT_MS = 30 * 1000;
|
|
23
|
+
|
|
24
|
+
const WINDOW_REOPEN_SID_KEY = 'WINDOW_REOPEN_TEMPLATE_SID';
|
|
25
|
+
const WARN_AFTER_MS = 60 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
const APPROVAL_POLL_DELAYS_MS = [30 * 1000, 60 * 1000, 2 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000];
|
|
28
|
+
|
|
29
|
+
function delayForAttempt(attempt) {
|
|
30
|
+
return APPROVAL_POLL_DELAYS_MS[attempt] ?? DEFAULT_DELAY_MS;
|
|
31
|
+
}
|
|
12
32
|
|
|
13
33
|
const DEFAULT_JOB_OPTIONS = {
|
|
14
34
|
attempts: 3,
|
|
@@ -30,18 +50,21 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
30
50
|
this.requireProvider = requireProvider;
|
|
31
51
|
}
|
|
32
52
|
|
|
33
|
-
async schedule({ templateSid, messageId, originalMessageSid = null, attempt = 0, delayMs
|
|
53
|
+
async schedule({ templateSid, messageId, originalMessageSid = null, attempt = 0, delayMs }) {
|
|
34
54
|
if (!templateSid) throw new Error('templateSid is required');
|
|
35
55
|
if (!messageId) throw new Error('messageId is required');
|
|
36
56
|
|
|
57
|
+
const effectiveDelayMs = delayMs ?? delayForAttempt(attempt);
|
|
37
58
|
const jobId = this._buildJobId(templateSid, attempt);
|
|
38
59
|
|
|
39
60
|
const enqueuedJobId = await this._enqueue(
|
|
40
61
|
{ templateSid, messageId: String(messageId), originalMessageSid, attempt },
|
|
41
|
-
{ ...DEFAULT_JOB_OPTIONS, delay:
|
|
62
|
+
{ ...DEFAULT_JOB_OPTIONS, delay: effectiveDelayMs, jobId }
|
|
42
63
|
);
|
|
43
64
|
|
|
44
|
-
logger.info('[TemplateApprovalJob] Enqueued', {
|
|
65
|
+
logger.info('[TemplateApprovalJob] Enqueued', {
|
|
66
|
+
templateSid, messageId, attempt, jobId: enqueuedJobId, delayMs: effectiveDelayMs
|
|
67
|
+
});
|
|
45
68
|
|
|
46
69
|
return { jobId: enqueuedJobId };
|
|
47
70
|
}
|
|
@@ -59,44 +82,64 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
59
82
|
}
|
|
60
83
|
|
|
61
84
|
const recovery = message.statusInfo || {};
|
|
62
|
-
if (recovery.recoverySentAt || recovery.recoveryRejectedAt) {
|
|
85
|
+
if (recovery.recoverySentAt || recovery.recoveryRejectedAt || recovery.recoveryReleasedAt) {
|
|
63
86
|
logger.info('[TemplateApprovalJob] Recovery already completed', { messageId, templateSid });
|
|
64
87
|
return { success: false, reason: 'already_completed' };
|
|
65
88
|
}
|
|
66
|
-
if (recovery.
|
|
89
|
+
if (recovery.recoveryFailedAt) {
|
|
90
|
+
logger.info('[TemplateApprovalJob] Recovery already abandoned', { messageId, templateSid });
|
|
91
|
+
return { success: false, reason: 'already_failed' };
|
|
92
|
+
}
|
|
93
|
+
if (recovery.recoveryTemplateSid !== templateSid) {
|
|
67
94
|
logger.info('[TemplateApprovalJob] Template superseded', { messageId, templateSid, currentTemplateSid: recovery.recoveryTemplateSid });
|
|
68
95
|
return { success: false, reason: 'template_superseded' };
|
|
69
96
|
}
|
|
70
97
|
|
|
98
|
+
await Message.updateOne(
|
|
99
|
+
{ _id: message._id },
|
|
100
|
+
{ $set: { 'statusInfo.recoveryCheckedAt': new Date(), 'statusInfo.recoveryAttempt': attempt + 1 } }
|
|
101
|
+
);
|
|
102
|
+
|
|
71
103
|
let provider;
|
|
72
104
|
let approvalStatus;
|
|
73
105
|
try {
|
|
74
106
|
provider = this.requireProvider();
|
|
75
|
-
const status = await
|
|
107
|
+
const status = await withTimeout(
|
|
108
|
+
provider.checkApprovalStatus(templateSid),
|
|
109
|
+
APPROVAL_CHECK_TIMEOUT_MS,
|
|
110
|
+
'checkApprovalStatus'
|
|
111
|
+
);
|
|
76
112
|
approvalStatus = status?.approvalRequest?.status?.toUpperCase();
|
|
77
113
|
} catch (err) {
|
|
78
114
|
logger.error('[TemplateApprovalJob] Provider error during approval check, treating as transient', {
|
|
79
115
|
templateSid, messageId, attempt, error: err.message
|
|
80
116
|
});
|
|
81
|
-
return await this._rescheduleOrGiveUp({ templateSid,
|
|
117
|
+
return await this._rescheduleOrGiveUp({ templateSid, message, originalMessageSid, attempt, reason: 'error' });
|
|
82
118
|
}
|
|
83
119
|
|
|
84
120
|
logger.info('[TemplateApprovalJob] Approval status', { templateSid, approvalStatus, attempt, messageId, originalMessageSid });
|
|
85
121
|
|
|
86
122
|
if (approvalStatus === 'APPROVED') {
|
|
87
|
-
return await this._handleApproved({
|
|
123
|
+
return await this._handleApproved({ message, templateSid, originalMessageSid });
|
|
88
124
|
}
|
|
89
125
|
if (approvalStatus === 'REJECTED') {
|
|
90
126
|
return await this._handleRejected({ provider, message, templateSid });
|
|
91
127
|
}
|
|
92
128
|
|
|
93
|
-
return await this._rescheduleOrGiveUp({ templateSid,
|
|
129
|
+
return await this._rescheduleOrGiveUp({ templateSid, message, originalMessageSid, attempt, reason: 'pending' });
|
|
94
130
|
}
|
|
95
131
|
|
|
96
|
-
async _rescheduleOrGiveUp({ templateSid,
|
|
132
|
+
async _rescheduleOrGiveUp({ templateSid, message, originalMessageSid, attempt, reason }) {
|
|
133
|
+
const messageId = message._id;
|
|
97
134
|
const nextAttempt = attempt + 1;
|
|
98
135
|
if (nextAttempt >= MAX_ATTEMPTS) {
|
|
99
|
-
logger.
|
|
136
|
+
logger.error('[TemplateApprovalJob] Max attempts reached, giving up', { templateSid, messageId, attempt, reason });
|
|
137
|
+
await this._failTerminally({
|
|
138
|
+
message,
|
|
139
|
+
templateSid,
|
|
140
|
+
stamp: 'statusInfo.recoveryFailedAt',
|
|
141
|
+
errorMessage: `Template approval abandoned after ${MAX_ATTEMPTS} checks (${reason})`
|
|
142
|
+
});
|
|
100
143
|
try {
|
|
101
144
|
const provider = this.requireProvider();
|
|
102
145
|
await provider.deleteTemplate(templateSid);
|
|
@@ -105,13 +148,138 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
105
148
|
}
|
|
106
149
|
return { success: false, reason: 'max_attempts', priorReason: reason };
|
|
107
150
|
}
|
|
151
|
+
await this._warnIfSlow(message, templateSid);
|
|
108
152
|
await this.schedule({ templateSid, messageId, originalMessageSid, attempt: nextAttempt });
|
|
109
153
|
return { success: false, reason, nextAttempt };
|
|
110
154
|
}
|
|
111
155
|
|
|
112
|
-
async
|
|
156
|
+
async _warnIfSlow(message, templateSid) {
|
|
157
|
+
const startedAt = message.statusInfo?.recoveryStartedAt;
|
|
158
|
+
if (!startedAt) return { warned: false, reason: 'no_start' };
|
|
159
|
+
const waitingMs = Date.now() - new Date(startedAt).getTime();
|
|
160
|
+
if (waitingMs < WARN_AFTER_MS) return { warned: false, reason: 'within_threshold' };
|
|
161
|
+
|
|
113
162
|
const claim = await Message.updateOne(
|
|
114
|
-
{ _id: message._id, 'statusInfo.
|
|
163
|
+
{ _id: message._id, 'statusInfo.recoveryWarnedAt': null },
|
|
164
|
+
{ $set: { 'statusInfo.recoveryWarnedAt': new Date() } }
|
|
165
|
+
);
|
|
166
|
+
if (!claim.modifiedCount && !claim.nModified) return { warned: false, reason: 'already_warned' };
|
|
167
|
+
|
|
168
|
+
const waitingMinutes = Math.round(waitingMs / 60000);
|
|
169
|
+
logger.warn('[TemplateApprovalJob] Approval still pending, message not delivered yet', {
|
|
170
|
+
messageId: String(message._id), templateSid, to: message.numero,
|
|
171
|
+
triggeredBy: message.triggeredBy || null, waitingMinutes
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
safeEmit(getMessaging().getEventBus(), 'message:delivery_delayed', createEvent('message:delivery_delayed', {
|
|
175
|
+
messageId: String(message._id),
|
|
176
|
+
to: message.numero,
|
|
177
|
+
templateSid,
|
|
178
|
+
triggeredBy: message.triggeredBy || null,
|
|
179
|
+
waitingMinutes
|
|
180
|
+
}));
|
|
181
|
+
|
|
182
|
+
const record = await recordUndeliverable(message, { status: 'queued' });
|
|
183
|
+
if (!record) {
|
|
184
|
+
await Message.updateOne(
|
|
185
|
+
{ _id: message._id },
|
|
186
|
+
{ $unset: { 'statusInfo.recoveryWarnedAt': '' } }
|
|
187
|
+
);
|
|
188
|
+
return { warned: false, reason: 'record_failed' };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { warned: true, waitingMinutes };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async _failTerminally({ message, templateSid, stamp, errorMessage }) {
|
|
195
|
+
await Message.updateOne(
|
|
196
|
+
{ _id: message._id },
|
|
197
|
+
{
|
|
198
|
+
$set: {
|
|
199
|
+
[stamp]: new Date(),
|
|
200
|
+
'statusInfo.status': 'failed',
|
|
201
|
+
'statusInfo.updatedAt': new Date(),
|
|
202
|
+
'statusInfo.errorMessage': errorMessage
|
|
203
|
+
},
|
|
204
|
+
$unset: { 'statusInfo.recoveryTemplateSid': '', 'statusInfo.recoveryStartedAt': '' }
|
|
205
|
+
}
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
const payload = {
|
|
209
|
+
source: 'template_approval',
|
|
210
|
+
messageId: String(message._id),
|
|
211
|
+
to: message.numero,
|
|
212
|
+
templateSid,
|
|
213
|
+
triggeredBy: message.triggeredBy || null,
|
|
214
|
+
errorMessage
|
|
215
|
+
};
|
|
216
|
+
alertUndeliverable(payload);
|
|
217
|
+
safeEmit(getMessaging().getEventBus(), 'message:status', createEvent('message:status', {
|
|
218
|
+
messageId: String(message._id),
|
|
219
|
+
to: message.numero,
|
|
220
|
+
status: 'failed',
|
|
221
|
+
errorCode: null,
|
|
222
|
+
errorMessage,
|
|
223
|
+
twilioSid: null
|
|
224
|
+
}));
|
|
225
|
+
recordUndeliverable(message, { status: 'failed' });
|
|
226
|
+
|
|
227
|
+
await DeliveryAttempt.updateOne(
|
|
228
|
+
{ messageId: message._id, kind: 'recovery_template_setup', twilioSid: templateSid },
|
|
229
|
+
{ $set: {
|
|
230
|
+
status: 'failed',
|
|
231
|
+
errorSource: 'server',
|
|
232
|
+
errorMessage,
|
|
233
|
+
completedAt: new Date()
|
|
234
|
+
} }
|
|
235
|
+
).catch(err => logger.warn('[TemplateApprovalJob] Could not fail the setup attempt', {
|
|
236
|
+
messageId: String(message._id), error: err.message
|
|
237
|
+
}));
|
|
238
|
+
|
|
239
|
+
await this._sendWindowReopenNudge(message);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async _sendWindowReopenNudge(message) {
|
|
243
|
+
const contentSid = runtimeConfig.get(WINDOW_REOPEN_SID_KEY);
|
|
244
|
+
if (!contentSid) {
|
|
245
|
+
logger.info('[TemplateApprovalJob] No window-reopen template configured, skipping nudge', {
|
|
246
|
+
messageId: String(message._id)
|
|
247
|
+
});
|
|
248
|
+
return { sent: false, reason: 'not_configured' };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
let result;
|
|
252
|
+
try {
|
|
253
|
+
result = await this.sendMessage({
|
|
254
|
+
code: message.numero,
|
|
255
|
+
...contactOf(message),
|
|
256
|
+
contentSid,
|
|
257
|
+
variables: {},
|
|
258
|
+
kind: 'window_reopen_nudge',
|
|
259
|
+
idempotencyKey: `window-reopen:${message._id}`
|
|
260
|
+
});
|
|
261
|
+
} catch (err) {
|
|
262
|
+
logger.error('[TemplateApprovalJob] Window-reopen nudge failed', {
|
|
263
|
+
messageId: String(message._id), contentSid, error: err.message
|
|
264
|
+
});
|
|
265
|
+
return { sent: false, reason: 'send_failed' };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (result?.duplicate) {
|
|
269
|
+
logger.info('[TemplateApprovalJob] Window-reopen nudge suppressed as duplicate', { messageId: String(message._id) });
|
|
270
|
+
return { sent: false, reason: 'duplicate_suppressed' };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
logger.info('[TemplateApprovalJob] Window-reopen nudge sent', {
|
|
274
|
+
messageId: String(message._id), contentSid, nudgeMessageId: result?.messageId || null
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
return { sent: Boolean(result?.messageId), nudgeMessageId: result?.messageId || null };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async _handleApproved({ message, templateSid, originalMessageSid }) {
|
|
281
|
+
const claim = await Message.updateOne(
|
|
282
|
+
{ _id: message._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
|
|
115
283
|
{ $set: { 'statusInfo.recoverySentAt': new Date() } }
|
|
116
284
|
);
|
|
117
285
|
if (!claim.modifiedCount && !claim.nModified) {
|
|
@@ -123,12 +291,23 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
123
291
|
try {
|
|
124
292
|
sendResult = await this.sendMessage({
|
|
125
293
|
code: message.numero,
|
|
294
|
+
...contactOf(message),
|
|
126
295
|
contentSid: templateSid,
|
|
127
296
|
variables: {},
|
|
128
297
|
parentMessageId: message._id,
|
|
129
298
|
kind: 'recovery_template',
|
|
130
|
-
body: message.body
|
|
299
|
+
body: message.body,
|
|
300
|
+
idempotencyKey: `recovery:${message._id}`
|
|
131
301
|
});
|
|
302
|
+
if (sendResult?.duplicate) {
|
|
303
|
+
logger.info('[TemplateApprovalJob] Recovery send already claimed elsewhere', { templateSid, messageId: message._id });
|
|
304
|
+
return { success: false, reason: 'duplicate_suppressed' };
|
|
305
|
+
}
|
|
306
|
+
if (sendResult?.status === 'outbound_blocked') {
|
|
307
|
+
// Keep the claim so the job does not retry a blocked number.
|
|
308
|
+
logger.warn('[TemplateApprovalJob] Recovery send refused by the outbound allowlist', { templateSid, messageId: message._id });
|
|
309
|
+
return { success: false, reason: 'outbound_blocked' };
|
|
310
|
+
}
|
|
132
311
|
if (!sendResult?.messageId) {
|
|
133
312
|
throw new Error('Provider did not return a messageId for the recovery send');
|
|
134
313
|
}
|
|
@@ -148,28 +327,16 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
148
327
|
{ $set: { status: 'sent', completedAt: new Date() } }
|
|
149
328
|
);
|
|
150
329
|
|
|
151
|
-
provider.deleteTemplate(templateSid).catch((deleteErr) =>
|
|
152
|
-
logger.warn('[TemplateApprovalJob] Failed to delete template after send', { templateSid, error: deleteErr.message })
|
|
153
|
-
);
|
|
154
|
-
|
|
155
330
|
return { success: true, recoveryMessageId: sendResult.messageId };
|
|
156
331
|
}
|
|
157
332
|
|
|
158
333
|
async _handleRejected({ provider, message, templateSid }) {
|
|
159
|
-
await
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
{ messageId: message._id, kind: 'recovery_template_setup', twilioSid: templateSid },
|
|
166
|
-
{ $set: {
|
|
167
|
-
status: 'failed',
|
|
168
|
-
errorSource: 'server',
|
|
169
|
-
errorMessage: 'Rejected by WhatsApp',
|
|
170
|
-
completedAt: new Date()
|
|
171
|
-
} }
|
|
172
|
-
);
|
|
334
|
+
await this._failTerminally({
|
|
335
|
+
message,
|
|
336
|
+
templateSid,
|
|
337
|
+
stamp: 'statusInfo.recoveryRejectedAt',
|
|
338
|
+
errorMessage: 'Rejected by WhatsApp'
|
|
339
|
+
});
|
|
173
340
|
|
|
174
341
|
try {
|
|
175
342
|
await provider.deleteTemplate(templateSid);
|
|
@@ -12,6 +12,11 @@ const scheduledMessageSchema = new mongoose.Schema({
|
|
|
12
12
|
variables: Object,
|
|
13
13
|
timeZone: { type: String, default: 'Etc/GMT' },
|
|
14
14
|
status: { type: String, default: 'pending' },
|
|
15
|
+
sendingAt: { type: Date, default: null },
|
|
16
|
+
sentAt: { type: Date, default: null },
|
|
17
|
+
failedAt: { type: Date, default: null },
|
|
18
|
+
errorCode: { type: String, default: null },
|
|
19
|
+
errorMessage: { type: String, default: null },
|
|
15
20
|
wa_id: { type: String, default: null },
|
|
16
21
|
triggeredBy: { type: String, default: null },
|
|
17
22
|
parentMessageId: { type: mongoose.Schema.Types.ObjectId, ref: 'Message', default: null },
|