@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,177 @@
|
|
|
1
|
+
// Tables and fields are configured by Airtable id, so renaming them in Airtable cannot change what the archive does.
|
|
2
|
+
const ARCHIVE_TABLES = Object.freeze({
|
|
3
|
+
QUESTIONNAIRES: 'tbl5VjUMEdPQJ8oR6',
|
|
4
|
+
TRIAGES: 'tblC1fwHpWEfDBovf',
|
|
5
|
+
SYMPTOMS: 'tblNHfup9y1s77vdN',
|
|
6
|
+
ADDITIONAL_ANSWERS: 'tblFeHmI5JDACsOBd',
|
|
7
|
+
RECOMMENDATIONS: 'tblwDv3v5wcFKnPrE',
|
|
8
|
+
RESOLUTIONS: 'tbly4e90Xcp19a6VA',
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const ARCHIVE_FIELDS = Object.freeze({
|
|
12
|
+
QUESTIONNAIRE: Object.freeze({
|
|
13
|
+
TRIAGE: 'fldFIcRnYXr6HbGEr',
|
|
14
|
+
ADDITIONAL_ANSWERS: 'fldCD4MvSjJ6GGYeQ',
|
|
15
|
+
PREVIOUS_TRIAGE: 'fldekZghYN1Zv7U5j',
|
|
16
|
+
PREVIOUS_SYMPTOMS: 'flduGxzHejCy7FfTr',
|
|
17
|
+
PHYSICIAN_REPORT: 'fld3w7Zfuc8BChDOL',
|
|
18
|
+
EXTRACTION_ANALYSIS: 'fldcrm4xZuG2hHzW2',
|
|
19
|
+
PATIENT: 'fldMIxWgaGiF7IvYr',
|
|
20
|
+
WHATSAPP: 'fld5XXqDfLgT8JQS4',
|
|
21
|
+
CREATED: 'fld1rLI32ITUtgfdJ',
|
|
22
|
+
APPROVED: 'fldTgcHGvR6Dy64US',
|
|
23
|
+
}),
|
|
24
|
+
TRIAGE: Object.freeze({
|
|
25
|
+
QUESTIONNAIRE: 'fldPSXnnwABCVlJYa',
|
|
26
|
+
SYMPTOMS: 'fld6mNLRqEjNqh6lc',
|
|
27
|
+
RECOMMENDATIONS: 'fldfIkWJNHmbzYWyk',
|
|
28
|
+
NEXT_QUESTIONNAIRE: 'fldjFFoiNFQfEJaTd',
|
|
29
|
+
PAIN_FOLLOW_UP: 'fldkWqBcTY8Y4nB3r',
|
|
30
|
+
PATIENT: 'fld13AeMleGR4Ar2S',
|
|
31
|
+
WHATSAPP: 'fldSPX9JIe1vS8fFQ',
|
|
32
|
+
}),
|
|
33
|
+
SYMPTOM: Object.freeze({
|
|
34
|
+
TRIAGE: 'fldmam6VjxqsDhIOc',
|
|
35
|
+
RECOMMENDATIONS: 'fldKWnRpBOw1bDgvE',
|
|
36
|
+
NEXT_QUESTIONNAIRE: 'fldRgZqXn4W5zYxIV',
|
|
37
|
+
PHYSICIAN_REPORT: 'fldE1RJpWMq9J7kye',
|
|
38
|
+
PATIENT: 'fld1HwByMBq3sPLf3',
|
|
39
|
+
WHATSAPP: 'fldN5yrbmRQlt35II',
|
|
40
|
+
}),
|
|
41
|
+
ADDITIONAL_ANSWER: Object.freeze({ QUESTIONNAIRE: 'fldWeXx3CalMGphYb' }),
|
|
42
|
+
RECOMMENDATION: Object.freeze({
|
|
43
|
+
TRIAGE: 'fldgY1c0T9MJhxtno',
|
|
44
|
+
SYMPTOMS: 'fldPnsR2JgEOWbdKi',
|
|
45
|
+
RESOLUTIONS: 'fld3vY8ATExN85r9U',
|
|
46
|
+
}),
|
|
47
|
+
RESOLUTION: Object.freeze({ RECOMMENDATION: 'fldOotQhruyC1tPuW' }),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const TABLE = ARCHIVE_TABLES;
|
|
51
|
+
const FIELD = ARCHIVE_FIELDS;
|
|
52
|
+
|
|
53
|
+
// Links inside one triage group: their records are archived together or not at all.
|
|
54
|
+
const GROUP_LINKS = Object.freeze({
|
|
55
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.TRIAGE, FIELD.QUESTIONNAIRE.ADDITIONAL_ANSWERS],
|
|
56
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.QUESTIONNAIRE, FIELD.TRIAGE.SYMPTOMS, FIELD.TRIAGE.RECOMMENDATIONS],
|
|
57
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.TRIAGE, FIELD.SYMPTOM.RECOMMENDATIONS],
|
|
58
|
+
[TABLE.ADDITIONAL_ANSWERS]: [FIELD.ADDITIONAL_ANSWER.QUESTIONNAIRE],
|
|
59
|
+
[TABLE.RECOMMENDATIONS]: [FIELD.RECOMMENDATION.TRIAGE, FIELD.RECOMMENDATION.SYMPTOMS, FIELD.RECOMMENDATION.RESOLUTIONS],
|
|
60
|
+
[TABLE.RESOLUTIONS]: [FIELD.RESOLUTION.RECOMMENDATION],
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Links from an older group to the newer questionnaire generated from it.
|
|
64
|
+
const CARRY_OVER_LINKS = Object.freeze({
|
|
65
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.NEXT_QUESTIONNAIRE],
|
|
66
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.NEXT_QUESTIONNAIRE],
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// Questionnaire links back to the group it continues: they keep a group only when they reach outside the scan.
|
|
70
|
+
const BACKWARD_LINKS = Object.freeze({
|
|
71
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PREVIOUS_TRIAGE, FIELD.QUESTIONNAIRE.PREVIOUS_SYMPTOMS],
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Links to non-catalog tables that are never archived: a linked group stays in Airtable.
|
|
75
|
+
const EXTERNAL_LINKS = Object.freeze({
|
|
76
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PHYSICIAN_REPORT, FIELD.QUESTIONNAIRE.EXTRACTION_ANALYSIS],
|
|
77
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.PAIN_FOLLOW_UP],
|
|
78
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.PHYSICIAN_REPORT],
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const PATIENT_FIELDS = Object.freeze({
|
|
82
|
+
[TABLE.QUESTIONNAIRES]: FIELD.QUESTIONNAIRE.PATIENT,
|
|
83
|
+
[TABLE.TRIAGES]: FIELD.TRIAGE.PATIENT,
|
|
84
|
+
[TABLE.SYMPTOMS]: FIELD.SYMPTOM.PATIENT,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const WHATSAPP_FIELDS = Object.freeze({
|
|
88
|
+
[TABLE.QUESTIONNAIRES]: FIELD.QUESTIONNAIRE.WHATSAPP,
|
|
89
|
+
[TABLE.TRIAGES]: FIELD.TRIAGE.WHATSAPP,
|
|
90
|
+
[TABLE.SYMPTOMS]: FIELD.SYMPTOM.WHATSAPP,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const QUESTIONNAIRE_ANCHOR_FIELDS = [FIELD.QUESTIONNAIRE.CREATED, FIELD.QUESTIONNAIRE.APPROVED];
|
|
94
|
+
|
|
95
|
+
const plannerFieldsOf = (tableId) => [...new Set([
|
|
96
|
+
...[GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS].flatMap((links) => links[tableId] || []),
|
|
97
|
+
PATIENT_FIELDS[tableId], WHATSAPP_FIELDS[tableId],
|
|
98
|
+
...(tableId === TABLE.QUESTIONNAIRES ? QUESTIONNAIRE_ANCHOR_FIELDS : []),
|
|
99
|
+
].filter(Boolean))];
|
|
100
|
+
|
|
101
|
+
// The only fields the planner reads, so the scan of every old record stays small.
|
|
102
|
+
const PLANNER_FIELDS = Object.freeze(Object.fromEntries(Object.values(TABLE).map((tableId) => [tableId, Object.freeze(plannerFieldsOf(tableId))])));
|
|
103
|
+
|
|
104
|
+
const LINK_FIELD_TYPES = Object.freeze(['multipleRecordLinks']);
|
|
105
|
+
const CHECKBOX_FIELD_TYPES = Object.freeze(['checkbox']);
|
|
106
|
+
const DATE_FIELD_TYPES = Object.freeze(['dateTime', 'date']);
|
|
107
|
+
const FIRST_MONTH_DAYS = 30;
|
|
108
|
+
|
|
109
|
+
const KEEP_REASONS = Object.freeze({
|
|
110
|
+
LINKS_NEWER: 'links_newer',
|
|
111
|
+
LINKS_OUTSIDE: 'links_outside',
|
|
112
|
+
FIRST_QUESTIONNAIRE: 'first_questionnaire',
|
|
113
|
+
FIRST_TRIAGE: 'first_triage',
|
|
114
|
+
FIRST_MONTH: 'first_month',
|
|
115
|
+
LATEST_QUESTIONNAIRE: 'latest_questionnaire',
|
|
116
|
+
LATEST_TRIAGE: 'latest_triage',
|
|
117
|
+
UNAPPROVED_QUESTIONNAIRE: 'unapproved_questionnaire',
|
|
118
|
+
CARRIED_INTO_NEWER: 'carried_into_newer',
|
|
119
|
+
CARRIED_INTO_KEPT: 'carried_into_kept',
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// A guard against a mistyped cutoff: nothing younger than this is ever archived.
|
|
123
|
+
const MIN_ARCHIVE_AGE_DAYS = 90;
|
|
124
|
+
const ARCHIVE_BATCH_SIZE = 100;
|
|
125
|
+
// Airtable field types whose value Airtable computes; they are stored but never decide whether the source changed.
|
|
126
|
+
const COMPUTED_FIELD_TYPES = Object.freeze([
|
|
127
|
+
'formula', 'rollup', 'count', 'multipleLookupValues', 'lastModifiedTime', 'lastModifiedBy',
|
|
128
|
+
'createdTime', 'createdBy', 'autoNumber', 'button', 'aiText',
|
|
129
|
+
]);
|
|
130
|
+
const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
|
|
131
|
+
const ARCHIVE_LEASE_RENEW_MS = 60 * 1000;
|
|
132
|
+
const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
133
|
+
const ARCHIVE_DELETE_MAX_GROUPS = 1000;
|
|
134
|
+
// Parents first: a surviving parent never sees its children vanish, which would match the base's send automations.
|
|
135
|
+
const ARCHIVE_DELETE_ORDER = Object.freeze([
|
|
136
|
+
ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_TABLES.TRIAGES, ARCHIVE_TABLES.RECOMMENDATIONS,
|
|
137
|
+
ARCHIVE_TABLES.RESOLUTIONS, ARCHIVE_TABLES.ADDITIONAL_ANSWERS, ARCHIVE_TABLES.SYMPTOMS,
|
|
138
|
+
]);
|
|
139
|
+
const ARCHIVE_DELETE_SPACING_MS = 250;
|
|
140
|
+
// Airtable deletes at most 10 records per request.
|
|
141
|
+
const ARCHIVE_DELETE_CHUNK_SIZE = 10;
|
|
142
|
+
const PATIENT_TABLE = Object.freeze({ ID: 'tblUi9KbsefAbrvK2', WHATSAPP: 'fldMfzbVbAxIJ9345' });
|
|
143
|
+
const MIRROR_MAX_ATTACHMENTS_PER_RUN = 2000;
|
|
144
|
+
// More records missing from a full scan than this is taken for a bad read, not deletions: none are marked gone.
|
|
145
|
+
const MIRROR_GONE_MAX_SHARE = 0.02;
|
|
146
|
+
const MIRROR_GONE_MIN_HELD = 25;
|
|
147
|
+
|
|
148
|
+
module.exports = {
|
|
149
|
+
ARCHIVE_TABLES,
|
|
150
|
+
ARCHIVE_FIELDS,
|
|
151
|
+
MIN_ARCHIVE_AGE_DAYS,
|
|
152
|
+
ARCHIVE_BATCH_SIZE,
|
|
153
|
+
ARCHIVE_LEASE_MS,
|
|
154
|
+
ARCHIVE_LEASE_RENEW_MS,
|
|
155
|
+
ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
156
|
+
ARCHIVE_DELETE_MAX_GROUPS,
|
|
157
|
+
ARCHIVE_DELETE_ORDER,
|
|
158
|
+
ARCHIVE_DELETE_SPACING_MS,
|
|
159
|
+
ARCHIVE_DELETE_CHUNK_SIZE,
|
|
160
|
+
PATIENT_TABLE,
|
|
161
|
+
MIRROR_MAX_ATTACHMENTS_PER_RUN,
|
|
162
|
+
MIRROR_GONE_MAX_SHARE,
|
|
163
|
+
MIRROR_GONE_MIN_HELD,
|
|
164
|
+
COMPUTED_FIELD_TYPES,
|
|
165
|
+
GROUP_LINKS,
|
|
166
|
+
CARRY_OVER_LINKS,
|
|
167
|
+
BACKWARD_LINKS,
|
|
168
|
+
EXTERNAL_LINKS,
|
|
169
|
+
PATIENT_FIELDS,
|
|
170
|
+
PLANNER_FIELDS,
|
|
171
|
+
WHATSAPP_FIELDS,
|
|
172
|
+
LINK_FIELD_TYPES,
|
|
173
|
+
CHECKBOX_FIELD_TYPES,
|
|
174
|
+
DATE_FIELD_TYPES,
|
|
175
|
+
FIRST_MONTH_DAYS,
|
|
176
|
+
KEEP_REASONS,
|
|
177
|
+
};
|
|
@@ -19,10 +19,30 @@ const Webinars_Leads_ID = runtimeConfig.get('AIRTABLE_WEBINARS_LEADS_ID') || 'ap
|
|
|
19
19
|
const Product_ID = runtimeConfig.get('AIRTABLE_PRODUCT_ID') || 'appu2YDW2pKDYLL5H';
|
|
20
20
|
const Dashboard_ID = runtimeConfig.get('AIRTABLE_DASHBOARD_ID') || 'appg9YUNlfIC82MzR';
|
|
21
21
|
const Estado_General_ID = runtimeConfig.get('AIRTABLE_ESTADO_GENERAL_ID') || 'appXb7LKgAuZ1d1KI';
|
|
22
|
+
const Quimio_Ops_ID = runtimeConfig.get('AIRTABLE_QUIMIO_OPS_ID') || 'appK0VzrMDcVGyuE9';
|
|
23
|
+
|
|
24
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
|
|
25
|
+
|
|
26
|
+
function positiveMsOr(raw, fallback) {
|
|
27
|
+
const parsed = Number(raw);
|
|
28
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function getApiKey() {
|
|
32
|
+
return runtimeConfig.get('AIRTABLE_API_KEY');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function getRequestTimeoutMs() {
|
|
36
|
+
return positiveMsOr(runtimeConfig.get('AIRTABLE_REQUEST_TIMEOUT_MS'), DEFAULT_REQUEST_TIMEOUT_MS);
|
|
37
|
+
}
|
|
22
38
|
|
|
23
39
|
let airtable = null;
|
|
24
40
|
if (airtableConfig.apiKey) {
|
|
25
|
-
airtable = new Airtable({
|
|
41
|
+
airtable = new Airtable({
|
|
42
|
+
apiKey: airtableConfig.apiKey,
|
|
43
|
+
noRetryIfRateLimited: true,
|
|
44
|
+
requestTimeout: getRequestTimeoutMs(),
|
|
45
|
+
});
|
|
26
46
|
}
|
|
27
47
|
|
|
28
48
|
const BASE_MAP = {
|
|
@@ -44,6 +64,8 @@ const BASE_MAP = {
|
|
|
44
64
|
module.exports = {
|
|
45
65
|
airtable,
|
|
46
66
|
config: airtableConfig,
|
|
67
|
+
getApiKey,
|
|
68
|
+
getRequestTimeoutMs,
|
|
47
69
|
Calendar_ID,
|
|
48
70
|
Config_ID,
|
|
49
71
|
Historial_Clinico_ID,
|
|
@@ -57,6 +79,7 @@ module.exports = {
|
|
|
57
79
|
Product_ID,
|
|
58
80
|
Dashboard_ID,
|
|
59
81
|
Estado_General_ID,
|
|
82
|
+
Quimio_Ops_ID,
|
|
60
83
|
getBase: (baseKeyOrId = runtimeConfig.get('AIRTABLE_BASE_ID')) => {
|
|
61
84
|
if (!airtable) {
|
|
62
85
|
throw new Error('Airtable not configured. Please set AIRTABLE_API_KEY environment variable.');
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
|
|
2
|
+
const DEFAULT_INSTRUCTION_SETTLE_MS = 2500;
|
|
3
|
+
const DUPLICATE_INSTRUCTION_WINDOW_MS = 60 * 60 * 1000;
|
|
4
|
+
|
|
5
|
+
module.exports = { PENDING_INSTRUCTION_WINDOW_MS, DEFAULT_INSTRUCTION_SETTLE_MS, DUPLICATE_INSTRUCTION_WINDOW_MS };
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -1,19 +1,54 @@
|
|
|
1
1
|
const { _resetOverrides } = require('../config/runtimeConfig');
|
|
2
2
|
const { _resetMetaConfig } = require('../config/metaConfig');
|
|
3
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
4
|
+
const { logger } = require('../utils/logger');
|
|
3
5
|
const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
|
|
4
6
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
7
|
+
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
8
|
+
const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
|
|
9
|
+
const { stopReviewDraftSweep } = require('../services/reviewDraftSweepService');
|
|
10
|
+
const { stopReviewAlertSweep } = require('../services/reviewAlertSweepService');
|
|
11
|
+
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
5
12
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
13
|
+
const { stopPatientProfileSync } = require('../clinical/services/patientProfileService');
|
|
14
|
+
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
15
|
+
const { _resetSafetyNetState } = require('../clinical/services/pausedSafetyNetService');
|
|
16
|
+
const { stopSafetyNetSweep } = require('../clinical/services/safetyNetPledgeService');
|
|
17
|
+
const { stopRecommendationRecoverySweep } = require('../clinical/services/recommendationRecoveryService');
|
|
18
|
+
const { _clearRecentIntakeCache } = require('../clinical/services/clinicalAirtableService');
|
|
19
|
+
const { _clearExtractorConfigCache } = require('../clinical/services/clinicalExtractionService');
|
|
6
20
|
const { _resetRegistry } = require('../clinical/services/assistantResolver');
|
|
7
21
|
const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
8
22
|
|
|
23
|
+
const SWEEP_STOP_MS = 2000;
|
|
24
|
+
|
|
25
|
+
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
26
|
+
const stopped = Promise.allSettled([
|
|
27
|
+
stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(), stopReviewAlertSweep(),
|
|
28
|
+
stopPatientProfileSync(),
|
|
29
|
+
]);
|
|
30
|
+
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
31
|
+
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
32
|
+
}
|
|
33
|
+
|
|
9
34
|
function resetAll() {
|
|
35
|
+
const sweepsStopped = stopAllSweeps();
|
|
36
|
+
|
|
10
37
|
_resetDefaultInstance();
|
|
11
38
|
_resetRegistry();
|
|
12
39
|
_resetLLMState();
|
|
13
40
|
setPreprocessingHandler(null);
|
|
41
|
+
clearInteractiveRoutes();
|
|
42
|
+
_resetSafetyNetConfig();
|
|
43
|
+
_resetSafetyNetState();
|
|
14
44
|
_resetOverrides();
|
|
15
45
|
_resetMetaConfig();
|
|
16
46
|
_clearClinicalContextCache();
|
|
47
|
+
_clearRecentIntakeCache();
|
|
48
|
+
_clearExtractorConfigCache();
|
|
49
|
+
clearTriageHistoryCache();
|
|
50
|
+
|
|
51
|
+
return sweepsStopped;
|
|
17
52
|
}
|
|
18
53
|
|
|
19
|
-
module.exports = { resetAll };
|
|
54
|
+
module.exports = { resetAll, stopAllSweeps, SWEEP_STOP_MS };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const runtimeConfig = require('./runtimeConfig');
|
|
2
|
+
|
|
3
|
+
// Symptoms/Monitoreo use `programa AMI`; Config uses `programa_AMI`.
|
|
4
|
+
const DEFAULT_PROGRAM_SOURCE = 'auna';
|
|
5
|
+
|
|
6
|
+
const programSource = () => runtimeConfig.get('PROGRAM_SOURCE') || DEFAULT_PROGRAM_SOURCE;
|
|
7
|
+
|
|
8
|
+
const programConfigSource = () => runtimeConfig.get('PROGRAM_CONFIG_SOURCE') || DEFAULT_PROGRAM_SOURCE;
|
|
9
|
+
|
|
10
|
+
function configureProgram({ source, configSource } = {}) {
|
|
11
|
+
if (source) runtimeConfig.set('PROGRAM_SOURCE', String(source));
|
|
12
|
+
if (configSource) runtimeConfig.set('PROGRAM_CONFIG_SOURCE', String(configSource));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
DEFAULT_PROGRAM_SOURCE,
|
|
17
|
+
configureProgram,
|
|
18
|
+
programConfigSource,
|
|
19
|
+
programSource,
|
|
20
|
+
};
|
|
@@ -1,21 +1,31 @@
|
|
|
1
1
|
const { Config_ID } = require('../config/airtableConfig');
|
|
2
2
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
3
|
+
const { DUPLICATE_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig');
|
|
3
4
|
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
6
|
+
const { isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
7
|
+
const { AssistantMessageError, injectAssistantMessages } = require('../services/assistantMessageService');
|
|
5
8
|
|
|
6
|
-
const { getThreadInfo, switchThreadStoppedStatus } = require('../
|
|
9
|
+
const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
|
|
7
10
|
|
|
8
11
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
9
|
-
const { sendMessage, processInstruction, processSystemMessage } = require('../core/NexusMessaging');
|
|
12
|
+
const { sendMessage, processInstruction, processSystemMessage, processCheckInDue, isDraining } = require('../core/NexusMessaging');
|
|
13
|
+
const { CHECK_IN_TYPES } = require('../clinical/config/checkInConfig');
|
|
10
14
|
const { createAssistant, switchAssistant } = require('../clinical');
|
|
15
|
+
const { cancelPendingFollowUps } = require('../clinical/services/clinicalAirtableService');
|
|
16
|
+
|
|
17
|
+
const asBoolean = (value) => (typeof value === 'string' ? value === 'true' : !!value);
|
|
11
18
|
|
|
12
19
|
const stopAssistantController = async (req, res) => {
|
|
13
20
|
const { code, stop } = req.body;
|
|
14
21
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
15
22
|
|
|
16
|
-
const stopped =
|
|
23
|
+
const stopped = asBoolean(stop);
|
|
17
24
|
try {
|
|
18
|
-
await switchThreadStoppedStatus(code, stopped);
|
|
25
|
+
await switchThreadStoppedStatus(code, stopped, { byOperator: true });
|
|
26
|
+
if (stopped && !(await cancelPendingFollowUps({ code, reason: 'thread_paused' }))) {
|
|
27
|
+
logger.error('[AssistantController] Pending follow-ups were not stood down on pause', { code });
|
|
28
|
+
}
|
|
19
29
|
return res.status(200).json({ success: true, message: stopped ? 'Assistant stopped' : 'Assistant resumed' });
|
|
20
30
|
} catch (error) {
|
|
21
31
|
logger.error('[AssistantController] Failed to stop assistant', { error: error.message, code });
|
|
@@ -23,12 +33,41 @@ const stopAssistantController = async (req, res) => {
|
|
|
23
33
|
}
|
|
24
34
|
};
|
|
25
35
|
|
|
36
|
+
const observedSilence = (through) => {
|
|
37
|
+
if (through === undefined || through === null || through === '') return null;
|
|
38
|
+
const at = new Date(through);
|
|
39
|
+
if (Number.isNaN(at.getTime()) || at.getTime() > Date.now()) return undefined;
|
|
40
|
+
return at;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const doNotAlertController = async (req, res) => {
|
|
44
|
+
const { code, doNotAlert, through } = req.body;
|
|
45
|
+
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
46
|
+
|
|
47
|
+
const observed = observedSilence(through);
|
|
48
|
+
if (observed === undefined) return res.status(400).json({ success: false, error: 'through must be a past timestamp' });
|
|
49
|
+
|
|
50
|
+
const muted = asBoolean(doNotAlert);
|
|
51
|
+
try {
|
|
52
|
+
const result = await setThreadDoNotAlert(code, muted, observed);
|
|
53
|
+
if (!result.matchedCount) return res.status(404).json({ success: false, error: 'No conversation with that code' });
|
|
54
|
+
logger.info('[AssistantController] Alerts for a contact were switched', { code, doNotAlert: muted, through: observed });
|
|
55
|
+
return res.status(200).json({ success: true, message: muted ? 'Alerts muted for this contact' : 'Alerts restored for this contact' });
|
|
56
|
+
} catch (error) {
|
|
57
|
+
logger.error('[AssistantController] Failed to switch alerts for a contact', { error: error.message, code });
|
|
58
|
+
return res.status(500).json({ success: false, error: 'Failed to switch alerts for this contact' });
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
26
62
|
const addInsAssistantController = async (req, res) => {
|
|
27
63
|
const { code, instruction, triggeredBy } = req.body;
|
|
28
64
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
29
65
|
|
|
30
66
|
try {
|
|
31
|
-
await processInstruction(code, instruction, 'developer', { triggeredBy });
|
|
67
|
+
const result = await processInstruction(code, instruction, 'developer', { triggeredBy, dedupeWithinMs: DUPLICATE_INSTRUCTION_WINDOW_MS });
|
|
68
|
+
if (result?.outcome === 'duplicate') {
|
|
69
|
+
return res.status(200).json({ success: true, duplicate: true, message: 'Instruction already answered' });
|
|
70
|
+
}
|
|
32
71
|
return res.status(200).json({ success: true, message: 'Instruction added to assistant' });
|
|
33
72
|
} catch (error) {
|
|
34
73
|
logger.error('[AssistantController] Add instruction error', { error: error.message, code });
|
|
@@ -36,16 +75,27 @@ const addInsAssistantController = async (req, res) => {
|
|
|
36
75
|
}
|
|
37
76
|
};
|
|
38
77
|
|
|
39
|
-
const
|
|
40
|
-
const { code,
|
|
41
|
-
if (!code) return res.status(400).json({ success: false, error: '
|
|
78
|
+
const checkInDueController = async (req, res) => {
|
|
79
|
+
const { code, reminder_id: reminderId, type, description, first_name: firstName } = req.body || {};
|
|
80
|
+
if (!code || !reminderId) return res.status(400).json({ success: false, error: 'code and reminder_id are required' });
|
|
81
|
+
if (!CHECK_IN_TYPES.includes(type)) return res.status(400).json({ success: false, error: `type must be one of ${CHECK_IN_TYPES.join(' | ')}` });
|
|
82
|
+
if (isDraining()) return res.status(503).json({ success: false, error: 'draining' });
|
|
42
83
|
|
|
84
|
+
processCheckInDue(code, { reminderId, type, question: description || '', firstName: firstName || null })
|
|
85
|
+
.then((result) => logger.info('[AssistantController] Check-in settled', { code, reminderId, ...result }))
|
|
86
|
+
.catch((error) => logger.error('[AssistantController] Check-in failed', { error: error.message, code, reminderId }));
|
|
87
|
+
return res.status(202).json({ success: true, accepted: true });
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const addMsgAssistantController = async (req, res) => {
|
|
43
91
|
try {
|
|
44
|
-
await
|
|
92
|
+
await injectAssistantMessages(req.body, processSystemMessage);
|
|
45
93
|
return res.status(200).json({ success: true, message: 'Message added to assistant' });
|
|
46
94
|
} catch (error) {
|
|
47
|
-
|
|
48
|
-
|
|
95
|
+
const failure = error instanceof AssistantMessageError ? error : new AssistantMessageError('MESSAGE_INJECTION_FAILED');
|
|
96
|
+
const { reasonCode, acceptedCount, statusCode } = failure;
|
|
97
|
+
logger.error('[AssistantController] Add message error', { reasonCode, acceptedCount });
|
|
98
|
+
return res.status(statusCode).json({ success: false, error: failure.message, reasonCode, acceptedCount });
|
|
49
99
|
}
|
|
50
100
|
};
|
|
51
101
|
|
|
@@ -57,6 +107,10 @@ const createAssistantController = async (req, res) => {
|
|
|
57
107
|
|
|
58
108
|
try {
|
|
59
109
|
for (const code of codes) {
|
|
110
|
+
if (isArchivedPatientCode(code)) {
|
|
111
|
+
logger.warn('[AssistantController] Skipped an archived patient code', { code });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
60
114
|
await createAssistant(code, assistant_id, [...instrucciones, ...messages], force);
|
|
61
115
|
for (const message of messages) {
|
|
62
116
|
await sendMessage({ code, body: message, fileType: 'text' });
|
|
@@ -111,8 +165,10 @@ const switchAssistantController = async (req, res) => {
|
|
|
111
165
|
|
|
112
166
|
module.exports = {
|
|
113
167
|
addInsAssistantController,
|
|
168
|
+
checkInDueController,
|
|
114
169
|
addMsgAssistantController,
|
|
115
170
|
createAssistantController,
|
|
171
|
+
doNotAlertController,
|
|
116
172
|
getInfoAssistantController,
|
|
117
173
|
listAssistantController,
|
|
118
174
|
switchAssistantController,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { syncContextFacts } = require('../clinical/services/contextSyncService');
|
|
3
|
+
|
|
4
|
+
const CLIENT_ERROR_REASONS = new Set([
|
|
5
|
+
'limit-requires-dry-run', 'patient-scope-required', 'patient-scope-must-be-a-function',
|
|
6
|
+
'patient-scope-must-return-boolean',
|
|
7
|
+
]);
|
|
8
|
+
|
|
9
|
+
const contextSyncController = async (req, res) => {
|
|
10
|
+
const { dry_run: dryRun = false, limit = null } = req.body || {};
|
|
11
|
+
if (typeof dryRun !== 'boolean') {
|
|
12
|
+
return res.status(400).json({ success: false, error: 'dry_run must be a boolean when provided' });
|
|
13
|
+
}
|
|
14
|
+
if (limit != null && (!Number.isInteger(limit) || limit < 1)) {
|
|
15
|
+
return res.status(400).json({ success: false, error: 'limit must be a positive integer when provided' });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
const { ok, ...detail } = await syncContextFacts({ dryRun, limit: limit ?? Infinity });
|
|
20
|
+
if (ok) return res.status(200).json({ success: true, ...detail });
|
|
21
|
+
return res.status(CLIENT_ERROR_REASONS.has(detail.reason) ? 400 : 502).json({ success: false, ...detail });
|
|
22
|
+
} catch (error) {
|
|
23
|
+
logger.error('[ContextSyncController] sync error', { error: error.message });
|
|
24
|
+
return res.status(500).json({ success: false, error: 'Failed to sync context facts' });
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
module.exports = {
|
|
29
|
+
contextSyncController,
|
|
30
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { applyContingencyEvent } = require('../clinical/services/contingencyDispatchService');
|
|
3
|
+
|
|
4
|
+
const STAGES = ['patient', 'team'];
|
|
5
|
+
const EVENTS = ['fired', 'expired'];
|
|
6
|
+
|
|
7
|
+
const contingencyEventController = async (req, res) => {
|
|
8
|
+
const { code, plan_id: planId, stage, event, at = null } = req.body || {};
|
|
9
|
+
if (!code) return res.status(400).json({ success: false, error: 'code is required' });
|
|
10
|
+
if (!planId) return res.status(400).json({ success: false, error: 'plan_id is required' });
|
|
11
|
+
if (!STAGES.includes(stage)) return res.status(400).json({ success: false, error: `stage must be one of ${STAGES.join(' | ')}` });
|
|
12
|
+
if (!EVENTS.includes(event)) return res.status(400).json({ success: false, error: `event must be one of ${EVENTS.join(' | ')}` });
|
|
13
|
+
if (at != null && (typeof at !== 'string' || Number.isNaN(new Date(at).getTime()))) {
|
|
14
|
+
return res.status(400).json({ success: false, error: 'at must be an ISO 8601 datetime when provided' });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const result = await applyContingencyEvent({ patientCode: code, planId, stage, event, at });
|
|
19
|
+
return res.status(200).json({ success: true, ...result });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
logger.error('[ContingencyController] event error', { error: error.message, code, planId, stage, event });
|
|
22
|
+
return res.status(500).json({ success: false, error: 'Failed to apply contingency event' });
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
module.exports = {
|
|
27
|
+
contingencyEventController,
|
|
28
|
+
};
|
|
@@ -34,7 +34,7 @@ const getConversationController = async (req, res) => {
|
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const { threads, total, airtableNameMap } = await fetchConversationData(filter, skip, limit);
|
|
37
|
+
const { threads, total, airtableNameMap, openTaskMap, reviewMap } = await fetchConversationData(filter, skip, limit);
|
|
38
38
|
|
|
39
39
|
if (!threads?.length) {
|
|
40
40
|
return res.status(200).json({
|
|
@@ -44,7 +44,7 @@ const getConversationController = async (req, res) => {
|
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
const processedConversations = await processConversations(threads, airtableNameMap);
|
|
47
|
+
const processedConversations = await processConversations(threads, airtableNameMap, openTaskMap, reviewMap);
|
|
48
48
|
const totalPages = Math.ceil(total / limit);
|
|
49
49
|
|
|
50
50
|
res.status(200).json({
|
|
@@ -91,7 +91,7 @@ const getConversationMessagesController = async (req, res) => {
|
|
|
91
91
|
|
|
92
92
|
const total = await countMessages(query);
|
|
93
93
|
const messages = await getMessages(query, { sort: { createdAt: -1 }, skip, limit });
|
|
94
|
-
messages.forEach(msg => { msg.body = msg.plainBody
|
|
94
|
+
messages.forEach(msg => { msg.body = msg.plainBody; });
|
|
95
95
|
const orderedMessages = await attachShadowReplies(messages.reverse(), code);
|
|
96
96
|
const totalPages = Math.ceil(total / limit);
|
|
97
97
|
|
|
@@ -135,7 +135,7 @@ const getConversationReplyController = async (req, res) => {
|
|
|
135
135
|
const messageData = {
|
|
136
136
|
code,
|
|
137
137
|
fileType: 'text',
|
|
138
|
-
|
|
138
|
+
processed: true,
|
|
139
139
|
triggeredBy: triggeredBy || null
|
|
140
140
|
};
|
|
141
141
|
|
|
@@ -408,7 +408,7 @@ const getNewMessagesController = async (req, res) => {
|
|
|
408
408
|
const raw = parseInt(req.query.limit, 10);
|
|
409
409
|
const clampedLimit = Number.isFinite(raw) ? Math.min(Math.max(raw, 1), 100) : 20;
|
|
410
410
|
const messages = await getMessages(query, { sort: { createdAt: 1 }, limit: clampedLimit });
|
|
411
|
-
messages.forEach(msg => { msg.body = msg.plainBody
|
|
411
|
+
messages.forEach(msg => { msg.body = msg.plainBody; });
|
|
412
412
|
|
|
413
413
|
res.status(200).json({
|
|
414
414
|
success: true,
|
|
@@ -494,7 +494,7 @@ const getOpenAIThreadMessagesController = async (req, res) => {
|
|
|
494
494
|
{ numero: code, group_id: null },
|
|
495
495
|
{ sort: { createdAt: order === 'asc' ? 1 : -1 }, limit: parsedLimit }
|
|
496
496
|
);
|
|
497
|
-
messages.forEach(msg => { msg.body = msg.plainBody
|
|
497
|
+
messages.forEach(msg => { msg.body = msg.plainBody; });
|
|
498
498
|
|
|
499
499
|
res.status(200).json({
|
|
500
500
|
success: true,
|
|
@@ -553,7 +553,7 @@ const searchMessagesByNumberController = async (req, res) => {
|
|
|
553
553
|
|
|
554
554
|
const total = await countMessages(mongoQuery);
|
|
555
555
|
const messages = await getMessages(mongoQuery, { sort: mongoSort, skip, limit });
|
|
556
|
-
messages.forEach(msg => { msg.body = msg.plainBody
|
|
556
|
+
messages.forEach(msg => { msg.body = msg.plainBody; });
|
|
557
557
|
const totalPages = Math.ceil(total / limit);
|
|
558
558
|
|
|
559
559
|
res.status(200).json({
|
|
@@ -8,9 +8,10 @@ const { getAllBoxes, getStatsById, updateBox, getDailyTrend } = require('../serv
|
|
|
8
8
|
const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
|
|
9
9
|
|
|
10
10
|
const getDashboardController = async (req, res) => {
|
|
11
|
+
res.set('Cache-Control', 'private, no-store');
|
|
11
12
|
try {
|
|
12
|
-
const
|
|
13
|
-
const boxes = await getAllBoxes(
|
|
13
|
+
const shouldForce = req.query.force === 'true';
|
|
14
|
+
const boxes = await getAllBoxes(shouldForce);
|
|
14
15
|
res.json({ success: true, boxes });
|
|
15
16
|
} catch (error) {
|
|
16
17
|
logger.error('[DashboardController] Error fetching dashboards:', { error: error.message });
|
|
@@ -19,6 +20,7 @@ const getDashboardController = async (req, res) => {
|
|
|
19
20
|
};
|
|
20
21
|
|
|
21
22
|
const getDashboardStatsControllerById = async (req, res) => {
|
|
23
|
+
res.set('Cache-Control', 'private, no-store');
|
|
22
24
|
try {
|
|
23
25
|
const { id } = req.params;
|
|
24
26
|
const { type } = req.query;
|
|
@@ -43,16 +45,17 @@ const updateDashboardControllerById = async (req, res) => {
|
|
|
43
45
|
return res.status(400).json({ success: false, error });
|
|
44
46
|
}
|
|
45
47
|
|
|
46
|
-
res.json({ success: true, message: 'Box updated', id: box.id });
|
|
47
|
-
|
|
48
48
|
const updatedBox = await updateBox(box.id, box);
|
|
49
49
|
|
|
50
|
+
res.json({ success: true, message: 'Box updated', id: box.id });
|
|
51
|
+
|
|
50
52
|
safeEmit(getStatusEventBus(), 'dashboard:updated', createEvent('dashboard:updated', {
|
|
51
53
|
...updatedBox
|
|
52
54
|
}));
|
|
53
55
|
|
|
54
56
|
} catch (error) {
|
|
55
57
|
logger.error('[DashboardController] Error updating dashboard:', { error: error.message, id: req.params?.id });
|
|
58
|
+
if (!res.headersSent) res.status(500).json({ success: false, error: error.message || 'Failed to update dashboard' });
|
|
56
59
|
}
|
|
57
60
|
};
|
|
58
61
|
|