@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,217 @@
|
|
|
1
|
+
const { isoDay, daysSince } = require('../../utils/dateUtils');
|
|
2
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
3
|
+
|
|
4
|
+
const MAX_RELEVANT_RISKS = 4;
|
|
5
|
+
const MAX_CHECKS = 8;
|
|
6
|
+
const MAX_ESCALATIONS = 5;
|
|
7
|
+
const ESCALATION_LOOKBACK_DAYS = 14;
|
|
8
|
+
|
|
9
|
+
const SEVERITY_RANK = { emergency: 3, safety_relevant: 2, moderate: 1 };
|
|
10
|
+
|
|
11
|
+
const NOT_REPORTED_NOTE = 'El paciente no reportó ningún síntoma actual en este turno. Todo lo que aparezca en el perfil de riesgo son eventos PREVISTOS del tratamiento, no síntomas reportados: nunca afirmes que el paciente los reportó ni le atribuyas un grado.';
|
|
12
|
+
|
|
13
|
+
const emptyBrief = (escalations, teamCases) => ({
|
|
14
|
+
current_concerns: [],
|
|
15
|
+
symptom_history: [],
|
|
16
|
+
recent_escalations: escalations,
|
|
17
|
+
team_cases: teamCases,
|
|
18
|
+
relevant_risks: [],
|
|
19
|
+
checks_now: [],
|
|
20
|
+
selection: 'no_current_concerns',
|
|
21
|
+
note: NOT_REPORTED_NOTE,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const inline = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
25
|
+
const fold = (value) => foldAccents(inline(value).toLowerCase());
|
|
26
|
+
const dedupe = (values) => [...new Set(values.map(inline))].filter(Boolean);
|
|
27
|
+
|
|
28
|
+
function tokens(value) {
|
|
29
|
+
const text = fold(value);
|
|
30
|
+
return new Set(text.split(/[^a-z0-9]+/).filter((token) => token.length > 2));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const canonicalTerm = (value) => fold(value).replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
|
|
34
|
+
|
|
35
|
+
function intersects(left, right) {
|
|
36
|
+
for (const item of left) if (right.has(item)) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function currentConcerns(clinicalMentions = []) {
|
|
41
|
+
return clinicalMentions
|
|
42
|
+
.filter((mention) => mention?.fact?.category === 'symptom')
|
|
43
|
+
.filter((mention) => mention.fact?.assertion?.negated !== true)
|
|
44
|
+
// 'past' is not a member of the temporal enum: the old guard admitted every historical mention.
|
|
45
|
+
.filter((mention) => (mention.fact?.assertion?.temporal ?? 'current') === 'current')
|
|
46
|
+
.filter((mention) => (mention.fact?.assertion?.experiencer ?? 'patient') === 'patient')
|
|
47
|
+
.map((mention) => ({
|
|
48
|
+
display: inline(mention.fact?.canonicalTerm || mention.fact?.ctcaeTerm),
|
|
49
|
+
ctcaeTerm: canonicalTerm(mention.fact?.ctcaeTerm),
|
|
50
|
+
}))
|
|
51
|
+
.filter((concern) => concern.display)
|
|
52
|
+
.filter((concern, index, all) => all.findIndex((item) => item.display === concern.display) === index);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function riskCandidates(profile) {
|
|
56
|
+
const predicted = (profile?.predicted_aes || []).map((risk) => ({
|
|
57
|
+
source: 'predicted_ae',
|
|
58
|
+
concern: inline(risk.ae_name),
|
|
59
|
+
severity_if_confirmed: risk.severity_if_confirmed || null,
|
|
60
|
+
why: inline(risk.why) || null,
|
|
61
|
+
warning_signs: dedupe(risk.minimum_symptom_set || []),
|
|
62
|
+
related_symptom_terms: dedupe(risk.related_symptom_terms || []).map(canonicalTerm),
|
|
63
|
+
}));
|
|
64
|
+
const disease = (profile?.disease_risks || []).map((risk) => ({
|
|
65
|
+
source: 'disease_risk',
|
|
66
|
+
concern: dedupe([risk.body_site, ...(risk.complications || [])]).join(': '),
|
|
67
|
+
severity_if_confirmed: null,
|
|
68
|
+
why: null,
|
|
69
|
+
warning_signs: dedupe(risk.warning_symptoms || []),
|
|
70
|
+
related_symptom_terms: dedupe(risk.related_symptom_terms || []).map(canonicalTerm),
|
|
71
|
+
}));
|
|
72
|
+
const amplifiers = (profile?.comorbidity_amplifiers || []).map((risk) => ({
|
|
73
|
+
source: 'comorbidity_amplifier',
|
|
74
|
+
concern: inline(risk.comorbidity),
|
|
75
|
+
severity_if_confirmed: null,
|
|
76
|
+
why: dedupe([risk.interaction, risk.clinical_note]).join('; ') || null,
|
|
77
|
+
warning_signs: [],
|
|
78
|
+
related_symptom_terms: [],
|
|
79
|
+
}));
|
|
80
|
+
return [...predicted, ...disease, ...amplifiers].filter((risk) => risk.concern);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function checksFor(risk) {
|
|
84
|
+
const checks = [...risk.warning_signs];
|
|
85
|
+
if (risk.related_symptom_terms.includes('fever')) {
|
|
86
|
+
checks.push('temperatura actual o reciente');
|
|
87
|
+
}
|
|
88
|
+
return dedupe(checks);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function escalationsFor(escalations, now) {
|
|
92
|
+
if (!Array.isArray(escalations)) return [];
|
|
93
|
+
return escalations.slice(0, MAX_ESCALATIONS).map((event) => ({
|
|
94
|
+
escalated_at: isoDay(event.escalatedAt),
|
|
95
|
+
days_since: daysSince(event.escalatedAt, now),
|
|
96
|
+
urgency: event.urgency,
|
|
97
|
+
reason: inline(event.reason) || null,
|
|
98
|
+
channels: event.channels,
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Every case the team still holds, and those it closed within the escalation window.
|
|
103
|
+
function teamCasesFor(escalationCases, now) {
|
|
104
|
+
if (!Array.isArray(escalationCases)) return [];
|
|
105
|
+
const since = escalationLookbackSince(now);
|
|
106
|
+
return escalationCases
|
|
107
|
+
.filter((escalationCase) => escalationCase.isOpen || Date.parse(escalationCase.closedAt ?? escalationCase.lastModified) >= since)
|
|
108
|
+
.slice(0, MAX_ESCALATIONS)
|
|
109
|
+
.map((escalationCase) => ({
|
|
110
|
+
status: escalationCase.label,
|
|
111
|
+
is_open: escalationCase.isOpen,
|
|
112
|
+
level: escalationCase.priority,
|
|
113
|
+
opened_at: isoDay(escalationCase.openedAt),
|
|
114
|
+
days_since: daysSince(escalationCase.openedAt, now),
|
|
115
|
+
doctor_decision: escalationCase.decision,
|
|
116
|
+
case_ids: escalationCase.conditionIds,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const graded = (assessment) => Number.isInteger(assessment?.grade?.bestEstimate);
|
|
121
|
+
const at = (assessment) => Date.parse(assessment?.performedAt) || 0;
|
|
122
|
+
|
|
123
|
+
function historyFor(concerns, symptomCases, now) {
|
|
124
|
+
const wanted = new Map(concerns.filter((c) => c.ctcaeTerm).map((c) => [c.ctcaeTerm, c.display]));
|
|
125
|
+
if (!wanted.size || !Array.isArray(symptomCases)) return [];
|
|
126
|
+
|
|
127
|
+
const chains = new Map();
|
|
128
|
+
for (const managed of symptomCases) {
|
|
129
|
+
const term = canonicalTerm(managed?.condition?.ctcaeTerm);
|
|
130
|
+
if (!wanted.has(term)) continue;
|
|
131
|
+
const graded_ = [managed.latestAssessment, ...(managed.priorAssessments || [])].filter(graded);
|
|
132
|
+
if (graded_.length) chains.set(term, [...(chains.get(term) || []), ...graded_]);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return [...chains].map(([term, chain]) => {
|
|
136
|
+
chain.sort((a, b) => at(b) - at(a));
|
|
137
|
+
const latest = chain[0];
|
|
138
|
+
const worst = chain.reduce((a, b) => (b.grade.bestEstimate > a.grade.bestEstimate ? b : a));
|
|
139
|
+
return {
|
|
140
|
+
symptom: term,
|
|
141
|
+
reported_as: wanted.get(term),
|
|
142
|
+
last_grade: latest.grade.bestEstimate,
|
|
143
|
+
last_reported_at: isoDay(latest.performedAt),
|
|
144
|
+
days_since_last_report: daysSince(latest.performedAt, now),
|
|
145
|
+
worst_grade: worst.grade.bestEstimate,
|
|
146
|
+
worst_reported_at: isoDay(worst.performedAt),
|
|
147
|
+
at_personal_worst: worst.grade.bestEstimate > 0 && latest.grade.bestEstimate >= worst.grade.bestEstimate,
|
|
148
|
+
assessments_on_record: chain.length,
|
|
149
|
+
};
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [], escalations = [], escalationCases = [], now = Date.now() } = {}) {
|
|
154
|
+
const recentEscalations = escalationsFor(escalations, now);
|
|
155
|
+
const teamCases = teamCasesFor(escalationCases, now);
|
|
156
|
+
const concerns = currentConcerns(clinicalMentions);
|
|
157
|
+
if (!concerns.length) return emptyBrief(recentEscalations, teamCases);
|
|
158
|
+
|
|
159
|
+
const candidates = riskCandidates(profile).map((risk, index) => {
|
|
160
|
+
const riskTokens = tokens([risk.concern, risk.why, ...risk.warning_signs].join(' '));
|
|
161
|
+
const appliesTo = concerns
|
|
162
|
+
.filter((concern) => (concern.ctcaeTerm && risk.related_symptom_terms.includes(concern.ctcaeTerm))
|
|
163
|
+
|| ((!concern.ctcaeTerm || !risk.related_symptom_terms.length)
|
|
164
|
+
&& intersects(tokens(concern.display), riskTokens)))
|
|
165
|
+
.map((concern) => concern.display);
|
|
166
|
+
return { ...risk, applies_to: appliesTo, index };
|
|
167
|
+
});
|
|
168
|
+
let selected = candidates.filter((risk) => risk.applies_to.length > 0);
|
|
169
|
+
let usedFallback = false;
|
|
170
|
+
let addedPriorityFallback = false;
|
|
171
|
+
if (!selected.length) {
|
|
172
|
+
const fallback = [...candidates]
|
|
173
|
+
.sort((a, b) => (SEVERITY_RANK[b.severity_if_confirmed] || 0) - (SEVERITY_RANK[a.severity_if_confirmed] || 0) || a.index - b.index)[0];
|
|
174
|
+
selected = fallback ? [{ ...fallback, applies_to: [] }] : [];
|
|
175
|
+
usedFallback = selected.length > 0;
|
|
176
|
+
} else if (!selected.some((risk) => risk.severity_if_confirmed === 'emergency')) {
|
|
177
|
+
const priorityFallback = candidates.find((risk) => risk.severity_if_confirmed === 'emergency');
|
|
178
|
+
if (priorityFallback) {
|
|
179
|
+
selected.push({ ...priorityFallback, applies_to: [] });
|
|
180
|
+
addedPriorityFallback = true;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
selected = selected
|
|
184
|
+
.sort((a, b) => b.applies_to.length - a.applies_to.length
|
|
185
|
+
|| (SEVERITY_RANK[b.severity_if_confirmed] || 0) - (SEVERITY_RANK[a.severity_if_confirmed] || 0)
|
|
186
|
+
|| a.index - b.index)
|
|
187
|
+
.slice(0, MAX_RELEVANT_RISKS)
|
|
188
|
+
.map((risk) => ({
|
|
189
|
+
source: risk.source,
|
|
190
|
+
concern: risk.concern,
|
|
191
|
+
severity_if_confirmed: risk.severity_if_confirmed,
|
|
192
|
+
why: risk.why,
|
|
193
|
+
applies_to: risk.applies_to,
|
|
194
|
+
checks_now: checksFor(risk),
|
|
195
|
+
escalation_threshold: risk.severity_if_confirmed
|
|
196
|
+
? { if_confirmed: risk.severity_if_confirmed, warning_signs: risk.warning_signs }
|
|
197
|
+
: { if_warning_signs_present: 'clinical_review', warning_signs: risk.warning_signs },
|
|
198
|
+
}));
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
current_concerns: concerns.map((concern) => concern.display),
|
|
202
|
+
symptom_history: historyFor(concerns, symptomCases, now),
|
|
203
|
+
recent_escalations: recentEscalations,
|
|
204
|
+
team_cases: teamCases,
|
|
205
|
+
relevant_risks: selected,
|
|
206
|
+
checks_now: dedupe(selected.flatMap((risk) => risk.checks_now)).slice(0, MAX_CHECKS),
|
|
207
|
+
selection: !candidates.length
|
|
208
|
+
? 'no_profile_risk_available'
|
|
209
|
+
: usedFallback
|
|
210
|
+
? 'highest_severity_profile_fallback'
|
|
211
|
+
: addedPriorityFallback ? 'matched_with_emergency_profile_fallback' : 'matched_to_current_concerns',
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const escalationLookbackSince = (now = Date.now()) => now - ESCALATION_LOOKBACK_DAYS * 86400000;
|
|
216
|
+
|
|
217
|
+
module.exports = { buildTurnRiskBrief, escalationLookbackSince };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { WriteClaim } = require('../../models/writeClaimModel');
|
|
4
|
+
const { MapCache } = require('../../utils/MapCache');
|
|
5
|
+
const { logger } = require('../../utils/logger');
|
|
6
|
+
|
|
7
|
+
class WriteClaimStore {
|
|
8
|
+
constructor({ namespace, ttlMs, maxSize = 1000 } = {}) {
|
|
9
|
+
if (!namespace) throw new Error('WriteClaimStore requires a namespace');
|
|
10
|
+
if (!ttlMs) throw new Error('WriteClaimStore requires a ttlMs');
|
|
11
|
+
this.namespace = namespace;
|
|
12
|
+
this.ttlMs = ttlMs;
|
|
13
|
+
this.memory = new MapCache({ maxSize, ttl: ttlMs });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
_key(key) {
|
|
17
|
+
return `${this.namespace}:${key}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
_durable() {
|
|
21
|
+
return mongoose.connection?.readyState === 1;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async get(key) {
|
|
25
|
+
const local = this.memory.get(key);
|
|
26
|
+
if (local !== undefined) return local;
|
|
27
|
+
if (!this._durable()) return undefined;
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const claim = await WriteClaim.findOne({ key: this._key(key), expiresAt: { $gt: new Date() } }).lean();
|
|
31
|
+
if (!claim) return undefined;
|
|
32
|
+
this.memory.set(key, claim.value);
|
|
33
|
+
return claim.value;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
logger.warn('[writeClaimStore] Durable read failed, falling back to memory', {
|
|
36
|
+
namespace: this.namespace, error: error.message,
|
|
37
|
+
});
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async set(key, value) {
|
|
43
|
+
this.memory.set(key, value);
|
|
44
|
+
if (!this._durable()) return;
|
|
45
|
+
try {
|
|
46
|
+
await WriteClaim.updateOne(
|
|
47
|
+
{ key: this._key(key) },
|
|
48
|
+
{ $set: { value, expiresAt: new Date(Date.now() + this.ttlMs) } },
|
|
49
|
+
{ upsert: true },
|
|
50
|
+
);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
logger.warn('[writeClaimStore] Durable write failed, dedupe stays memory-only for this key', {
|
|
53
|
+
namespace: this.namespace, error: error.message,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async acquire(key, value = true) {
|
|
59
|
+
if (this.memory.get(key) !== undefined) return 'taken';
|
|
60
|
+
if (!this._durable()) return 'unavailable';
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
await WriteClaim.create({ key: this._key(key), value, expiresAt: new Date(Date.now() + this.ttlMs) });
|
|
64
|
+
this.memory.set(key, value);
|
|
65
|
+
return 'acquired';
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error?.code === 11000) {
|
|
68
|
+
this.memory.set(key, value);
|
|
69
|
+
return 'taken';
|
|
70
|
+
}
|
|
71
|
+
logger.warn('[writeClaimStore] Claim could not be acquired', { namespace: this.namespace, error: error.message });
|
|
72
|
+
return 'unavailable';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async claimedAtMs(key) {
|
|
77
|
+
if (!this._durable()) return null;
|
|
78
|
+
try {
|
|
79
|
+
const claim = await WriteClaim.findOne({ key: this._key(key) }, { expiresAt: 1 }).lean();
|
|
80
|
+
if (!claim?.expiresAt) return null;
|
|
81
|
+
return new Date(claim.expiresAt).getTime() - this.ttlMs;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
logger.warn('[writeClaimStore] Claim age could not be read', { namespace: this.namespace, error: error.message });
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async has(key) {
|
|
89
|
+
if (!this._durable()) return this.memory.get(key) !== undefined ? true : null;
|
|
90
|
+
try {
|
|
91
|
+
const claim = await WriteClaim.findOne({ key: this._key(key), expiresAt: { $gt: new Date() } }).lean();
|
|
92
|
+
return Boolean(claim);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
logger.warn('[writeClaimStore] Claim presence could not be read', { namespace: this.namespace, error: error.message });
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async countSince(since, { value = undefined } = {}) {
|
|
100
|
+
if (!this._durable()) return null;
|
|
101
|
+
const query = { key: new RegExp(`^${this.namespace}:`), createdAt: { $gte: since } };
|
|
102
|
+
if (value !== undefined) query.value = value;
|
|
103
|
+
try {
|
|
104
|
+
return await WriteClaim.countDocuments(query);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
logger.warn('[writeClaimStore] Claims could not be counted', { namespace: this.namespace, error: error.message });
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async release(key) {
|
|
112
|
+
this.memory.delete(key);
|
|
113
|
+
if (!this._durable()) return;
|
|
114
|
+
try {
|
|
115
|
+
await WriteClaim.deleteOne({ key: this._key(key) });
|
|
116
|
+
} catch (error) {
|
|
117
|
+
logger.warn('[writeClaimStore] Claim could not be released', { namespace: this.namespace, error: error.message });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
clear() {
|
|
122
|
+
this.memory.clear();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = { WriteClaimStore };
|
|
@@ -32,6 +32,26 @@ class CtcaeCatalog {
|
|
|
32
32
|
return grades && Object.keys(grades).length ? grades : null;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
lookupEntry(ctcaeTerm) {
|
|
36
|
+
this._assertLoaded();
|
|
37
|
+
const key = (ctcaeTerm || '').trim().toLowerCase();
|
|
38
|
+
const symptom = key ? this.symptomsByTerm.get(key) : null;
|
|
39
|
+
if (symptom) {
|
|
40
|
+
return {
|
|
41
|
+
entry: {
|
|
42
|
+
ctcae_term: symptom.ctcaeTerm,
|
|
43
|
+
spanish_label: symptom.spanishLabel,
|
|
44
|
+
patient_phrases_validated: symptom.patientPhrasesValidated,
|
|
45
|
+
grades: symptom.grades,
|
|
46
|
+
},
|
|
47
|
+
found: true,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const nearestTerms = [...this.symptomsByTerm.keys()]
|
|
51
|
+
.filter((k) => key && (key.includes(k) || k.includes(key) || k.split('_')[0] === key.split('_')[0]));
|
|
52
|
+
return { entry: {}, found: false, nearest_terms: nearestTerms };
|
|
53
|
+
}
|
|
54
|
+
|
|
35
55
|
_assertLoaded() {
|
|
36
56
|
if (this.symptomsByTerm === null) throw new Error('ctcae catalog not loaded: call initialize() at startup');
|
|
37
57
|
}
|
|
@@ -39,6 +59,7 @@ class CtcaeCatalog {
|
|
|
39
59
|
_parseCuratedSymptom(record) {
|
|
40
60
|
return {
|
|
41
61
|
ctcaeTerm: record.ctcae_term,
|
|
62
|
+
ctcaeV5Term: record.ctcae_v5 || null,
|
|
42
63
|
spanishLabel: record.spanish_label || null,
|
|
43
64
|
patientPhrasesValidated: JSON.parse(record.patient_phrases_validated),
|
|
44
65
|
observedFieldsSchema: JSON.parse(record.observed_fields_schema),
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
const { readSymptomCases, readPatientRiskAssessments } = require('../../fhir');
|
|
2
|
+
const { OPEN_STATUSES, CLOSED_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
3
|
+
|
|
4
|
+
const _CHECKPOINT_KEYWORDS = [
|
|
5
|
+
'pembrolizumab', 'nivolumab', 'atezolizumab', 'durvalumab',
|
|
6
|
+
'ipilimumab', 'cemiplimab', 'avelumab', 'checkpoint',
|
|
7
|
+
];
|
|
8
|
+
|
|
9
|
+
const _CYTOTOXIC_KEYWORDS = [
|
|
10
|
+
'folfox', 'folfiri', 'folfirinox', 'ac-t', 'ac ', 'taxol',
|
|
11
|
+
'paclitaxel', 'doxorub', 'cisplat', 'carboplat', '5-fu',
|
|
12
|
+
'capecitab', 'gemcitab', 'docetax', 'vincrist', 'etop', 'quimio',
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
const _PATTERN_CATALOG = [
|
|
16
|
+
{
|
|
17
|
+
pattern_id: 'pattern-pneumonitis',
|
|
18
|
+
type: 'ae_profile',
|
|
19
|
+
hypothesis_label_suggestion: 'pneumonitis_candidate',
|
|
20
|
+
treatment_context: 'checkpoint_inhibitor',
|
|
21
|
+
key_symptoms: ['cough', 'dyspnea', 'fatigue', 'chest_pain_cardiac'],
|
|
22
|
+
disconfirming_symptoms: [],
|
|
23
|
+
clinical_significance_if_confirmed: 'emergency',
|
|
24
|
+
confidence_would_strengthen_if: [
|
|
25
|
+
'dyspnea reported at any severity',
|
|
26
|
+
'oxygen saturation drops below baseline',
|
|
27
|
+
'cough becomes progressive or productive',
|
|
28
|
+
'chest imaging abnormal',
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
pattern_id: 'pattern-cinv',
|
|
33
|
+
type: 'ae_profile',
|
|
34
|
+
hypothesis_label_suggestion: 'chemotherapy_induced_nausea_vomiting',
|
|
35
|
+
treatment_context: 'cytotoxic_chemo',
|
|
36
|
+
key_symptoms: ['nausea', 'vomiting', 'anorexia'],
|
|
37
|
+
disconfirming_symptoms: [],
|
|
38
|
+
clinical_significance_if_confirmed: 'moderate',
|
|
39
|
+
confidence_would_strengthen_if: [
|
|
40
|
+
'timing within 5 days of chemo cycle',
|
|
41
|
+
'severity moderate or worse',
|
|
42
|
+
'functional impact on oral intake',
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
pattern_id: 'pattern-febrile-syndrome',
|
|
47
|
+
type: 'symptom_syndrome',
|
|
48
|
+
hypothesis_label_suggestion: 'febrile_syndrome_suspected',
|
|
49
|
+
treatment_context: null,
|
|
50
|
+
key_symptoms: ['fever', 'chills'],
|
|
51
|
+
disconfirming_symptoms: [],
|
|
52
|
+
clinical_significance_if_confirmed: 'safety_relevant',
|
|
53
|
+
confidence_would_strengthen_if: [
|
|
54
|
+
'temperature measured ≥38.3°C',
|
|
55
|
+
'patient in neutropenic nadir window',
|
|
56
|
+
'rigors or night sweats reported',
|
|
57
|
+
],
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
pattern_id: 'pattern-neuro-constellation',
|
|
61
|
+
type: 'disease_complication',
|
|
62
|
+
hypothesis_label_suggestion: 'neuro_constellation',
|
|
63
|
+
treatment_context: null,
|
|
64
|
+
key_symptoms: ['headache', 'dizziness'],
|
|
65
|
+
disconfirming_symptoms: [],
|
|
66
|
+
clinical_significance_if_confirmed: 'emergency',
|
|
67
|
+
confidence_would_strengthen_if: [
|
|
68
|
+
'sudden onset or worst-ever headache',
|
|
69
|
+
'focal neurological deficit reported',
|
|
70
|
+
'vision or speech change',
|
|
71
|
+
'history of CNS metastasis',
|
|
72
|
+
],
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
pattern_id: 'pattern-cord-compression',
|
|
76
|
+
type: 'disease_complication',
|
|
77
|
+
hypothesis_label_suggestion: 'cord_compression_suspected',
|
|
78
|
+
treatment_context: null,
|
|
79
|
+
key_symptoms: ['pain', 'peripheral_neuropathy'],
|
|
80
|
+
disconfirming_symptoms: [],
|
|
81
|
+
clinical_significance_if_confirmed: 'emergency',
|
|
82
|
+
confidence_would_strengthen_if: [
|
|
83
|
+
'new back pain with leg weakness',
|
|
84
|
+
'bladder or bowel involvement',
|
|
85
|
+
'history of spine metastasis',
|
|
86
|
+
],
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
pattern_id: 'pattern-pain-insomnia-fatigue',
|
|
90
|
+
type: 'relational_causal',
|
|
91
|
+
hypothesis_label_suggestion: 'pain_insomnia_fatigue_chain',
|
|
92
|
+
treatment_context: null,
|
|
93
|
+
key_symptoms: ['pain', 'insomnia', 'fatigue'],
|
|
94
|
+
disconfirming_symptoms: [],
|
|
95
|
+
clinical_significance_if_confirmed: 'moderate',
|
|
96
|
+
confidence_would_strengthen_if: [
|
|
97
|
+
'temporal sequence confirmed (pain → insomnia → fatigue)',
|
|
98
|
+
'pain interferes with sleep specifically',
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
];
|
|
102
|
+
|
|
103
|
+
const _SCOPES = ['all_active_cases', 'specific_cases', 'include_recent_resolved'];
|
|
104
|
+
|
|
105
|
+
const definition = {
|
|
106
|
+
name: 'analyzeSymptomPatterns',
|
|
107
|
+
description: '**Does:** VALIDATES a clinical pattern you propose against the patient\'s active symptom landscape + treatment context. You pick a `specific_pattern_to_validate` (one of 6 frozen catalog patterns) from your reasoning over the symptoms + regimen + grades; the tool deterministically confirms whether the data matches. Read-only — never writes.\n\n**Required inputs:** `specific_pattern_to_validate` — one of `pattern-pneumonitis`, `pattern-cinv`, `pattern-febrile-syndrome`, `pattern-neuro-constellation`, `pattern-cord-compression`, `pattern-pain-insomnia-fatigue`. Optional `scope` (`all_active_cases` default | `specific_cases` | `include_recent_resolved`); `specific_case_ids` (required only for `scope=specific_cases`).\n\n**Returns:** `pattern_validated` (bool). When validated: `match` (pattern_id, type, hypothesis_label_suggestion, treatment_context, member_case_ids_matching, key_symptoms_present/missing, disconfirming_symptoms, match_strength, confidence). When not: `pattern_id`, `reason`, `key_symptoms_present[]`, `key_symptoms_missing[]`. Requires ≥2 key-symptom overlaps and a compatible treatment context.',
|
|
108
|
+
strict: false,
|
|
109
|
+
parameters: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
properties: {
|
|
112
|
+
specific_pattern_to_validate: {
|
|
113
|
+
type: 'string',
|
|
114
|
+
enum: _PATTERN_CATALOG.map((p) => p.pattern_id),
|
|
115
|
+
description: 'The catalog pattern_id you propose to validate, chosen from your clinical reasoning over the symptom landscape + active regimen + grades.',
|
|
116
|
+
},
|
|
117
|
+
scope: {
|
|
118
|
+
type: 'string',
|
|
119
|
+
enum: _SCOPES,
|
|
120
|
+
description: '`all_active_cases` (default): open cases only. `specific_cases`: only the given `specific_case_ids`. `include_recent_resolved`: open cases + cases closed within the last 7 days.',
|
|
121
|
+
},
|
|
122
|
+
specific_case_ids: {
|
|
123
|
+
type: 'array',
|
|
124
|
+
items: { type: 'string' },
|
|
125
|
+
description: 'The case ids to validate against. Required for scope=specific_cases; must be absent otherwise.',
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
required: ['specific_pattern_to_validate'],
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
function fail(error, data = {}) {
|
|
133
|
+
return JSON.stringify({ success: false, error, data });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function regimenMatchesContext(regimen, context) {
|
|
137
|
+
if (!context) return true;
|
|
138
|
+
if (!regimen) return false;
|
|
139
|
+
const regimenLower = regimen.toLowerCase();
|
|
140
|
+
if (context === 'checkpoint_inhibitor') return _CHECKPOINT_KEYWORDS.some((keyword) => regimenLower.includes(keyword));
|
|
141
|
+
if (context === 'cytotoxic_chemo') return _CYTOTOXIC_KEYWORDS.some((keyword) => regimenLower.includes(keyword));
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function matchPattern(pattern, activeTerms, termToCases, patientRegimen) {
|
|
146
|
+
if (!regimenMatchesContext(patientRegimen, pattern.treatment_context)) return null;
|
|
147
|
+
const keySymptoms = new Set(pattern.key_symptoms || []);
|
|
148
|
+
const present = [...keySymptoms].filter((term) => activeTerms.has(term)).sort();
|
|
149
|
+
if (present.length < 2) return null;
|
|
150
|
+
const missing = [...keySymptoms].filter((term) => !activeTerms.has(term)).sort();
|
|
151
|
+
const disconfirmingCatalog = new Set(pattern.disconfirming_symptoms || []);
|
|
152
|
+
const disconfirmingPresent = [...disconfirmingCatalog].filter((term) => activeTerms.has(term)).sort();
|
|
153
|
+
|
|
154
|
+
const matchingCaseIds = [];
|
|
155
|
+
const seen = new Set();
|
|
156
|
+
for (const term of present) {
|
|
157
|
+
for (const caseId of termToCases[term] || []) {
|
|
158
|
+
if (caseId && !seen.has(caseId)) { matchingCaseIds.push(caseId); seen.add(caseId); }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const strength = keySymptoms.size ? Math.round((present.length / keySymptoms.size) * 100) / 100 : 0;
|
|
163
|
+
const confidence = strength >= 0.75 ? 'strong' : strength >= 0.5 ? 'moderate' : 'speculative';
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
pattern_id: pattern.pattern_id,
|
|
167
|
+
type: pattern.type,
|
|
168
|
+
hypothesis_label_suggestion: pattern.hypothesis_label_suggestion,
|
|
169
|
+
treatment_context: pattern.treatment_context,
|
|
170
|
+
member_case_ids_matching: matchingCaseIds,
|
|
171
|
+
key_symptoms_present: present,
|
|
172
|
+
key_symptoms_missing: missing,
|
|
173
|
+
disconfirming_symptoms: disconfirmingPresent,
|
|
174
|
+
match_strength: strength,
|
|
175
|
+
confidence,
|
|
176
|
+
clinical_significance_if_confirmed: pattern.clinical_significance_if_confirmed,
|
|
177
|
+
confidence_would_strengthen_if: [...(pattern.confidence_would_strengthen_if || [])],
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function resolveRegimen(patientId) {
|
|
182
|
+
const [risk] = await readPatientRiskAssessments({ patientId, limit: 1 });
|
|
183
|
+
const regimen = typeof risk?.sourceRegimen === 'string' ? risk.sourceRegimen.trim() : '';
|
|
184
|
+
return regimen || null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function gatherCases({ patientId, scope, specificCaseIds }) {
|
|
188
|
+
if (scope === 'specific_cases') {
|
|
189
|
+
const ids = new Set(specificCaseIds || []);
|
|
190
|
+
const cases = await readSymptomCases({ patientId });
|
|
191
|
+
return cases.filter((symptomCase) => ids.has(symptomCase.condition.conditionId));
|
|
192
|
+
}
|
|
193
|
+
const cases = await readSymptomCases({ patientId });
|
|
194
|
+
const open = cases.filter((symptomCase) => OPEN_STATUSES.includes(symptomCase.condition.clinicalStatus));
|
|
195
|
+
if (scope !== 'include_recent_resolved') return open;
|
|
196
|
+
const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
|
197
|
+
const recentTerminal = cases.filter((symptomCase) => CLOSED_STATUSES.includes(symptomCase.condition.clinicalStatus)
|
|
198
|
+
&& symptomCase.condition.abatementAt && new Date(symptomCase.condition.abatementAt).getTime() >= cutoff);
|
|
199
|
+
return [...open, ...recentTerminal];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function handler(args = {}, context = {}) {
|
|
203
|
+
try {
|
|
204
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
205
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
206
|
+
return fail('analyzeSymptomPatterns requires an active turn context (turnId, patientCode).');
|
|
207
|
+
}
|
|
208
|
+
const specificPattern = typeof args?.specific_pattern_to_validate === 'string' ? args.specific_pattern_to_validate.trim() : '';
|
|
209
|
+
const knownIds = _PATTERN_CATALOG.map((p) => p.pattern_id);
|
|
210
|
+
if (!specificPattern) {
|
|
211
|
+
return fail('specific_pattern_to_validate is required. Pick a pattern_id from your reasoning over the symptom landscape + active regimen + grades, then call this tool to confirm it against the catalog.', { known_pattern_ids: [...knownIds].sort() });
|
|
212
|
+
}
|
|
213
|
+
if (!knownIds.includes(specificPattern)) {
|
|
214
|
+
return fail(`unknown pattern_id: '${specificPattern}'`, { known_pattern_ids: [...knownIds].sort() });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const scope = (typeof args?.scope === 'string' ? args.scope : 'all_active_cases').trim().toLowerCase();
|
|
218
|
+
if (!_SCOPES.includes(scope)) {
|
|
219
|
+
return fail(`invalid scope: '${scope}'. Must be one of ${_SCOPES.join(' | ')}.`, { scope });
|
|
220
|
+
}
|
|
221
|
+
const specificCaseIds = args?.specific_case_ids;
|
|
222
|
+
if (scope === 'specific_cases') {
|
|
223
|
+
if (!Array.isArray(specificCaseIds) || !specificCaseIds.length) {
|
|
224
|
+
return fail('scope=specific_cases requires non-empty specific_case_ids');
|
|
225
|
+
}
|
|
226
|
+
} else if (specificCaseIds !== undefined && specificCaseIds !== null && !(Array.isArray(specificCaseIds) && !specificCaseIds.length)) {
|
|
227
|
+
return fail('specific_case_ids requires scope=specific_cases');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const patientId = runtime.patientCode;
|
|
231
|
+
const matchingCases = await gatherCases({ patientId, scope, specificCaseIds });
|
|
232
|
+
|
|
233
|
+
const termToCases = {};
|
|
234
|
+
const activeTerms = new Set();
|
|
235
|
+
for (const symptomCase of matchingCases) {
|
|
236
|
+
const term = (symptomCase.condition.ctcaeTerm || '').trim().toLowerCase();
|
|
237
|
+
if (!term) continue;
|
|
238
|
+
activeTerms.add(term);
|
|
239
|
+
(termToCases[term] = termToCases[term] || []).push(symptomCase.condition.conditionId);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const patientRegimen = await resolveRegimen(patientId);
|
|
243
|
+
const pattern = _PATTERN_CATALOG.find((p) => p.pattern_id === specificPattern);
|
|
244
|
+
const match = matchPattern(pattern, activeTerms, termToCases, patientRegimen);
|
|
245
|
+
|
|
246
|
+
if (match) {
|
|
247
|
+
return JSON.stringify({ success: true, data: { pattern_validated: true, match } });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const contextOk = regimenMatchesContext(patientRegimen, pattern.treatment_context);
|
|
251
|
+
const keySymptoms = new Set(pattern.key_symptoms || []);
|
|
252
|
+
const present = [...keySymptoms].filter((t) => activeTerms.has(t)).sort();
|
|
253
|
+
const missing = [...keySymptoms].filter((t) => !activeTerms.has(t)).sort();
|
|
254
|
+
const reason = !contextOk
|
|
255
|
+
? `treatment-context mismatch: the pattern requires '${pattern.treatment_context}'; patient regimen is '${patientRegimen}'`
|
|
256
|
+
: `insufficient symptom overlap: ${present.length} of ${keySymptoms.size} key symptoms present (≥2 required)`;
|
|
257
|
+
return JSON.stringify({
|
|
258
|
+
success: true,
|
|
259
|
+
data: {
|
|
260
|
+
pattern_validated: false,
|
|
261
|
+
pattern_id: specificPattern,
|
|
262
|
+
patient_regimen: patientRegimen,
|
|
263
|
+
reason,
|
|
264
|
+
key_symptoms_present: present,
|
|
265
|
+
key_symptoms_missing: missing,
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
} catch (err) {
|
|
269
|
+
return JSON.stringify({ success: false, error: err?.message || 'analyzeSymptomPatterns failed', data: {} });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
module.exports = {
|
|
274
|
+
definition,
|
|
275
|
+
handler,
|
|
276
|
+
};
|