@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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
|
-
const MapCache = require('../utils/MapCache');
|
|
2
|
+
const { MapCache } = require('../utils/MapCache');
|
|
3
3
|
const { normalize } = require('../utils/tokenMapUtils');
|
|
4
4
|
|
|
5
5
|
const { getGlobalEntityMap } = require('../models/globalEntityMapModel');
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const { normalizedKeyOf } = require('../utils/coercionUtils');
|
|
2
|
+
|
|
3
|
+
const { DOCUMENTING_STATUSES } = require('./escalationReviewService');
|
|
4
|
+
const { pendingWaitMinutes } = require('./reviewDeadlineService');
|
|
5
|
+
|
|
6
|
+
const keysOf = (flags) => [...new Set((flags ?? []).map(normalizedKeyOf).filter(Boolean))];
|
|
7
|
+
|
|
8
|
+
// The urgent red flags still pending in the latest draft of this episode, and since when each has been pending without a break.
|
|
9
|
+
function pendingFlagsOf(review, since) {
|
|
10
|
+
// A draft written before these fields existed says nothing about the flags, so it neither clears nor starts a wait.
|
|
11
|
+
const drafts = (review.drafts ?? [])
|
|
12
|
+
.filter((draft) => new Date(draft.createdAt).getTime() >= since.getTime() && Array.isArray(draft.urgentUnassessedRedFlags));
|
|
13
|
+
const firstSeen = new Map();
|
|
14
|
+
for (const draft of drafts) {
|
|
15
|
+
const pending = keysOf(draft.urgentUnassessedRedFlags);
|
|
16
|
+
for (const flag of [...firstSeen.keys()]) if (!pending.includes(flag)) firstSeen.delete(flag);
|
|
17
|
+
for (const flag of pending) if (!firstSeen.has(flag)) firstSeen.set(flag, new Date(draft.createdAt));
|
|
18
|
+
}
|
|
19
|
+
const unobtainable = keysOf(drafts.at(-1)?.unobtainableRedFlags);
|
|
20
|
+
return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
|
|
24
|
+
const isDraftCurrent = (review, latest) => !review.draftDueAt
|
|
25
|
+
&& !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
|
|
26
|
+
|
|
27
|
+
// A grave datum is missing at once when the patient cannot give it, or once it stays unanswered past the level's wait.
|
|
28
|
+
function graveMissingOf(review, clock, now) {
|
|
29
|
+
const limit = pendingWaitMinutes(clock?.level);
|
|
30
|
+
if (!limit) return [];
|
|
31
|
+
const { latest, flags } = pendingFlagsOf(review, clock.since);
|
|
32
|
+
if (!latest || !isDraftCurrent(review, latest)) return [];
|
|
33
|
+
// Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
|
|
34
|
+
const waiting = DOCUMENTING_STATUSES.includes(review.status);
|
|
35
|
+
return flags.flatMap(({ flag, firstSeenAt, unobtainable }) => {
|
|
36
|
+
if (unobtainable) return [{ flag, firstSeenAt, reason: 'unobtainable' }];
|
|
37
|
+
return waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000 ? [{ flag, firstSeenAt, reason: 'unanswered' }] : [];
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
const { Logging_ID, Symptoms_ID } = require('../config/airtableConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { mapConcurrent } = require('../utils/concurrencyUtils');
|
|
4
|
+
const { mexicoClock, mexicoWeekStart } = require('../utils/dateUtils');
|
|
5
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
|
+
const { inlineOf } = require('../utils/coercionUtils');
|
|
7
|
+
const { createdBetween } = require('../helpers/airtableFormulaHelper');
|
|
8
|
+
const { isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
9
|
+
const { STATUS, worst, signatureOf, countBySignature, lastDigits, hoursAgo } = require('../helpers/healthHelper');
|
|
10
|
+
const { getTurnTraceModel } = require('../clinical/models/turnTraceModel');
|
|
11
|
+
|
|
12
|
+
const { getRecordByFilter } = require('./airtableService');
|
|
13
|
+
const { stillUnanswered, unansweredThreads, threadIsOwnedByAHuman, silenceWasWavedOff } = require('./inboundRecoveryService');
|
|
14
|
+
|
|
15
|
+
const MINUTE_MS = 60 * 1000;
|
|
16
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
17
|
+
const CACHE_TTL_MS = MINUTE_MS;
|
|
18
|
+
const CHECK_TIMEOUT_MS = 10 * 1000;
|
|
19
|
+
|
|
20
|
+
const CREDITS_PATTERN = /no credits|insufficient_quota|exceeded your current quota|credit balance|spend limit|usage limit|billing/i;
|
|
21
|
+
const CREDITS_WINDOW_MS = 24 * HOUR_MS;
|
|
22
|
+
const CREDITS_RED_MS = 6 * HOUR_MS;
|
|
23
|
+
|
|
24
|
+
const BUG_REPORTS_TABLE = 'bug_reports';
|
|
25
|
+
const BUG_REPORTS_LINK = `https://airtable.com/${Logging_ID}/tblnhMcSKQV92tPdp`;
|
|
26
|
+
const SYSTEM_ERRORS = '{server} != \'\', {reporterToGithub} = \'system\', {devServer} = 0';
|
|
27
|
+
|
|
28
|
+
const PATIENTS_TABLE = 'estado_general';
|
|
29
|
+
const QUESTIONNAIRES_TABLE = 'weekly_questionnaires';
|
|
30
|
+
const WEEKLY_VIEW = 'viwEm1YhVDDf8ACQR';
|
|
31
|
+
const WEEKLY_LINK = `https://airtable.com/${Symptoms_ID}/tblUi9KbsefAbrvK2/${WEEKLY_VIEW}`;
|
|
32
|
+
const WEEKLY_TARGET = 0.95;
|
|
33
|
+
|
|
34
|
+
const FAILED_TURN_WINDOW_MS = HOUR_MS;
|
|
35
|
+
const FAILED_PATIENTS_RED = 3;
|
|
36
|
+
const UNANSWERED_MIN_AGE_MS = 30 * MINUTE_MS;
|
|
37
|
+
const UNANSWERED_MAX_AGE_MS = 24 * HOUR_MS;
|
|
38
|
+
const UNANSWERED_LATE_MS = 2 * HOUR_MS;
|
|
39
|
+
const UNANSWERED_RED = 5;
|
|
40
|
+
const UNANSWERED_SCAN_LIMIT = 200;
|
|
41
|
+
const UNANSWERED_CONCURRENCY = 20;
|
|
42
|
+
|
|
43
|
+
const BUG_WINDOW_MS = 24 * HOUR_MS;
|
|
44
|
+
const BUG_SIGNATURE_AMBER = 5;
|
|
45
|
+
const BUG_SIGNATURE_RED = 20;
|
|
46
|
+
const DETAIL_LIMIT = 10;
|
|
47
|
+
|
|
48
|
+
let cached = null;
|
|
49
|
+
let inflight = null;
|
|
50
|
+
|
|
51
|
+
async function checkLlmCredits(now) {
|
|
52
|
+
const since = new Date(now.getTime() - CREDITS_WINDOW_MS);
|
|
53
|
+
const [reports, traces] = await Promise.all([
|
|
54
|
+
getRecordByFilter(Logging_ID, BUG_REPORTS_TABLE, createdBetween(since, now), null, ['description', 'server'], true),
|
|
55
|
+
getTurnTraceModel()
|
|
56
|
+
.find({ shadow: false, createdAt: { $gte: since, $lte: now }, 'abort.message': CREDITS_PATTERN })
|
|
57
|
+
.select({ 'abort.message': 1, createdAt: 1 })
|
|
58
|
+
.lean(),
|
|
59
|
+
]);
|
|
60
|
+
const events = [
|
|
61
|
+
...reports
|
|
62
|
+
.filter((r) => CREDITS_PATTERN.test(String(r.description || '')))
|
|
63
|
+
.map((r) => ({ at: new Date(r._createdTime), text: `${r.server || 'servidor'}: ${r.description}` })),
|
|
64
|
+
...traces
|
|
65
|
+
.filter((t) => CREDITS_PATTERN.test(String(t.abort?.message || '')))
|
|
66
|
+
.map((t) => ({ at: new Date(t.createdAt), text: `agente: ${t.abort?.message}` })),
|
|
67
|
+
];
|
|
68
|
+
const newest = events.reduce((max, e) => (e.at > max ? e.at : max), null);
|
|
69
|
+
const sinceNewestMs = newest ? now.getTime() - newest.getTime() : null;
|
|
70
|
+
|
|
71
|
+
let status = STATUS.GREEN;
|
|
72
|
+
if (newest && sinceNewestMs <= CREDITS_RED_MS) status = STATUS.RED;
|
|
73
|
+
else if (newest) status = STATUS.AMBER;
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
check: 'H1',
|
|
77
|
+
key: 'llm_credits',
|
|
78
|
+
label: 'Saldo de los proveedores de IA',
|
|
79
|
+
status,
|
|
80
|
+
value: events.length,
|
|
81
|
+
threshold: 'un error de saldo o cuota en las últimas 6 h (rojo) o 24 h (ámbar)',
|
|
82
|
+
summary: newest
|
|
83
|
+
? `${events.length} errores de saldo o cuota en 24 h · el último hace ${hoursAgo(sinceNewestMs)}`
|
|
84
|
+
: 'Sin errores de saldo en las últimas 24 h',
|
|
85
|
+
detail: countBySignature(events.map((e) => e.text)).slice(0, DETAIL_LIMIT).map(([sig, n]) => `${n} × ${sig}`),
|
|
86
|
+
link: BUG_REPORTS_LINK,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function checkWeeklyCoverage(now) {
|
|
91
|
+
const weekStart = mexicoWeekStart(now);
|
|
92
|
+
const [patients, weeklies] = await Promise.all([
|
|
93
|
+
getRecordByFilter(Symptoms_ID, PATIENTS_TABLE, '{tipo} = \'prod\'', WEEKLY_VIEW, ['whatsapp_id', 'first_triage_date_received'], true),
|
|
94
|
+
getRecordByFilter(Symptoms_ID, QUESTIONNAIRES_TABLE, `AND({type_quest} = 'weekly', ${createdBetween(weekStart, now)})`, null, ['patient_id']),
|
|
95
|
+
]);
|
|
96
|
+
const covered = new Set(weeklies.flatMap((q) => q.patient_id || []));
|
|
97
|
+
// A patient whose first triage landed this week is not due a weekly until next Sunday.
|
|
98
|
+
const expected = patients.filter((p) => !isArchivedPatientCode(inlineOf(p.whatsapp_id))
|
|
99
|
+
&& !(p.first_triage_date_received && new Date(p.first_triage_date_received) >= weekStart));
|
|
100
|
+
const base = {
|
|
101
|
+
check: 'H2',
|
|
102
|
+
key: 'weekly_coverage',
|
|
103
|
+
label: 'Cobertura del cuestionario semanal',
|
|
104
|
+
threshold: `<${WEEKLY_TARGET * 100}% (rojo el domingo desde las 06:00 y el lunes, MX)`,
|
|
105
|
+
link: WEEKLY_LINK,
|
|
106
|
+
};
|
|
107
|
+
if (!expected.length) {
|
|
108
|
+
return { ...base, status: STATUS.UNKNOWN, value: null, summary: 'La vista no devolvió pacientes', detail: [] };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const missing = expected.filter((p) => !covered.has(p._recordId));
|
|
112
|
+
const ratio = (expected.length - missing.length) / expected.length;
|
|
113
|
+
const { weekday, hour } = mexicoClock(now);
|
|
114
|
+
const isEnforced = (weekday === 0 && hour >= 6) || weekday === 1;
|
|
115
|
+
|
|
116
|
+
let status = STATUS.GREEN;
|
|
117
|
+
if (ratio < WEEKLY_TARGET) status = isEnforced ? STATUS.RED : STATUS.AMBER;
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
...base,
|
|
121
|
+
status,
|
|
122
|
+
value: Math.round(ratio * 100),
|
|
123
|
+
summary: `${expected.length - missing.length} de ${expected.length} pacientes con weekly esta semana`,
|
|
124
|
+
detail: missing.slice(0, DETAIL_LIMIT * 3).map((p) => `Sin weekly: …${lastDigits(p.whatsapp_id)}`),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function unansweredPatients(now) {
|
|
129
|
+
const threads = await unansweredThreads(now, {
|
|
130
|
+
minAgeMs: UNANSWERED_MIN_AGE_MS, maxAgeMs: UNANSWERED_MAX_AGE_MS, limit: UNANSWERED_SCAN_LIMIT,
|
|
131
|
+
});
|
|
132
|
+
const waiting = [];
|
|
133
|
+
await mapConcurrent(threads, UNANSWERED_CONCURRENCY, async ({ code }) => {
|
|
134
|
+
const newest = await stillUnanswered(code, now, { minAgeMs: UNANSWERED_MIN_AGE_MS, maxAgeMs: UNANSWERED_MAX_AGE_MS });
|
|
135
|
+
if (!newest) return;
|
|
136
|
+
if (await threadIsOwnedByAHuman(code)) return;
|
|
137
|
+
if (await silenceWasWavedOff(code, newest.createdAt)) return;
|
|
138
|
+
waiting.push({ code, ageMs: now.getTime() - new Date(newest.createdAt).getTime() });
|
|
139
|
+
});
|
|
140
|
+
return waiting.sort((a, b) => b.ageMs - a.ageMs);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function checkUnansweredMessages(now) {
|
|
144
|
+
const since = new Date(now.getTime() - FAILED_TURN_WINDOW_MS);
|
|
145
|
+
const [failed, waiting] = await Promise.all([
|
|
146
|
+
getTurnTraceModel()
|
|
147
|
+
.find({ shadow: false, status: 'failed', createdAt: { $gte: since, $lte: now } })
|
|
148
|
+
.select({ 'abort.message': 1, patientCode: 1 })
|
|
149
|
+
.lean(),
|
|
150
|
+
unansweredPatients(now),
|
|
151
|
+
]);
|
|
152
|
+
const patientsBySignature = new Map();
|
|
153
|
+
for (const t of failed) {
|
|
154
|
+
const sig = signatureOf(t.abort?.message);
|
|
155
|
+
if (!patientsBySignature.has(sig)) patientsBySignature.set(sig, new Set());
|
|
156
|
+
patientsBySignature.get(sig).add(t.patientCode);
|
|
157
|
+
}
|
|
158
|
+
const signatures = countBySignature(failed.map((t) => t.abort?.message));
|
|
159
|
+
const isWidespread = [...patientsBySignature.values()].some((codes) => codes.size >= FAILED_PATIENTS_RED);
|
|
160
|
+
const late = waiting.filter((w) => w.ageMs >= UNANSWERED_LATE_MS);
|
|
161
|
+
|
|
162
|
+
let failedStatus = STATUS.GREEN;
|
|
163
|
+
if (isWidespread) failedStatus = STATUS.RED;
|
|
164
|
+
else if (failed.length) failedStatus = STATUS.AMBER;
|
|
165
|
+
let lateStatus = STATUS.GREEN;
|
|
166
|
+
if (late.length >= UNANSWERED_RED) lateStatus = STATUS.RED;
|
|
167
|
+
else if (late.length) lateStatus = STATUS.AMBER;
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
check: 'H5',
|
|
171
|
+
key: 'unanswered_messages',
|
|
172
|
+
label: 'Pacientes sin respuesta',
|
|
173
|
+
status: worst(failedStatus, lateStatus),
|
|
174
|
+
value: late.length,
|
|
175
|
+
threshold: `≥1 sin respuesta >2 h (ámbar), ≥${UNANSWERED_RED} (rojo); la misma falla del agente en ≥${FAILED_PATIENTS_RED} pacientes en 1 h (rojo)`,
|
|
176
|
+
summary: `${late.length} sin respuesta hace más de 2 h · ${failed.length} turnos del agente fallidos en 1 h`,
|
|
177
|
+
detail: [
|
|
178
|
+
...signatures.slice(0, 3).map(([sig, n]) => `Agente: ${n} × ${sig} (${patientsBySignature.get(sig)?.size || 0} pacientes)`),
|
|
179
|
+
...late.slice(0, DETAIL_LIMIT).map((w) => `…${lastDigits(w.code)} lleva ${hoursAgo(w.ageMs)} sin respuesta`),
|
|
180
|
+
],
|
|
181
|
+
link: null,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function checkNewErrors(now) {
|
|
186
|
+
const since = new Date(now.getTime() - BUG_WINDOW_MS);
|
|
187
|
+
const rows = await getRecordByFilter(
|
|
188
|
+
Logging_ID, BUG_REPORTS_TABLE, `AND(${createdBetween(since, now)}, ${SYSTEM_ERRORS})`, null, ['description', 'server'],
|
|
189
|
+
);
|
|
190
|
+
const signatures = countBySignature(rows.map((r) => `${r.server}: ${r.description}`));
|
|
191
|
+
const top = signatures[0]?.[1] || 0;
|
|
192
|
+
|
|
193
|
+
let status = STATUS.GREEN;
|
|
194
|
+
if (top >= BUG_SIGNATURE_RED) status = STATUS.RED;
|
|
195
|
+
else if (top >= BUG_SIGNATURE_AMBER) status = STATUS.AMBER;
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
check: 'H10',
|
|
199
|
+
key: 'new_errors',
|
|
200
|
+
label: 'Errores automáticos de servidor',
|
|
201
|
+
status,
|
|
202
|
+
value: rows.length,
|
|
203
|
+
threshold: `una misma falla ≥${BUG_SIGNATURE_AMBER} (ámbar) o ≥${BUG_SIGNATURE_RED} (rojo) en 24 h`,
|
|
204
|
+
summary: `${rows.length} errores de servidor en 24 h, ${signatures.length} distintos`,
|
|
205
|
+
detail: signatures.slice(0, 3).map(([sig, n]) => `${n} × ${sig}`),
|
|
206
|
+
link: BUG_REPORTS_LINK,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const CHECKS = [
|
|
211
|
+
{ check: 'H1', key: 'llm_credits', label: 'Saldo de los proveedores de IA', run: checkLlmCredits },
|
|
212
|
+
{ check: 'H2', key: 'weekly_coverage', label: 'Cobertura del cuestionario semanal', run: checkWeeklyCoverage },
|
|
213
|
+
{ check: 'H5', key: 'unanswered_messages', label: 'Pacientes sin respuesta', run: checkUnansweredMessages },
|
|
214
|
+
{ check: 'H10', key: 'new_errors', label: 'Errores automáticos de servidor', run: checkNewErrors },
|
|
215
|
+
];
|
|
216
|
+
|
|
217
|
+
// H2 and H5 read current state, so only H1 and H10 can be evaluated at a past `now`.
|
|
218
|
+
async function computeHealthSummary(now = new Date()) {
|
|
219
|
+
const computedAt = now.toISOString();
|
|
220
|
+
const settled = await Promise.allSettled(CHECKS.map(({ check, run }) => withTimeout(Promise.resolve().then(() => run(now)), CHECK_TIMEOUT_MS, check)));
|
|
221
|
+
const checks = settled.map((result, i) => {
|
|
222
|
+
if (result.status === 'fulfilled') return { ...result.value, computedAt };
|
|
223
|
+
const { check, key, label } = CHECKS[i];
|
|
224
|
+
logger.warn('[HealthService] check failed', { check, error: result.reason?.message });
|
|
225
|
+
return { check, key, label, status: STATUS.UNKNOWN, value: null, threshold: null, summary: 'No se pudo calcular', detail: [], link: null, computedAt };
|
|
226
|
+
});
|
|
227
|
+
return { computedAt, status: worst(...checks.map((c) => c.status)), checks };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function getHealthSummary({ force = false, now = new Date() } = {}) {
|
|
231
|
+
if (!force && cached && now.getTime() - cached.at < CACHE_TTL_MS) return cached.summary;
|
|
232
|
+
if (inflight) return inflight;
|
|
233
|
+
inflight = computeHealthSummary(now)
|
|
234
|
+
.then((summary) => {
|
|
235
|
+
cached = { at: now.getTime(), summary };
|
|
236
|
+
return summary;
|
|
237
|
+
})
|
|
238
|
+
.finally(() => { inflight = null; });
|
|
239
|
+
return inflight;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const _resetHealthCache = () => { cached = null; inflight = null; };
|
|
243
|
+
|
|
244
|
+
module.exports = {
|
|
245
|
+
getHealthSummary,
|
|
246
|
+
computeHealthSummary,
|
|
247
|
+
checkLlmCredits,
|
|
248
|
+
checkWeeklyCoverage,
|
|
249
|
+
checkUnansweredMessages,
|
|
250
|
+
checkNewErrors,
|
|
251
|
+
_resetHealthCache,
|
|
252
|
+
};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { isWithinHourWindow, contactHoursBetween } = require('../utils/scheduleUtils');
|
|
3
|
+
|
|
4
|
+
const { Message } = require('../models/messageModel');
|
|
5
|
+
|
|
6
|
+
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
|
+
const { contactOf } = require('../helpers/caregiverHelper');
|
|
8
|
+
const { cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi } = require('../helpers/templateRecoveryHelper');
|
|
9
|
+
|
|
10
|
+
const { getMessages } = require('./messageService');
|
|
11
|
+
|
|
12
|
+
const getMessaging = () => require('../core/NexusMessaging');
|
|
13
|
+
|
|
14
|
+
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
|
|
15
|
+
const MAX_CONTACT_HOURS = 3;
|
|
16
|
+
const MAX_RELEASE_BATCH = 5;
|
|
17
|
+
const MAX_HELD_AGE_MS = 24 * 60 * 60 * 1000;
|
|
18
|
+
const MAX_SWEEP_CANDIDATES = 200;
|
|
19
|
+
|
|
20
|
+
function heldQuery(extra = {}) {
|
|
21
|
+
return {
|
|
22
|
+
from_me: true,
|
|
23
|
+
createdAt: { $gte: new Date(Date.now() - MAX_HELD_AGE_MS) },
|
|
24
|
+
'statusInfo.recoverySentAt': null,
|
|
25
|
+
'statusInfo.recoveryReleasedAt': null,
|
|
26
|
+
$or: [
|
|
27
|
+
{ 'statusInfo.recoveryTemplateSid': { $ne: null } },
|
|
28
|
+
{ 'statusInfo.recoveryFailedAt': { $ne: null } },
|
|
29
|
+
{ 'statusInfo.recoveryRejectedAt': { $ne: null } }
|
|
30
|
+
],
|
|
31
|
+
...extra
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function releaseClaim(messageId) {
|
|
36
|
+
await Message.updateOne({ _id: messageId }, { $unset: { 'statusInfo.recoveryReleasedAt': '' } });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function releaseOne(message, now) {
|
|
40
|
+
const logCtx = { messageId: String(message._id), to: message.numero };
|
|
41
|
+
|
|
42
|
+
const aged = contactHoursBetween(message.createdAt, now, PATIENT_CONTACT_WINDOW);
|
|
43
|
+
if (aged === null || aged > MAX_CONTACT_HOURS) {
|
|
44
|
+
logger.info('[HeldMessage] Held message is past its freshness bound, leaving it for staff', {
|
|
45
|
+
...logCtx, contactHours: aged === null ? null : Number(aged.toFixed(2))
|
|
46
|
+
});
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const body = await resolveRecoveryBody(message);
|
|
51
|
+
if (hasUnresolvedPhi(body)) {
|
|
52
|
+
logger.error('[HeldMessage] Body still carries a PHI placeholder, refusing to release', logCtx);
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const claim = await Message.updateOne(
|
|
57
|
+
{ _id: message._id, 'statusInfo.recoveryReleasedAt': null, 'statusInfo.recoverySentAt': null },
|
|
58
|
+
{ $set: { 'statusInfo.recoveryReleasedAt': new Date() } }
|
|
59
|
+
);
|
|
60
|
+
if (!claim.modifiedCount && !claim.nModified) return false;
|
|
61
|
+
|
|
62
|
+
const sidBeforeSend = message.message_id || null;
|
|
63
|
+
let result;
|
|
64
|
+
try {
|
|
65
|
+
result = await getMessaging().sendMessage({
|
|
66
|
+
code: message.numero,
|
|
67
|
+
...contactOf(message),
|
|
68
|
+
body,
|
|
69
|
+
parentMessageId: message._id,
|
|
70
|
+
kind: 'freeform',
|
|
71
|
+
idempotencyKey: `window-release:${message._id}`
|
|
72
|
+
});
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const [after] = await getMessages({ _id: message._id }, { select: 'message_id', limit: 1 });
|
|
75
|
+
if (after?.message_id && after.message_id !== sidBeforeSend) {
|
|
76
|
+
logger.error('[HeldMessage] Release reached the provider but bookkeeping failed', {
|
|
77
|
+
...logCtx, error: error.message
|
|
78
|
+
});
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
await releaseClaim(message._id);
|
|
82
|
+
logger.error('[HeldMessage] Release send failed', { ...logCtx, error: error.message });
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (result?.duplicate) {
|
|
87
|
+
await releaseClaim(message._id);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
await cleanupRecoveryTemplate(message);
|
|
92
|
+
|
|
93
|
+
logger.info('[HeldMessage] Delivered a held message on the reopened window', {
|
|
94
|
+
...logCtx, contactHours: Number(aged.toFixed(2))
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function releaseHeldMessages(code, { contactCode = null } = {}) {
|
|
101
|
+
if (!code) return { released: 0, reason: 'no_code' };
|
|
102
|
+
|
|
103
|
+
const now = new Date();
|
|
104
|
+
if (!isWithinHourWindow(now, PATIENT_CONTACT_WINDOW)) {
|
|
105
|
+
return { released: 0, reason: 'quiet_hours' };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const held = await getMessages(heldQuery({ numero: code, contact_code: contactCode }), { sort: { createdAt: 1 }, limit: MAX_RELEASE_BATCH });
|
|
109
|
+
if (!held.length) return { released: 0, reason: 'none_held' };
|
|
110
|
+
|
|
111
|
+
let released = 0;
|
|
112
|
+
for (const message of held) {
|
|
113
|
+
if (await releaseOne(message, now)) released += 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return { released, considered: held.length };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function sweepHeldMessages() {
|
|
120
|
+
if (!isWithinHourWindow(new Date(), PATIENT_CONTACT_WINDOW)) return 0;
|
|
121
|
+
|
|
122
|
+
const recent = await getMessages(heldQuery(), {
|
|
123
|
+
select: 'numero contact_code', sort: { createdAt: -1 }, limit: MAX_SWEEP_CANDIDATES
|
|
124
|
+
});
|
|
125
|
+
const phones = new Map(recent.map(doc => [`${doc.numero}|${doc.contact_code || ''}`, { code: doc.numero, contactCode: doc.contact_code || null }]));
|
|
126
|
+
let released = 0;
|
|
127
|
+
|
|
128
|
+
for (const { code, contactCode } of phones.values()) {
|
|
129
|
+
try {
|
|
130
|
+
if (!(await isWithin24HourWindow(code, { contactCode }))) continue;
|
|
131
|
+
const outcome = await releaseHeldMessages(code, { contactCode });
|
|
132
|
+
released += outcome.released;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.error('[HeldMessage] Sweep failed for one conversation', { code, error: error.message });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return released;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = { releaseHeldMessages, sweepHeldMessages };
|