@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 { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
2
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
3
|
+
const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
4
|
+
const { logger } = require('../../utils/logger');
|
|
5
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
6
|
+
|
|
7
|
+
const ACTIVE_DAYS = 35;
|
|
8
|
+
const DEFAULT_CYTOTOXIC_WINDOW_DAYS = 42;
|
|
9
|
+
const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice algo distinto, créele: si es otra fecha de cita, que el paciente la confirme con el área de tratamiento, sin avisar al equipo; si es un dato clínico, o una sesión suspendida o cambiada por un motivo clínico, avisa al equipo)';
|
|
10
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
11
|
+
const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
12
|
+
const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
|
|
13
|
+
const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
|
|
14
|
+
|
|
15
|
+
const isDay = (value) => typeof value === 'string' && ISO_DAY.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
|
|
16
|
+
const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
|
|
17
|
+
// a weekday with the date: the model miscounts the day of the week from a bare date ("el viernes" for a Saturday)
|
|
18
|
+
const WEEKDAYS = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
|
|
19
|
+
const weekdayDmy = (iso) => `${WEEKDAYS[new Date(`${iso}T00:00:00Z`).getUTCDay()]} ${dmy(iso)}`;
|
|
20
|
+
const addDays = (iso, days) => new Date(Date.parse(`${iso}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
|
|
21
|
+
const fold = (value) => foldAccents(String(value || '')).toLowerCase().trim();
|
|
22
|
+
const text = (value) => (typeof value === 'string' ? value.trim() : '');
|
|
23
|
+
const list = (value) => (Array.isArray(value) ? value : []);
|
|
24
|
+
const texts = (value) => list(value).map(text).filter(Boolean);
|
|
25
|
+
const dayOr = (value) => (isDay(value) ? value : null);
|
|
26
|
+
|
|
27
|
+
function normalize(raw) {
|
|
28
|
+
const last = isPlainObject(raw.ultimaAplicacion) && isDay(raw.ultimaAplicacion.fecha) ? raw.ultimaAplicacion : null;
|
|
29
|
+
const nadir = Array.isArray(raw.nadirDias) && raw.nadirDias.length === 2 && raw.nadirDias.every(Number.isInteger) ? raw.nadirDias : null;
|
|
30
|
+
const dated = (value, keys) => (isPlainObject(value) && isDay(value.fecha) && keys.every((k) => k in value) ? value : null);
|
|
31
|
+
return {
|
|
32
|
+
ultimaAplicacion: last,
|
|
33
|
+
ultimaCitotoxica: dayOr(raw.ultimaCitotoxica),
|
|
34
|
+
esquema: list(raw.esquema).filter(isPlainObject).filter((e) => text(e.farmaco)),
|
|
35
|
+
vigilancia: texts(raw.vigilancia),
|
|
36
|
+
nadirDias: nadir,
|
|
37
|
+
premedicacion: texts(raw.premedicacion),
|
|
38
|
+
enCasa: list(raw.enCasa).filter(isPlainObject).filter((m) => text(m.farmaco)),
|
|
39
|
+
inicioEsquema: dated(raw.inicioEsquema, ['anteriorAlRegistro']),
|
|
40
|
+
proximaSesion: dated(raw.proximaSesion, ['tipo']),
|
|
41
|
+
noAplicadas: list(raw.noAplicadas).filter(isDay),
|
|
42
|
+
reaccionInfusion: dated(raw.reaccionInfusion, ['texto']),
|
|
43
|
+
alergias: dated(raw.alergias, ['estado', 'texto']),
|
|
44
|
+
acceso: text(raw.acceso),
|
|
45
|
+
peso: dated(raw.peso, ['kg']),
|
|
46
|
+
signosAnormales: dated(raw.signosAnormales, ['hallazgos']),
|
|
47
|
+
ajusteProximoCiclo: dated(raw.ajusteProximoCiclo, ['valor']),
|
|
48
|
+
esquemaPrevio: isPlainObject(raw.esquemaPrevio) && isDay(raw.esquemaPrevio.hasta) ? { farmacos: texts(raw.esquemaPrevio.farmacos), hasta: raw.esquemaPrevio.hasta } : null,
|
|
49
|
+
visitaSoporte: dated(raw.visitaSoporte, ['farmacos']),
|
|
50
|
+
proximaVisitaSoporte: dated(raw.proximaVisitaSoporte, ['detalle']),
|
|
51
|
+
antecedentes: dated(raw.antecedentes, []),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseChemoContext(raw) {
|
|
56
|
+
const parsed = safeParse(raw, null);
|
|
57
|
+
return isPlainObject(parsed) && parsed.version === 1 ? normalize(parsed) : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function daysSinceLastCytotoxic(context, today = mexicoDay(new Date())) {
|
|
61
|
+
return context?.ultimaCitotoxica ? daysBetween(context.ultimaCitotoxica, today) : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function cytotoxicWindowDays() {
|
|
65
|
+
const days = Number(runtimeConfig.get('FEVER_CHEMO_WINDOW_DAYS', DEFAULT_CYTOTOXIC_WINDOW_DAYS));
|
|
66
|
+
return Number.isFinite(days) && days > 0 ? days : DEFAULT_CYTOTOXIC_WINDOW_DAYS;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// context: null = the unit has no record of the patient; undefined = the record could not be read
|
|
70
|
+
function cytotoxicWindowStatus(context, today, windowDays) {
|
|
71
|
+
if (context === undefined) return 'desconocido: no se pudo leer el registro de la unidad';
|
|
72
|
+
if (context === null) return 'desconocido: la unidad no tiene registro de este paciente';
|
|
73
|
+
if (!context.ultimaCitotoxica) return 'desconocido: el registro de la unidad no tiene una fecha de quimioterapia citotóxica';
|
|
74
|
+
const last = dmy(context.ultimaCitotoxica);
|
|
75
|
+
const days = daysSinceLastCytotoxic(context, today);
|
|
76
|
+
if (!Number.isFinite(days) || days < 0) return `desconocido: no se puede contar desde hoy la última aplicación registrada (${last})`;
|
|
77
|
+
return days <= windowDays
|
|
78
|
+
? `sí: última aplicación citotóxica ${last} (hace ${days} días)`
|
|
79
|
+
: `no según la unidad: última aplicación citotóxica ${last} (hace ${days} días)`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function renderCytotoxicWindow(context, today, windowDays = cytotoxicWindowDays()) {
|
|
83
|
+
return `Quimioterapia citotóxica en los últimos ${windowDays} días (registro de la unidad de quimioterapia; no incluye otros centros ni quimioterapia oral): ${cytotoxicWindowStatus(context, today, windowDays)}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function chemoStatus(context, today, windowDays = ACTIVE_DAYS) {
|
|
87
|
+
const last = context.ultimaAplicacion?.fecha;
|
|
88
|
+
if (!last) return { active: false, days: null };
|
|
89
|
+
const days = daysBetween(last, today);
|
|
90
|
+
if (days < 0) return { active: true, days: null };
|
|
91
|
+
const scheduled = context.proximaSesion && context.proximaSesion.fecha >= today;
|
|
92
|
+
return { active: days <= windowDays || Boolean(scheduled), days };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// the unit confirms an appointment the day before: unconfirmed is the normal state of a later one
|
|
96
|
+
function confirmation(appointment) {
|
|
97
|
+
if (typeof appointment.confirmada !== 'boolean') return '';
|
|
98
|
+
return appointment.confirmada ? 'confirmada por la unidad' : 'la unidad aún no la confirma';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function regimenText(context) {
|
|
102
|
+
return context.esquema.map((e) => [e.farmaco, e.via, e.tiempo].map(text).filter(Boolean).join(' ')).join('; ');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function statusLine(last, active, days) {
|
|
106
|
+
const cycle = [last.ciclo ? `ciclo ${last.ciclo}` : '', last.sesion ? `sesión ${last.sesion}${last.total ? `/${last.total}` : ''}` : ''].filter(Boolean).join(', ');
|
|
107
|
+
const when = days === null ? `última aplicación registrada ${dmy(last.fecha)}` : `última aplicación ${dmy(last.fecha)} (hace ${days} días)`;
|
|
108
|
+
return active
|
|
109
|
+
? `Estado: en quimioterapia activa; ${when}${cycle ? `, ${cycle}` : ''}`
|
|
110
|
+
: `Estado: sin aplicaciones registradas en la unidad desde ${dmy(last.fecha)} (hace ${days} días); confirma con el paciente si sigue en tratamiento`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function chemoLines(context, today) {
|
|
114
|
+
const lines = [];
|
|
115
|
+
const last = context.ultimaAplicacion;
|
|
116
|
+
const { active, days } = chemoStatus(context, today);
|
|
117
|
+
if (last) {
|
|
118
|
+
lines.push(statusLine(last, active, days));
|
|
119
|
+
const regimen = regimenText(context);
|
|
120
|
+
if (regimen) lines.push(`${active ? 'Esquema actual' : 'Último esquema'}: ${regimen}`);
|
|
121
|
+
if (context.vigilancia.length) lines.push(`Vigilar por sus fármacos: ${context.vigilancia.join('; ')}`);
|
|
122
|
+
if (active && days !== null && context.nadirDias && days <= context.nadirDias[1]) {
|
|
123
|
+
const [from, to] = context.nadirDias;
|
|
124
|
+
lines.push(`Mayor riesgo de defensas bajas: días ${from} a ${to} después de la aplicación (${dmy(addDays(last.fecha, from))} al ${dmy(addDays(last.fecha, to))}); hoy es el día ${days}. Fiebre de 38 °C o más es urgente cualquier día`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (context.enCasa.length) {
|
|
128
|
+
lines.push(`Se fue a casa con: ${context.enCasa.map((m) => `${text(m.farmaco)}${text(m.indicacion) ? ` (${text(m.indicacion)})` : ''}${m.esteroide ? ' [esteroide: puede ocultar la fiebre]' : ''}`).join('; ')}`);
|
|
129
|
+
}
|
|
130
|
+
if (context.premedicacion.length) lines.push(`Premedicación en la unidad: ${context.premedicacion.join(', ')}`);
|
|
131
|
+
if (context.inicioEsquema) {
|
|
132
|
+
lines.push(context.inicioEsquema.anteriorAlRegistro
|
|
133
|
+
? `Inicio de este esquema: antes del ${dmy(context.inicioEsquema.fecha)} (inicio del registro)`
|
|
134
|
+
: `Inicio de este esquema: ${dmy(context.inicioEsquema.fecha)}`);
|
|
135
|
+
}
|
|
136
|
+
if (context.proximaSesion && context.proximaSesion.fecha >= today) {
|
|
137
|
+
lines.push(context.proximaSesion.tipo === 'agendada'
|
|
138
|
+
? `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
|
|
139
|
+
: `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
|
|
140
|
+
}
|
|
141
|
+
const support = context.proximaVisitaSoporte;
|
|
142
|
+
if (support && support.fecha >= today) {
|
|
143
|
+
const care = texts(support.detalle);
|
|
144
|
+
lines.push(`Próxima visita a la unidad sin quimioterapia: ${weekdayDmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
|
|
145
|
+
}
|
|
146
|
+
if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
|
|
147
|
+
if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
|
|
148
|
+
if (context.acceso) lines.push(`Acceso venoso: ${context.acceso}`);
|
|
149
|
+
if (Number.isFinite(context.peso?.kg)) {
|
|
150
|
+
const pct = context.peso.cambioPct;
|
|
151
|
+
const change = Number.isFinite(pct) && isDay(context.peso.desde) ? `; cambio ${pct > 0 ? '+' : ''}${pct}% desde ${dmy(context.peso.desde)}` : '';
|
|
152
|
+
lines.push(`Peso: ${context.peso.kg} kg (${dmy(context.peso.fecha)})${change}`);
|
|
153
|
+
}
|
|
154
|
+
const findings = texts(context.signosAnormales?.hallazgos);
|
|
155
|
+
if (findings.length) lines.push(`Signos fuera de rango en la última sesión (${dmy(context.signosAnormales.fecha)}): ${findings.join(', ')}`);
|
|
156
|
+
if (context.ajusteProximoCiclo?.valor === true) lines.push(`El médico indicó un ajuste para el próximo ciclo (${dmy(context.ajusteProximoCiclo.fecha)}): no lo comuniques, lo explica el médico`);
|
|
157
|
+
if (context.esquemaPrevio?.farmacos.length) lines.push(`Esquema previo: ${context.esquemaPrevio.farmacos.join(', ')}, hasta ${dmy(context.esquemaPrevio.hasta)}`);
|
|
158
|
+
if (context.visitaSoporte) {
|
|
159
|
+
const drugs = texts(context.visitaSoporte.farmacos);
|
|
160
|
+
lines.push(`Última visita a la unidad sin quimioterapia: ${dmy(context.visitaSoporte.fecha)}${drugs.length ? ` (${drugs.join(', ')})` : ''}`);
|
|
161
|
+
}
|
|
162
|
+
const h = context.antecedentes;
|
|
163
|
+
if (h) {
|
|
164
|
+
const parts = [['diabetes', h.diabetes], ['hipertensión', h.hipertension], ['otros', h.otros], ['histología', h.histologia], ['tratamiento previo', h.tratamientoPrevio]]
|
|
165
|
+
.filter(([, value]) => text(value)).map(([label, value]) => `${label}: ${text(value)}`);
|
|
166
|
+
if (parts.length) lines.push(`Antecedentes (historia de primera vez, enfermería, ${dmy(h.fecha)}): ${parts.join('; ')}`);
|
|
167
|
+
}
|
|
168
|
+
return lines;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function renderChemoContext(context, today = mexicoDay(new Date())) {
|
|
172
|
+
if (!context) return '';
|
|
173
|
+
try {
|
|
174
|
+
const lines = chemoLines(context, today);
|
|
175
|
+
return lines.length ? `${HEADER}:\n- ${lines.join('\n- ')}` : '';
|
|
176
|
+
} catch (error) {
|
|
177
|
+
logger.warn('[chemoContext] section left out', { error: error.message });
|
|
178
|
+
return '';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function listsAllergy(existing, allergy) {
|
|
183
|
+
const held = fold(existing);
|
|
184
|
+
if (NEGATION.test(held)) return false;
|
|
185
|
+
return new RegExp(`(^|[^a-z0-9])${fold(allergy).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`).test(held);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function withChemoContext(clinical, context, today = mexicoDay(new Date())) {
|
|
189
|
+
if (!context) return clinical || {};
|
|
190
|
+
try {
|
|
191
|
+
const merged = { ...(clinical || {}) };
|
|
192
|
+
if (!text(merged.tratamiento_actual) && chemoStatus(context, today).active && context.esquema.length) {
|
|
193
|
+
merged.tratamiento_actual = `${regimenText(context)} (según la unidad de quimioterapia)`;
|
|
194
|
+
}
|
|
195
|
+
const allergies = context.alergias;
|
|
196
|
+
const nursing = text(allergies?.texto);
|
|
197
|
+
if (allergies?.estado === 'si' && nursing && !listsAllergy(merged.alergias_medicamentos, nursing)) {
|
|
198
|
+
const recorded = `${nursing} (registrado por enfermería, ${dmy(allergies.fecha)})`;
|
|
199
|
+
const held = text(merged.alergias_medicamentos);
|
|
200
|
+
merged.alergias_medicamentos = !held || NO_ALLERGY.test(fold(held)) ? recorded : `${held}; ${recorded}`;
|
|
201
|
+
}
|
|
202
|
+
return merged;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
logger.warn('[chemoContext] merge skipped', { error: error.message });
|
|
205
|
+
return clinical || {};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
module.exports = {
|
|
210
|
+
chemoStatus,
|
|
211
|
+
cytotoxicWindowDays,
|
|
212
|
+
daysSinceLastCytotoxic,
|
|
213
|
+
parseChemoContext,
|
|
214
|
+
renderChemoContext,
|
|
215
|
+
renderCytotoxicWindow,
|
|
216
|
+
withChemoContext,
|
|
217
|
+
};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
const { LEGACY_CONCEPT, NO_KNOWN_ALLERGY } = require('../../fhir/constants/variableRegistry');
|
|
2
|
+
const { ageFrom, genderFrom } = require('../../fhir/resources/Patient');
|
|
3
|
+
const {
|
|
4
|
+
ageInYears, daysBetween, isoDay, mexicoDay,
|
|
5
|
+
} = require('../../utils/dateUtils');
|
|
6
|
+
const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
|
|
7
|
+
const { decodePair } = require('./encodedPairHelper');
|
|
8
|
+
|
|
9
|
+
const FIELD_LABELS = {
|
|
10
|
+
edad: 'Edad',
|
|
11
|
+
sexo: 'Sexo',
|
|
12
|
+
medico_tratante: 'Médico tratante',
|
|
13
|
+
diagnostico: 'Diagnóstico',
|
|
14
|
+
tratamiento_actual: 'Tratamiento actual',
|
|
15
|
+
medicacion_actual: 'Medicación',
|
|
16
|
+
tratamiento_suspendido: 'Suspendido recientemente',
|
|
17
|
+
alergias_medicamentos: 'Alergias',
|
|
18
|
+
comorbilidades: 'Comorbilidades',
|
|
19
|
+
episodios_intercurrentes: 'Episodios',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const FIELD_VARIABLES = Object.freeze({
|
|
23
|
+
diagnostico: Object.freeze(['diagnosis_summary']),
|
|
24
|
+
tratamiento_actual: Object.freeze(['injectable_onco_summary', 'oral_onco_summary', 'radiotherapy_summary', 'surgery_summary', 'legacy_treatment_summary']),
|
|
25
|
+
medicacion_actual: Object.freeze(['other_meds_summary']),
|
|
26
|
+
alergias_medicamentos: Object.freeze(['allergies_list']),
|
|
27
|
+
comorbilidades: Object.freeze(['comorbidities_summary']),
|
|
28
|
+
episodios_intercurrentes: Object.freeze(['intercurrent_events_summary']),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const AGE_EXTENSION_SUFFIX = 'patient-age';
|
|
32
|
+
const MAX_PLAUSIBLE_AGE = 130;
|
|
33
|
+
const GENDER_LABELS = { female: 'Mujer', male: 'Hombre' };
|
|
34
|
+
const VALUE_SEPARATOR = ', ';
|
|
35
|
+
const PART_SEPARATOR = '. ';
|
|
36
|
+
const SECTION_SEPARATOR = '\n\n';
|
|
37
|
+
const RETRACTED = new Set(['resolved', 'inactive', 'stopped', 'not-done']);
|
|
38
|
+
// still stored and covering the field, but not rendered as what the patient has now
|
|
39
|
+
const NOT_CURRENT = new Set(['completed', 'not-taking', 'preparation']);
|
|
40
|
+
|
|
41
|
+
// a stopped drug stays in view while its late toxicity may still show: the sign-off of 2026-10-14 asks a year for
|
|
42
|
+
// checkpoint inhibitors, anthracyclines, ADCs and anti-HER2; every injectable gets it to avoid a catalog read, and
|
|
43
|
+
// an oral anti-HER2 inhibitor gets the 90 days of any oral
|
|
44
|
+
const RECENTLY_STOPPED_DAYS = Object.freeze({
|
|
45
|
+
injectable_onco_summary: 365,
|
|
46
|
+
oral_onco_summary: 90,
|
|
47
|
+
other_meds_summary: 90,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const isRetracted = (status) => RETRACTED.has(status);
|
|
51
|
+
|
|
52
|
+
function isRecentlyStopped(row, today = mexicoDay(new Date())) {
|
|
53
|
+
const windowDays = RECENTLY_STOPPED_DAYS[row.variableId];
|
|
54
|
+
if (!windowDays || row.status !== 'stopped') return false;
|
|
55
|
+
const days = daysBetween(isoDay(row.validTime), today);
|
|
56
|
+
return days >= 0 && days <= windowDays;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
|
|
60
|
+
|
|
61
|
+
function ageOf(patient) {
|
|
62
|
+
const derived = ageInYears(patient?.birthDate);
|
|
63
|
+
if (derived !== null && derived > 0 && derived < MAX_PLAUSIBLE_AGE) return derived;
|
|
64
|
+
const found = (patient?.extension || []).find((ext) => String(ext.url || '').endsWith(AGE_EXTENSION_SUFFIX));
|
|
65
|
+
return found?.valueInteger ?? null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const preferring = (rows, uninformative) => {
|
|
69
|
+
const specific = rows.filter((row) => row.concept !== uninformative);
|
|
70
|
+
return specific.length ? specific : rows;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
function renderableValues(bucket) {
|
|
74
|
+
const current = preferring(bucket, LEGACY_CONCEPT).filter((row) => !NOT_CURRENT.has(row.status));
|
|
75
|
+
return preferring(current, NO_KNOWN_ALLERGY.concept).map((row) => decodePair(row.value));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function fieldsFromFhir(rows, patient, today = mexicoDay(new Date())) {
|
|
79
|
+
const byVariable = new Map();
|
|
80
|
+
const stopped = [];
|
|
81
|
+
for (const row of rows) {
|
|
82
|
+
if (row.value && isRecentlyStopped(row, today)) stopped.push(`${decodePair(row.value)} (a más tardar ${dmy(isoDay(row.validTime))})`);
|
|
83
|
+
if (!row.value || isRetracted(row.status)) continue;
|
|
84
|
+
const bucket = byVariable.get(row.variableId) || [];
|
|
85
|
+
bucket.push(row);
|
|
86
|
+
byVariable.set(row.variableId, bucket);
|
|
87
|
+
}
|
|
88
|
+
const fields = {};
|
|
89
|
+
const age = ageOf(patient);
|
|
90
|
+
if (age !== null) fields.edad = String(age);
|
|
91
|
+
if (patient?.gender && GENDER_LABELS[patient.gender]) fields.sexo = GENDER_LABELS[patient.gender];
|
|
92
|
+
for (const [field, variables] of Object.entries(FIELD_VARIABLES)) {
|
|
93
|
+
const values = renderableValues(variables.flatMap((variableId) => byVariable.get(variableId) || []));
|
|
94
|
+
if (values.length) fields[field] = values.join(VALUE_SEPARATOR);
|
|
95
|
+
}
|
|
96
|
+
if (stopped.length) fields.tratamiento_suspendido = stopped.join(VALUE_SEPARATOR);
|
|
97
|
+
return fields;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A field runs to the separator or to the tail appended after the profile, whichever comes first.
|
|
101
|
+
const legacyField = (label) => new RegExp(`\\b${label}:\\s*([^\\n.]+)`);
|
|
102
|
+
const LEGACY_EDAD = legacyField(FIELD_LABELS.edad);
|
|
103
|
+
const LEGACY_SEXO = legacyField(FIELD_LABELS.sexo);
|
|
104
|
+
const NEXT_LABEL = Object.values(FIELD_LABELS).join('|');
|
|
105
|
+
const LEGACY_MEDICO = new RegExp(`\\b${FIELD_LABELS.medico_tratante}:\\s*(.+?)\\s*(?=\\.\\s+(?:${NEXT_LABEL}):|\\.?\\s*(?:\\n|$))`);
|
|
106
|
+
|
|
107
|
+
const legacyAge = (text) => {
|
|
108
|
+
const found = ageFrom(LEGACY_EDAD.exec(text)?.[1]?.trim());
|
|
109
|
+
return found === null ? null : String(found);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// The legacy block interpolates whatever the profile stored, so `Sexo: F` is as likely as `Sexo: Mujer`.
|
|
113
|
+
const legacyGender = (text) => GENDER_LABELS[genderFrom(LEGACY_SEXO.exec(text)?.[1])] || null;
|
|
114
|
+
|
|
115
|
+
const legacyPhysician = (text) => LEGACY_MEDICO.exec(text)?.[1]?.trim() || null;
|
|
116
|
+
|
|
117
|
+
function withLegacyDemographics(fields, legacyBlock) {
|
|
118
|
+
const text = String(legacyBlock ?? '');
|
|
119
|
+
const out = { ...fields };
|
|
120
|
+
if (!out.edad) out.edad = legacyAge(text) || out.edad;
|
|
121
|
+
if (!out.sexo) out.sexo = legacyGender(text) || out.sexo;
|
|
122
|
+
if (!out.medico_tratante) out.medico_tratante = legacyPhysician(text) || out.medico_tratante;
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function hasClinicalContent(fields) {
|
|
127
|
+
return Object.keys(FIELD_VARIABLES).some((field) => Boolean(fields?.[field]));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function renderContextBlock(fields) {
|
|
131
|
+
return Object.entries(FIELD_LABELS)
|
|
132
|
+
.filter(([field]) => fields[field])
|
|
133
|
+
.map(([field, label]) => `${label}: ${sanitizeInlineText(fields[field], Infinity)}`)
|
|
134
|
+
.join(PART_SEPARATOR);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/* Swaps the clinical profile for the FHIR-rendered one and leaves everything after it alone.
|
|
138
|
+
* `clinical_context` is not only the profile: a risk headline produced by a different subsystem is
|
|
139
|
+
* appended after it, and replacing the whole variable would silently drop that headline. The marker is
|
|
140
|
+
* the boundary; the section separator is the fallback, so a marker that stops matching keeps the tail
|
|
141
|
+
* instead of discarding it.
|
|
142
|
+
*/
|
|
143
|
+
function swapProfilePortion(legacyBlock, fhirBlock, marker = null) {
|
|
144
|
+
const text = String(legacyBlock ?? '');
|
|
145
|
+
const profile = String(fhirBlock ?? '');
|
|
146
|
+
const at = marker ? text.indexOf(marker) : -1;
|
|
147
|
+
if (at === -1) return profile;
|
|
148
|
+
const tail = text.slice(at);
|
|
149
|
+
return profile ? `${profile}${SECTION_SEPARATOR}${tail}` : tail;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
module.exports = {
|
|
153
|
+
FIELD_VARIABLES,
|
|
154
|
+
fieldsFromFhir,
|
|
155
|
+
withLegacyDemographics,
|
|
156
|
+
hasClinicalContent,
|
|
157
|
+
isRetracted,
|
|
158
|
+
isRecentlyStopped,
|
|
159
|
+
renderContextBlock,
|
|
160
|
+
swapProfilePortion,
|
|
161
|
+
VALUE_SEPARATOR,
|
|
162
|
+
};
|
|
@@ -12,13 +12,24 @@ const CATEGORY_TO_KIND = {
|
|
|
12
12
|
};
|
|
13
13
|
const LOW_CONFIDENCE = 0.7;
|
|
14
14
|
|
|
15
|
-
function projectClinicalFacts({ clinicalMentions = [], safetyFlags = [], gradeScales = {} }) {
|
|
15
|
+
function projectClinicalFacts({ clinicalMentions = [], safetyFlags = [], gradeScales = {}, askAgenda = null }) {
|
|
16
16
|
const clinicalFacts = clinicalMentions.map((m) => toClinicalFact(m, gradeScales)).filter(Boolean);
|
|
17
|
+
const pendingConfirmation = askAgenda?.pendingConfirmation || [];
|
|
18
|
+
const contextGaps = askAgenda?.contextGaps || [];
|
|
17
19
|
|
|
18
20
|
const symptoms = clinicalMentions.filter((m) => m?.fact?.category === 'symptom').length;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
21
|
+
let agentHint;
|
|
22
|
+
if (pendingConfirmation.length) {
|
|
23
|
+
const [pending] = pendingConfirmation;
|
|
24
|
+
const extra = pendingConfirmation.length > 1 ? ` (+${pendingConfirmation.length - 1} más sin confirmar)` : '';
|
|
25
|
+
agentHint = `Hecho clínico sin confirmar: «${pending.term}»${extra}. No se registró. Pregunta al paciente SOLO por este antes de darlo por cierto.`;
|
|
26
|
+
} else if (!clinicalMentions.length) {
|
|
27
|
+
agentHint = contextGaps.length
|
|
28
|
+
? `Sin entidades clínicas extraíbles en este mensaje. Dato desactualizado que puedes aprovechar para preguntar: ${contextGaps[0]}.`
|
|
29
|
+
: 'Sin entidades clínicas extraíbles en este mensaje.';
|
|
30
|
+
} else {
|
|
31
|
+
agentHint = symptoms ? `${symptoms} síntoma(s) nuevo(s)` : `${clinicalMentions.length} mención(es) clínica(s)`;
|
|
32
|
+
}
|
|
22
33
|
|
|
23
34
|
return {
|
|
24
35
|
success: true,
|
|
@@ -28,6 +39,8 @@ function projectClinicalFacts({ clinicalMentions = [], safetyFlags = [], gradeSc
|
|
|
28
39
|
degraded: false,
|
|
29
40
|
degraded_reasons: [],
|
|
30
41
|
clinical_facts: clinicalFacts,
|
|
42
|
+
pending_confirmation: pendingConfirmation,
|
|
43
|
+
context_gaps: contextGaps,
|
|
31
44
|
},
|
|
32
45
|
};
|
|
33
46
|
}
|
|
@@ -76,6 +89,34 @@ function toClinicalFact(mention, gradeScales = {}) {
|
|
|
76
89
|
return out;
|
|
77
90
|
}
|
|
78
91
|
|
|
92
|
+
function renderClinicalIntakeSummary({ clinicalMentions = [], safetyFlags = [] } = {}) {
|
|
93
|
+
const lines = clinicalMentions.map((mention) => {
|
|
94
|
+
const fact = mention?.fact || {};
|
|
95
|
+
const prov = mention?.provenance || {};
|
|
96
|
+
if (!fact.canonicalTerm) return null;
|
|
97
|
+
const parts = [`[${fact.category || 'mención'}] ${fact.canonicalTerm}`];
|
|
98
|
+
if (fact.ctcaeTerm && fact.ctcaeTerm !== fact.canonicalTerm) parts.push(`CTCAE: ${fact.ctcaeTerm}`);
|
|
99
|
+
const observed = Object.entries(fact.observedFields || {})
|
|
100
|
+
.filter(([, value]) => value !== null && value !== undefined)
|
|
101
|
+
.map(([key, value]) => `${key}=${value}`);
|
|
102
|
+
if (observed.length) parts.push(observed.join(', '));
|
|
103
|
+
const assertion = fact.assertion || {};
|
|
104
|
+
if (assertion.negated) parts.push('negado');
|
|
105
|
+
if (assertion.hedged) parts.push('con duda');
|
|
106
|
+
if (assertion.temporal && assertion.temporal !== 'current') parts.push(assertion.temporal);
|
|
107
|
+
if (assertion.experiencer && assertion.experiencer !== 'patient') parts.push(`de: ${assertion.experiencer}`);
|
|
108
|
+
const quote = (Array.isArray(prov.verbatimQuotes) ? prov.verbatimQuotes : []).find(Boolean);
|
|
109
|
+
if (quote) parts.push(`«${quote}»`);
|
|
110
|
+
if (prov.resolvedFromContext) parts.push('resuelto en contexto');
|
|
111
|
+
return `- ${parts.join(' — ')}`;
|
|
112
|
+
}).filter(Boolean);
|
|
113
|
+
if (!lines.length) return '';
|
|
114
|
+
const flags = safetyFlags.map((flag) => (typeof flag === 'string' ? flag : flag?.type)).filter(Boolean);
|
|
115
|
+
const flagLine = flags.length ? `\nAlertas de seguridad: ${flags.join(', ')}` : '';
|
|
116
|
+
return `Extracción clínica (clinical-agent):\n${lines.join('\n')}${flagLine}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
79
119
|
module.exports = {
|
|
80
120
|
projectClinicalFacts,
|
|
121
|
+
renderClinicalIntakeSummary,
|
|
81
122
|
};
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
const { ClinicalMention } = require('../../shared/dtos/ClinicalMention');
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
const { readStructuredText } = require('./structuredTextHelper');
|
|
4
|
+
|
|
5
|
+
function buildExtractorInput(text, detectedTags, curated, template, { priorTurns = null, patientContext = null } = {}) {
|
|
6
|
+
const priorTurnsPayload = Array.isArray(priorTurns) && priorTurns.length ? { prior_turns: priorTurns } : {};
|
|
7
|
+
const contextPayload = patientContext ? { patient_context: patientContext } : {};
|
|
8
|
+
const payload = JSON.stringify({
|
|
9
|
+
raw_message: text,
|
|
10
|
+
detected_tags: detectedTags,
|
|
11
|
+
...priorTurnsPayload,
|
|
12
|
+
...contextPayload,
|
|
13
|
+
}, null, 2);
|
|
5
14
|
const tpl = curated.length ? template.symptom : template.default;
|
|
6
15
|
return tpl
|
|
7
16
|
.replace('{{curated}}', () => JSON.stringify(curated, null, 2))
|
|
8
17
|
.replace('{{payload}}', () => payload);
|
|
9
18
|
}
|
|
10
19
|
|
|
11
|
-
function
|
|
12
|
-
if (result?.output_text) return result.output_text;
|
|
13
|
-
const output = Array.isArray(result?.output) ? result.output : [];
|
|
14
|
-
const message = output.find((item) => item.type === 'message');
|
|
15
|
-
const content = Array.isArray(message?.content) ? message.content : [];
|
|
16
|
-
const part = content.find((c) => typeof c?.text === 'string');
|
|
17
|
-
return part?.text || '';
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function toClinicalMention(raw, { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm = {} }) {
|
|
20
|
+
function toClinicalMention(raw, { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm = {}, ctcaeV5ByTerm = {} }) {
|
|
21
21
|
const rawTerm = (raw.ctcae_term || '').trim().toLowerCase();
|
|
22
22
|
const ctcaeTerm = !rawTerm || rawTerm === 'other' ? null : rawTerm;
|
|
23
23
|
const canonicalTerm = deriveCanonicalTerm(raw, ctcaeTerm, spanishByTerm);
|
|
@@ -35,6 +35,7 @@ function toClinicalMention(raw, { code, turnId, index, now, intakeSource, respon
|
|
|
35
35
|
reportedAt: now,
|
|
36
36
|
assertion: raw.assertion || {},
|
|
37
37
|
ctcaeTerm,
|
|
38
|
+
ctcaeV5Term: (ctcaeTerm && ctcaeV5ByTerm[ctcaeTerm]) || null,
|
|
38
39
|
temporality: raw.temporality || null,
|
|
39
40
|
observedFields: responseFormat === 'router'
|
|
40
41
|
? Object.fromEntries(Object.entries(observed).filter(([, v]) => v != null))
|
|
@@ -48,6 +49,9 @@ function toClinicalMention(raw, { code, turnId, index, now, intakeSource, respon
|
|
|
48
49
|
source: intakeSource || 'self',
|
|
49
50
|
verbatimQuotes: verbatim,
|
|
50
51
|
extractorConfidence: raw.extractor_confidence ?? raw.confidence ?? raw.assertion?.confidence ?? 1,
|
|
52
|
+
resolvedFromContext: raw.resolved_from_context === true,
|
|
53
|
+
needsConfirmation: raw.needs_confirmation === true,
|
|
54
|
+
missingDetails: Array.isArray(raw.missing) ? raw.missing.filter((d) => typeof d === 'string') : [],
|
|
51
55
|
},
|
|
52
56
|
});
|
|
53
57
|
}
|
|
@@ -63,6 +67,5 @@ function deriveCanonicalTerm(raw, ctcaeTerm, spanishByTerm) {
|
|
|
63
67
|
|
|
64
68
|
module.exports = {
|
|
65
69
|
buildExtractorInput,
|
|
66
|
-
readOutputText,
|
|
67
70
|
toClinicalMention,
|
|
68
71
|
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const { resolveProfileIdentity } = require('../services/patientProfileService');
|
|
2
|
+
const { safeParse } = require('../../utils/jsonUtils');
|
|
3
|
+
const { parseChemoContext } = require('./chemoContextHelper');
|
|
4
|
+
|
|
5
|
+
const CONTEXT_FIELD = 'clinical-context-json';
|
|
6
|
+
|
|
7
|
+
function isPopulated(value) {
|
|
8
|
+
if (value === null || value === undefined) return false;
|
|
9
|
+
if (typeof value === 'object') return Object.values(value).some(isPopulated);
|
|
10
|
+
return String(value).trim() !== '';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function populatedCount(section) {
|
|
14
|
+
if (!section || typeof section !== 'object') return 0;
|
|
15
|
+
return Object.values(section).filter(isPopulated).length;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const clinicalFieldCount = (profile) => populatedCount(profile?.datos_clinicos);
|
|
19
|
+
|
|
20
|
+
const totalFieldCount = (profile) => Object.values(profile).reduce((sum, section) => sum + populatedCount(section), 0);
|
|
21
|
+
|
|
22
|
+
function richestProfile(records) {
|
|
23
|
+
const parsed = records
|
|
24
|
+
.map((record) => ({
|
|
25
|
+
profile: safeParse(record?.[CONTEXT_FIELD], null),
|
|
26
|
+
when: Date.parse(record?.last_modified_clinical_context) || 0,
|
|
27
|
+
}))
|
|
28
|
+
.filter((entry) => entry.profile && typeof entry.profile === 'object');
|
|
29
|
+
if (!parsed.length) return null;
|
|
30
|
+
parsed.sort((a, b) => clinicalFieldCount(b.profile) - clinicalFieldCount(a.profile)
|
|
31
|
+
|| totalFieldCount(b.profile) - totalFieldCount(a.profile)
|
|
32
|
+
|| b.when - a.when);
|
|
33
|
+
return parsed[0].profile;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// null: no profile; undefined: unreadable
|
|
37
|
+
async function readResolvedRecord(code) {
|
|
38
|
+
try {
|
|
39
|
+
const identity = await resolveProfileIdentity(code);
|
|
40
|
+
if (identity.kind === 'missing') return null;
|
|
41
|
+
return identity.kind === 'resolved' ? identity.record : undefined;
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function readClinicalProfile(code) {
|
|
48
|
+
const record = await readResolvedRecord(code);
|
|
49
|
+
return record ? richestProfile([record]) : record;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// null: no chemo record; undefined: unreadable or unparseable
|
|
53
|
+
async function readRecordedChemo(code) {
|
|
54
|
+
const record = await readResolvedRecord(code);
|
|
55
|
+
if (!record) return record;
|
|
56
|
+
if (!record.quimio_context) return null;
|
|
57
|
+
return parseChemoContext(record.quimio_context) ?? undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { readClinicalProfile, readRecordedChemo, richestProfile };
|