@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
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const { httpError } = require('../utils/httpErrorUtils');
|
|
2
|
+
const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
|
+
|
|
4
|
+
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
5
|
+
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
6
|
+
|
|
7
|
+
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
|
+
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
9
|
+
const BOARD_BUCKETS = ['pending', 'followup', 'done'];
|
|
10
|
+
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
11
|
+
|
|
12
|
+
const bucketQuery = (bucket, now) => {
|
|
13
|
+
switch (bucket) {
|
|
14
|
+
case 'pending':
|
|
15
|
+
return { closedAt: null, status: { $nin: [...FOLLOWUP_STATUSES, ...DONE_STATUSES] } };
|
|
16
|
+
case 'followup':
|
|
17
|
+
return { closedAt: null, status: { $in: FOLLOWUP_STATUSES } };
|
|
18
|
+
case 'done':
|
|
19
|
+
return { status: { $in: DONE_STATUSES }, closedAt: { $gte: new Date(now.getTime() - DONE_WINDOW_MS) } };
|
|
20
|
+
default:
|
|
21
|
+
throw httpError(400, `bucket must be one of: ${BOARD_BUCKETS.join(', ')}`);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
26
|
+
const alarms = review.alarms || [];
|
|
27
|
+
const lead = effectiveUrgencyOf(review);
|
|
28
|
+
const raised = alarms.map((alarm) => alarm.raisedAt).filter(Boolean);
|
|
29
|
+
const since = raised.length ? new Date(Math.min(...raised.map(Number))) : review.createdAt;
|
|
30
|
+
return {
|
|
31
|
+
reviewId: String(review._id),
|
|
32
|
+
patientCode: review.patientCode,
|
|
33
|
+
bucket,
|
|
34
|
+
status: review.status,
|
|
35
|
+
caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null,
|
|
36
|
+
urgency: lead?.urgency || null,
|
|
37
|
+
symptom: lead?.symptom || null,
|
|
38
|
+
alarmCount: alarms.length,
|
|
39
|
+
since,
|
|
40
|
+
closedAt: review.closedAt || null,
|
|
41
|
+
updatedSinceSeen: review.updatedSinceSeen === true,
|
|
42
|
+
responseDeadline: responseDeadlineOf(review, deadlinePolicy),
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const byUrgencyThenAge = (a, b) => (URGENCY_RANK[b.urgency] || 0) - (URGENCY_RANK[a.urgency] || 0)
|
|
47
|
+
|| new Date(a.since) - new Date(b.since);
|
|
48
|
+
|
|
49
|
+
const byMostRecentlyClosed = (a, b) => new Date(b.closedAt) - new Date(a.closedAt);
|
|
50
|
+
|
|
51
|
+
async function listReviewBoard({ bucket, now = new Date() } = {}) {
|
|
52
|
+
const reviews = await getEscalationReview()
|
|
53
|
+
.find(bucketQuery(bucket, now), {
|
|
54
|
+
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
55
|
+
'decisions.createdAt': 1, urgencyReclassifications: 1,
|
|
56
|
+
})
|
|
57
|
+
.lean();
|
|
58
|
+
const deadlinePolicy = responseDeadlinePolicy();
|
|
59
|
+
const rows = reviews.map((review) => boardRowOf(review, bucket, deadlinePolicy))
|
|
60
|
+
.sort(bucket === 'done' ? byMostRecentlyClosed : byUrgencyThenAge);
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
return rows.filter((row) => !seen.has(row.patientCode) && seen.add(row.patientCode));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const boardBucketOfFilter = (filter) => {
|
|
66
|
+
if (typeof filter !== 'string' || !filter.startsWith(BOARD_FILTER_PREFIX)) return null;
|
|
67
|
+
const bucket = filter.slice(BOARD_FILTER_PREFIX.length);
|
|
68
|
+
return BOARD_BUCKETS.includes(bucket) ? bucket : null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
module.exports = {
|
|
72
|
+
BOARD_BUCKETS,
|
|
73
|
+
boardBucketOfFilter,
|
|
74
|
+
listReviewBoard,
|
|
75
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { addWorkingMinutes } = require('../utils/dateUtils');
|
|
3
|
+
const { FOLLOWUP_STATUSES, URGENCY_RANK } = require('../models/escalationReviewModel');
|
|
4
|
+
|
|
5
|
+
const RESPONSE_MINUTES = { stat: 15, asap: 60, urgent: 240, routine: 720 };
|
|
6
|
+
const MAX_RESPONSE_MINUTES = 7 * 24 * 60;
|
|
7
|
+
const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
|
|
8
|
+
const TEAM_TIMEZONE = 'America/Mexico_City';
|
|
9
|
+
const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
|
|
10
|
+
const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
|
|
11
|
+
const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20 };
|
|
12
|
+
const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES' };
|
|
13
|
+
const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
|
|
14
|
+
const DEFAULT_PENDING_WAIT_MINUTES = { asap: 5, urgent: 60 };
|
|
15
|
+
const PENDING_WAIT_KEYS = { asap: 'ESCALATION_PENDING_WAIT_MINUTES_ASAP', urgent: 'ESCALATION_PENDING_WAIT_MINUTES_URGENT' };
|
|
16
|
+
const DEFAULT_QUIET_REMINDER_MINUTES = 30;
|
|
17
|
+
|
|
18
|
+
const rankOf = (level) => URGENCY_RANK[level] || 0;
|
|
19
|
+
const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
|
|
20
|
+
|
|
21
|
+
const configuredMinutes = (level) => {
|
|
22
|
+
const minutes = Number(runtimeConfig.get(`ESCALATION_REVIEW_RESPONSE_MINUTES_${level.toUpperCase()}`, RESPONSE_MINUTES[level]));
|
|
23
|
+
return Number.isFinite(minutes) && minutes > 0 && minutes <= MAX_RESPONSE_MINUTES ? minutes : RESPONSE_MINUTES[level];
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function configuredTeamHours() {
|
|
27
|
+
const entries = String(runtimeConfig.get('ESCALATION_REVIEW_TEAM_DAYS', '')).split(',').map((day) => day.trim()).filter(Boolean);
|
|
28
|
+
const days = entries.map(Number);
|
|
29
|
+
const isValidDays = days.length > 0 && days.every((day) => Number.isInteger(day) && day >= 1 && day <= 7);
|
|
30
|
+
const startHour = Number(runtimeConfig.get('ESCALATION_REVIEW_TEAM_START_HOUR', DEFAULT_TEAM_HOURS.startHour));
|
|
31
|
+
const endHour = Number(runtimeConfig.get('ESCALATION_REVIEW_TEAM_END_HOUR', DEFAULT_TEAM_HOURS.endHour));
|
|
32
|
+
const isValidSpan = Number.isInteger(startHour) && Number.isInteger(endHour) && startHour >= 0 && startHour < endHour && endHour <= 24;
|
|
33
|
+
return {
|
|
34
|
+
timeZone: TEAM_TIMEZONE,
|
|
35
|
+
days: isValidDays ? [...new Set(days)] : DEFAULT_TEAM_HOURS.days,
|
|
36
|
+
startHour: isValidSpan ? startHour : DEFAULT_TEAM_HOURS.startHour,
|
|
37
|
+
endHour: isValidSpan ? endHour : DEFAULT_TEAM_HOURS.endHour,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function responseDeadlinePolicy() {
|
|
42
|
+
return {
|
|
43
|
+
responseMinutes: Object.fromEntries(Object.keys(RESPONSE_MINUTES).map((level) => [level, configuredMinutes(level)])),
|
|
44
|
+
teamHours: configuredTeamHours(),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function alarmLevelsOf(review) {
|
|
49
|
+
const reclassifications = [...(review.urgencyReclassifications ?? [])].sort((a, b) => timeOf(a.at) - timeOf(b.at));
|
|
50
|
+
return (review.alarms ?? []).map((alarm) => reclassifications
|
|
51
|
+
.filter((change) => timeOf(alarm.raisedAt) <= timeOf(change.at))
|
|
52
|
+
.reduce((entry, change) => ({
|
|
53
|
+
alarm,
|
|
54
|
+
level: change.toLevel,
|
|
55
|
+
clockFrom: rankOf(change.toLevel) > rankOf(entry.level) ? change.at : entry.clockFrom,
|
|
56
|
+
}), { alarm, level: alarm.urgencyLevel, clockFrom: alarm.raisedAt }));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function effectiveUrgencyOf(review) {
|
|
60
|
+
const lead = alarmLevelsOf(review).reduce((top, entry) => (
|
|
61
|
+
!top || rankOf(entry.level) > rankOf(top.level)
|
|
62
|
+
|| (rankOf(entry.level) === rankOf(top.level) && timeOf(entry.alarm.raisedAt) > timeOf(top.alarm.raisedAt)) ? entry : top
|
|
63
|
+
), null);
|
|
64
|
+
return lead ? { urgency: lead.level, symptom: lead.alarm.symptom ?? null } : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level]) {
|
|
68
|
+
if (BUSINESS_HOURS_LEVELS.includes(level)) return addWorkingMinutes(new Date(from), minutes, policy.teamHours);
|
|
69
|
+
return new Date(timeOf(from) + minutes * 60 * 1000);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const positiveMinutes = (key, fallback) => {
|
|
73
|
+
const minutes = Number(runtimeConfig.get(key, fallback));
|
|
74
|
+
return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// asap leaves the team its early alert before the patient gets the numbers to call.
|
|
78
|
+
const patientTimerMinutes = (level) => positiveMinutes(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
|
|
79
|
+
const untakenEarlyMinutes = () => positiveMinutes('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
|
|
80
|
+
// How long a question the patient left unanswered waits before the case goes to the doctor without the answer.
|
|
81
|
+
const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveMinutes(PENDING_WAIT_KEYS[level], DEFAULT_PENDING_WAIT_MINUTES[level]) : null);
|
|
82
|
+
const teamOpenAt = (now, policy) => addWorkingMinutes(now, 0, policy.teamHours);
|
|
83
|
+
const quietReminderMinutes = () => positiveMinutes('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
|
|
84
|
+
|
|
85
|
+
// Untaken alerts: asap early, asap and urgent at half the response time, and every level at the deadline.
|
|
86
|
+
function untakenStagesOf(level, since, policy) {
|
|
87
|
+
const total = policy.responseMinutes[level];
|
|
88
|
+
const minutesOf = { early: untakenEarlyMinutes(), half: total / 2, deadline: total };
|
|
89
|
+
return (UNTAKEN_STAGES[level] ?? [])
|
|
90
|
+
.filter((stage) => stage !== 'early' || minutesOf.early < minutesOf.half)
|
|
91
|
+
.map((stage) => ({ stage, minutes: minutesOf[stage], totalMinutes: total, dueAt: dueAtFor(since, level, policy, minutesOf[stage]) }));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function responseDeadlineOf(review, policy) {
|
|
95
|
+
if (review.closedAt || FOLLOWUP_STATUSES.includes(review.status)) return null;
|
|
96
|
+
const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
|
|
97
|
+
const waiting = alarmLevelsOf(review)
|
|
98
|
+
.filter(({ alarm }) => Number.isNaN(decidedAt) || timeOf(alarm.raisedAt) > decidedAt)
|
|
99
|
+
.map(({ level, clockFrom }) => ({ urgency: level, dueAt: dueAtFor(clockFrom, level, policy) }))
|
|
100
|
+
.filter(({ dueAt }) => dueAt);
|
|
101
|
+
if (!waiting.length) return null;
|
|
102
|
+
const earliest = waiting.reduce((first, entry) => (entry.dueAt < first.dueAt ? entry : first));
|
|
103
|
+
return { ...earliest, isBusinessHoursOnly: BUSINESS_HOURS_LEVELS.includes(earliest.urgency) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = {
|
|
107
|
+
BUSINESS_HOURS_LEVELS,
|
|
108
|
+
effectiveUrgencyOf,
|
|
109
|
+
responseDeadlineOf,
|
|
110
|
+
patientTimerMinutes,
|
|
111
|
+
pendingWaitMinutes,
|
|
112
|
+
quietReminderMinutes,
|
|
113
|
+
responseDeadlinePolicy,
|
|
114
|
+
teamOpenAt,
|
|
115
|
+
untakenStagesOf,
|
|
116
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
3
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
4
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
|
+
|
|
6
|
+
const { BOOKKEEPING, DOCUMENTING_STATUSES, generateBotDraft } = require('./escalationReviewService');
|
|
7
|
+
|
|
8
|
+
const SWEEP_LIMIT = 1;
|
|
9
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 10 * 1000;
|
|
10
|
+
const RETRY_DELAY_MS = 5 * 60 * 1000;
|
|
11
|
+
// A refused answer is a fresh sample away from a good one; only an unreachable model needs the long wait.
|
|
12
|
+
const REJECTED_RETRY_DELAY_MS = 20 * 1000;
|
|
13
|
+
const MAX_DRAFT_ATTEMPTS = 3;
|
|
14
|
+
const LEASE_MS = 10 * 60 * 1000;
|
|
15
|
+
const GENERATION_TIMEOUT_MS = 4 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts = 0 }, now) {
|
|
18
|
+
const lease = new Date(now.getTime() + LEASE_MS);
|
|
19
|
+
const claimed = await EscalationReview
|
|
20
|
+
.findOneAndUpdate({ _id, draftDueAt }, { $set: { draftDueAt: lease } }, { ...BOOKKEEPING, new: true, projection: { _id: 1 } })
|
|
21
|
+
.lean();
|
|
22
|
+
if (!claimed) return false;
|
|
23
|
+
|
|
24
|
+
let outcome;
|
|
25
|
+
try {
|
|
26
|
+
outcome = await withTimeout(generateBotDraft({ id: String(_id), lease }), GENERATION_TIMEOUT_MS, 'automatic draft generation');
|
|
27
|
+
} catch (error) {
|
|
28
|
+
logger.error('[ReviewDraftSweep] The automatic draft threw', { escalationReviewId: String(_id), error: error.message });
|
|
29
|
+
outcome = { review: null, retry: true };
|
|
30
|
+
}
|
|
31
|
+
const { review, retry, rejected = false } = outcome;
|
|
32
|
+
if (review) return true;
|
|
33
|
+
const willRetry = retry && draftAttempts + 1 < MAX_DRAFT_ATTEMPTS;
|
|
34
|
+
if (retry && !willRetry) {
|
|
35
|
+
logger.error('[ReviewDraftSweep] The automatic draft failed on every attempt; it waits for new material', {
|
|
36
|
+
escalationReviewId: String(_id), attempts: draftAttempts + 1,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (retry && !willRetry) {
|
|
40
|
+
const marked = await EscalationReview.updateOne(
|
|
41
|
+
{ _id, draftDueAt: lease, closedAt: null, status: { $in: DOCUMENTING_STATUSES } },
|
|
42
|
+
{ $set: { draftDueAt: null, draftFailedAt: new Date() } },
|
|
43
|
+
BOOKKEEPING,
|
|
44
|
+
);
|
|
45
|
+
if (marked.matchedCount) return false;
|
|
46
|
+
}
|
|
47
|
+
await EscalationReview.updateOne(
|
|
48
|
+
{ _id, draftDueAt: lease },
|
|
49
|
+
willRetry
|
|
50
|
+
? { $set: { draftDueAt: new Date(Date.now() + (rejected ? REJECTED_RETRY_DELAY_MS : RETRY_DELAY_MS)) }, $inc: { draftAttempts: 1 } }
|
|
51
|
+
: { $set: { draftDueAt: null } },
|
|
52
|
+
BOOKKEEPING,
|
|
53
|
+
);
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function sweepReviewDrafts({ now = new Date() } = {}) {
|
|
58
|
+
const EscalationReview = getEscalationReview();
|
|
59
|
+
const due = await EscalationReview
|
|
60
|
+
.find({ closedAt: null, draftDueAt: { $lte: now } }, { _id: 1, draftDueAt: 1, draftAttempts: 1 })
|
|
61
|
+
.sort({ draftDueAt: 1 })
|
|
62
|
+
.limit(SWEEP_LIMIT)
|
|
63
|
+
.lean();
|
|
64
|
+
|
|
65
|
+
let written = 0;
|
|
66
|
+
for (const entry of due) {
|
|
67
|
+
try {
|
|
68
|
+
if (await draftReview(EscalationReview, entry, now)) written += 1;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
logger.error('[ReviewDraftSweep] Could not draft a review', { escalationReviewId: String(entry._id), error: error.message });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return written;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const sweeper = createIntervalSweeper({
|
|
77
|
+
label: '[ReviewDraftSweep]',
|
|
78
|
+
sweep: () => sweepReviewDrafts(),
|
|
79
|
+
defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const startReviewDraftSweep = (options) => sweeper.start(options);
|
|
83
|
+
const stopReviewDraftSweep = () => sweeper.stop();
|
|
84
|
+
|
|
85
|
+
module.exports = { startReviewDraftSweep, stopReviewDraftSweep, sweepReviewDrafts };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
const axios = require('axios');
|
|
2
|
+
|
|
3
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
5
|
+
const { logger } = require('../utils/logger');
|
|
6
|
+
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
7
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
8
|
+
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
9
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
10
|
+
|
|
11
|
+
const airtableService = require('./airtableService');
|
|
12
|
+
|
|
13
|
+
const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
|
|
14
|
+
const REQUEST_TIMEOUT_MS = 15000;
|
|
15
|
+
const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
|
|
16
|
+
const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
|
|
17
|
+
const ROSTER_TABLE = 'equipo_guardia';
|
|
18
|
+
const ROSTER_FIELDS = ['whatsapp', 'sin_tomar'];
|
|
19
|
+
const ROSTER_TTL_MS = 5 * 60 * 1000;
|
|
20
|
+
const ROSTER_READ_TIMEOUT_MS = 5000;
|
|
21
|
+
|
|
22
|
+
const getMessaging = () => require('../core/NexusMessaging');
|
|
23
|
+
|
|
24
|
+
const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').replace(/[^\d+]/g, ''));
|
|
25
|
+
|
|
26
|
+
const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
|
|
27
|
+
|
|
28
|
+
let roster = { members: null, readAt: 0 };
|
|
29
|
+
let reading = null;
|
|
30
|
+
|
|
31
|
+
// Used when the roster is unreadable or has no active phone; it ignores levels.
|
|
32
|
+
function configuredPhones() {
|
|
33
|
+
return String(runtimeConfig.get('ESCALATION_TEAM_ALERT_PHONES', '') ?? '')
|
|
34
|
+
.split(',')
|
|
35
|
+
.map((phone) => phone.trim())
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
.map(whatsAppCodeOf)
|
|
38
|
+
.filter((code) => PATIENT_CODE.test(code));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function readRoster() {
|
|
42
|
+
const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, '{activo}', null, ROSTER_FIELDS);
|
|
43
|
+
if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
|
|
44
|
+
return rows
|
|
45
|
+
.map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [] }))
|
|
46
|
+
.filter((member) => PATIENT_CODE.test(member.code));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function refreshRoster(now) {
|
|
50
|
+
try {
|
|
51
|
+
const members = await withTimeout(readRoster(), ROSTER_READ_TIMEOUT_MS, 'on-call roster read');
|
|
52
|
+
roster = { members: members.length ? members : null, readAt: now };
|
|
53
|
+
if (!members.length) logger.warn('[TeamAlert] The on-call roster has no active phone; using ESCALATION_TEAM_ALERT_PHONES');
|
|
54
|
+
} catch (error) {
|
|
55
|
+
roster = { ...roster, readAt: now };
|
|
56
|
+
logger.error('[TeamAlert] The on-call roster could not be read; using the last one read', { error: redacted(error) });
|
|
57
|
+
}
|
|
58
|
+
return roster.members;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The Airtable roster, read at most every 5 min by one read at a time; a failed read keeps the last one and waits as long to retry.
|
|
62
|
+
async function rosterMembers(now = Date.now()) {
|
|
63
|
+
if (roster.readAt && now - roster.readAt < ROSTER_TTL_MS) return roster.members;
|
|
64
|
+
if (!reading) reading = refreshRoster(now).finally(() => { reading = null; });
|
|
65
|
+
return reading;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// With a level, only the members who take that level's untaken alerts; without one, every active member.
|
|
69
|
+
async function teamPhones(level = null) {
|
|
70
|
+
const members = await rosterMembers();
|
|
71
|
+
if (!members) return configuredPhones();
|
|
72
|
+
return members.filter((member) => !level || member.levels.includes(level)).map((member) => member.code);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const _resetRoster = () => {
|
|
76
|
+
roster = { members: null, readAt: 0 };
|
|
77
|
+
reading = null;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
|
|
81
|
+
async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
82
|
+
const inWindow = await isWithin24HourWindow(code);
|
|
83
|
+
const contentSid = inWindow ? null : runtimeConfig.get(templateKey);
|
|
84
|
+
if (!inWindow && !contentSid) throw new Error(`${templateKey} is not configured`);
|
|
85
|
+
const outgoing = inWindow
|
|
86
|
+
? { code, body: message.body, triggeredBy: operator }
|
|
87
|
+
: { code, contentSid, variables: message.template, triggeredBy: operator };
|
|
88
|
+
const result = await getMessaging().sendMessage(outgoing);
|
|
89
|
+
if (!result?.success && !result?.completed) throw new Error('The WhatsApp alert could not be sent');
|
|
90
|
+
if (result?.deferred) throw new Error('The WhatsApp alert was queued for template approval, not sent');
|
|
91
|
+
return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
|
|
95
|
+
|
|
96
|
+
// Phones alone count only once the notice template exists, or a notice outside the 24-hour window reaches no one.
|
|
97
|
+
const teamChannelConfigured = async () => groupConfigured() || (Boolean(runtimeConfig.get(NOTICE_TEMPLATE_KEY)) && (await teamPhones()).length > 0);
|
|
98
|
+
|
|
99
|
+
async function postToGroup(body, quoted) {
|
|
100
|
+
const res = await axios({
|
|
101
|
+
url: WHAPI_MESSAGES_URL,
|
|
102
|
+
method: 'POST',
|
|
103
|
+
data: { to: runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'), body, ...(quoted ? { quoted } : {}) },
|
|
104
|
+
timeout: REQUEST_TIMEOUT_MS,
|
|
105
|
+
headers: { authorization: `Bearer ${runtimeConfig.get('WHAPI_TOKEN')}` },
|
|
106
|
+
validateStatus: () => true,
|
|
107
|
+
});
|
|
108
|
+
if (res.status >= 200 && res.status < 300) return { delivered: true, error: null, messageId: res.data?.message?.id || null };
|
|
109
|
+
return { delivered: false, error: `whapi responded ${res.status}` };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function sendToGroup(body, quoted = null) {
|
|
113
|
+
if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
|
|
114
|
+
try {
|
|
115
|
+
const sent = await postToGroup(body, quoted);
|
|
116
|
+
// A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
|
|
117
|
+
return sent.delivered || !quoted ? sent : await postToGroup(body, null);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
return { delivered: false, error: redacted(error) };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Alerts the group and the on-call phones for `level` (all without one); one failed recipient never stops the others and nothing throws.
|
|
124
|
+
async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null }) {
|
|
125
|
+
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
126
|
+
const group = await sendToGroup(message.body, quoted);
|
|
127
|
+
const phones = [];
|
|
128
|
+
for (const code of await teamPhones(level)) {
|
|
129
|
+
try {
|
|
130
|
+
phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
|
|
131
|
+
} catch (error) {
|
|
132
|
+
phones.push({ code, delivered: false, transport: null, messageId: null, error: redacted(error) });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const delivered = (group.delivered ? 1 : 0) + phones.filter((phone) => phone.delivered).length;
|
|
136
|
+
if (!delivered) logger.error('[TeamAlert] The team alert reached no one', { groupError: group.error, phones: phones.length });
|
|
137
|
+
return { group, phones, delivered };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { _resetRoster, groupConfigured, sendGroupNotice: sendToGroup, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
2
|
|
|
3
|
-
const TemplateModel = require('../models/templateModel');
|
|
3
|
+
const { Template: TemplateModel } = require('../models/templateModel');
|
|
4
4
|
|
|
5
5
|
const { requireProvider } = require('../core/NexusMessaging');
|
|
6
6
|
|
|
@@ -15,7 +15,6 @@ const refreshApprovalStatuses = async (templates) => {
|
|
|
15
15
|
const reqData = approvalInfo.approvalRequest;
|
|
16
16
|
const updateFields = {
|
|
17
17
|
approvalRequest: {
|
|
18
|
-
sid: reqData.sid,
|
|
19
18
|
dateSubmitted: reqData.dateCreated ? new Date(reqData.dateCreated) : new Date(),
|
|
20
19
|
dateUpdated: reqData.dateUpdated ? new Date(reqData.dateUpdated) : new Date(),
|
|
21
20
|
rejectionReason: reqData.rejectionReason || ''
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
const { Config_ID, Monitoreo_ID, Historial_Clinico_ID } = require('../config/airtableConfig.js');
|
|
2
2
|
const runtimeConfig = require('../config/runtimeConfig.js');
|
|
3
|
+
const { programConfigSource } = require('../config/programConfig.js');
|
|
3
4
|
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
5
6
|
|
|
6
7
|
const { Thread } = require('../models/threadModel.js');
|
|
8
|
+
const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper.js');
|
|
9
|
+
const { patientIsDeceased } = require('../helpers/pausedThreadHelper.js');
|
|
7
10
|
|
|
8
11
|
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService.js');
|
|
12
|
+
const { ensurePatientResource } = require('../services/patientResourceService.js');
|
|
9
13
|
|
|
10
14
|
const getThread = async (code, message = null) => {
|
|
11
15
|
try {
|
|
@@ -24,20 +28,36 @@ const getThread = async (code, message = null) => {
|
|
|
24
28
|
}
|
|
25
29
|
};
|
|
26
30
|
|
|
27
|
-
const getThreadInfo = async (code) => {
|
|
31
|
+
const getThreadInfo = async (code, { rethrow = false } = {}) => {
|
|
28
32
|
try {
|
|
29
33
|
return await Thread.findOne({ code });
|
|
30
34
|
} catch (error) {
|
|
31
35
|
logger.error('[getThreadInfo] Error', { code, error: error.message });
|
|
36
|
+
if (rethrow) throw error;
|
|
32
37
|
return null;
|
|
33
38
|
}
|
|
34
39
|
};
|
|
35
40
|
|
|
36
|
-
const switchThreadStoppedStatus = async (code, stopped) => {
|
|
37
|
-
|
|
41
|
+
const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } = {}) => {
|
|
42
|
+
// A deceased patient's bot stays paused until the death is undone, whoever asks to resume it.
|
|
43
|
+
if (!stopped && await patientIsDeceased(code)) return { matchedCount: 0, modifiedCount: 0 };
|
|
44
|
+
const result = stopped && byOperator
|
|
45
|
+
? await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() })
|
|
46
|
+
: await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
|
|
38
47
|
|
|
39
48
|
updateRecordByFilter(Monitoreo_ID, 'message_monitor', `{whatsapp_id} = "${code}"`, { stopped }, code)
|
|
40
49
|
.catch(err => logger.error('[switchThreadStoppedStatus] Failed to update message_monitor', { code, error: err.message }));
|
|
50
|
+
|
|
51
|
+
return result;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const setThreadDoNotAlert = async (code, doNotAlert, through = null) => Thread.updateMany({ code }, { $set: { doNotAlertThrough: doNotAlert ? (through || new Date()) : null } });
|
|
55
|
+
|
|
56
|
+
const setCheckInsPausedUntil = async (code, until) => Thread.updateMany({ code }, { $set: { checkInsPausedUntil: until } });
|
|
57
|
+
|
|
58
|
+
const checkInsPausedUntil = async (code, now = new Date()) => {
|
|
59
|
+
const thread = await Thread.findOne({ code, checkInsPausedUntil: { $gt: now } }).select('checkInsPausedUntil').lean();
|
|
60
|
+
return thread?.checkInsPausedUntil || null;
|
|
41
61
|
};
|
|
42
62
|
|
|
43
63
|
const setThreadPromptId = async (code, promptId) => {
|
|
@@ -49,9 +69,15 @@ const setThreadPromptId = async (code, promptId) => {
|
|
|
49
69
|
.catch(err => logger.error('[setThreadPromptId] Failed to update message_monitor', { code, error: err.message }));
|
|
50
70
|
};
|
|
51
71
|
|
|
72
|
+
// `status` and `source` are multi-selects, so equality would miss a `prod, dev` row.
|
|
73
|
+
const defaultPromptFormula = () => {
|
|
74
|
+
const status = escapeFormulaValue(runtimeConfig.getServerMode());
|
|
75
|
+
const source = escapeFormulaValue(programConfigSource());
|
|
76
|
+
return `AND({code}="PIPO_ASST", FIND('${status}', ARRAYJOIN({status})), FIND('${source}', ARRAYJOIN({source})))`;
|
|
77
|
+
};
|
|
78
|
+
|
|
52
79
|
const createThread = async (code, { assistantId = null, fallbackName = null }) => {
|
|
53
|
-
const
|
|
54
|
-
const configRecord = await getRecordByFilter(Config_ID, 'responses', `AND({code}="PIPO_ASST", {status}="${assistantStatus}")`, undefined, ['prompt_id']);
|
|
80
|
+
const configRecord = await getRecordByFilter(Config_ID, 'responses', defaultPromptFormula(), undefined, ['prompt_id']);
|
|
55
81
|
const patientRecord = await getRecordByFilter(Historial_Clinico_ID, 'estado_general', `{whatsapp_id} = "${code}"`, undefined, ['name', 'record_id']);
|
|
56
82
|
|
|
57
83
|
const promptId = assistantId || configRecord?.[0]?.['prompt_id'] || null;
|
|
@@ -67,6 +93,8 @@ const createThread = async (code, { assistantId = null, fallbackName = null }) =
|
|
|
67
93
|
const condition = { code };
|
|
68
94
|
const options = { upsert: true, new: true };
|
|
69
95
|
await Thread.findOneAndUpdate( condition, { ...thread }, options);
|
|
96
|
+
ensurePatientResource(code)
|
|
97
|
+
.catch(err => logger.warn('[createThread] Patient anchor failed', { code, error: err.message }));
|
|
70
98
|
await switchThreadStoppedStatus(code, true);
|
|
71
99
|
await setThreadPromptId(code, promptId);
|
|
72
100
|
return await Thread.findOne({ code });
|
|
@@ -96,5 +124,9 @@ module.exports = {
|
|
|
96
124
|
createPlaceholderThread,
|
|
97
125
|
ensureThreadExists,
|
|
98
126
|
switchThreadStoppedStatus,
|
|
99
|
-
|
|
127
|
+
setThreadDoNotAlert,
|
|
128
|
+
setThreadPromptId,
|
|
129
|
+
setCheckInsPausedUntil,
|
|
130
|
+
checkInsPausedUntil,
|
|
131
|
+
defaultPromptFormula
|
|
100
132
|
};
|