@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,39 @@
|
|
|
1
|
+
const { logger } = require('../../utils/logger');
|
|
2
|
+
|
|
3
|
+
const DELIVERY_OUTCOMES = new Set(['sent', 'known_not_sent', 'unknown']);
|
|
4
|
+
|
|
5
|
+
async function settleClaimedDelivery({
|
|
6
|
+
directive,
|
|
7
|
+
settleDelivery,
|
|
8
|
+
outcome,
|
|
9
|
+
providerMessageId = null,
|
|
10
|
+
patientCode,
|
|
11
|
+
turnId = null,
|
|
12
|
+
traceId = null,
|
|
13
|
+
}) {
|
|
14
|
+
if (!directive?.claimed || directive.settled || !DELIVERY_OUTCOMES.has(outcome)
|
|
15
|
+
|| typeof settleDelivery !== 'function') return false;
|
|
16
|
+
|
|
17
|
+
const accepted = await settleDelivery({
|
|
18
|
+
operationId: directive.operationId,
|
|
19
|
+
outcome,
|
|
20
|
+
providerMessageId: typeof providerMessageId === 'string' && providerMessageId
|
|
21
|
+
? providerMessageId
|
|
22
|
+
: null,
|
|
23
|
+
patientCode,
|
|
24
|
+
turnId,
|
|
25
|
+
traceId,
|
|
26
|
+
});
|
|
27
|
+
if (accepted === false) {
|
|
28
|
+
logger.warn('[deliverySettlement] repository rejected settlement', {
|
|
29
|
+
operationId: directive.operationId,
|
|
30
|
+
outcome,
|
|
31
|
+
});
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
directive.settled = true;
|
|
35
|
+
if (outcome === 'known_not_sent') directive.claimed = false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = { settleClaimedDelivery };
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
const { termForItem } = require('../../fhir/helpers/terminologyHelper');
|
|
2
|
+
const {
|
|
3
|
+
keyOf, resolveTerm, symptomRecord, aliasKeysOf, aliasClosure, symptomKeySet,
|
|
4
|
+
} = require('../../fhir/helpers/symptomAliasHelper');
|
|
5
|
+
const { str, strList } = require('../../utils/coercionUtils');
|
|
6
|
+
|
|
7
|
+
const URGENT_CARD_NAMES = {
|
|
8
|
+
equipo_tratante_hoy: 'Contacto con tu equipo médico hoy',
|
|
9
|
+
urgencias: 'Atención médica urgente',
|
|
10
|
+
emergencia: 'Atención médica inmediata',
|
|
11
|
+
};
|
|
12
|
+
const SURFACE_MAX = 6;
|
|
13
|
+
|
|
14
|
+
const itemTerm = (catalog, item) => (catalog?.item_index ? termForItem(catalog, item) : null);
|
|
15
|
+
|
|
16
|
+
function deniedAeKeySet(catalog, gate) {
|
|
17
|
+
const keys = new Set();
|
|
18
|
+
for (const redFlag of (gate?.redFlags || [])) {
|
|
19
|
+
if (redFlag?.verificationStatus !== 'denied') continue;
|
|
20
|
+
for (const ae of (redFlag.relatedAes || [])) {
|
|
21
|
+
for (const key of aliasClosure(catalog, ae?.ctcaeTerm)) keys.add(key);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return keys;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function resolveAdditionalSymptoms(catalog, items = []) {
|
|
28
|
+
return items
|
|
29
|
+
.map((item) => str(item).trim())
|
|
30
|
+
.filter(Boolean)
|
|
31
|
+
.map((item) => {
|
|
32
|
+
const term = itemTerm(catalog, item);
|
|
33
|
+
const record = symptomRecord(catalog, term);
|
|
34
|
+
return { term, label: record?.es || record?.en || term || item };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function targetKeysOf(element) {
|
|
39
|
+
return [...new Set([
|
|
40
|
+
...strList(element.targetedCtcaeTerms),
|
|
41
|
+
...(element.symptoms || []).map((symptom) => symptom.ctcaeTerm),
|
|
42
|
+
].map(keyOf).filter(Boolean))];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const singleLine = (value) => (value && !value.includes('\n') ? value : '');
|
|
46
|
+
|
|
47
|
+
const spellingOf = (record, fallback) => str(singleLine(str(record?.ctcae_v5)) || record?.en || fallback).trim();
|
|
48
|
+
|
|
49
|
+
function canonicalCtcaeTerm(catalog, term) {
|
|
50
|
+
const resolved = resolveTerm(catalog, term);
|
|
51
|
+
return resolved ? spellingOf(catalog.symptoms[resolved], resolved) || term : term;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A free-text complaint the classifier could not code keeps the patient's label: a fuzzy
|
|
55
|
+
// alias match would rename it to a catalog term she never reported, and drop the card.
|
|
56
|
+
function canonicaliseTerms(element, catalog, uncodedKeys = new Set()) {
|
|
57
|
+
const canonical = (term) => (uncodedKeys.has(keyOf(term)) ? term : canonicalCtcaeTerm(catalog, term));
|
|
58
|
+
element.targetedCtcaeTerms = [...new Set(element.targetedCtcaeTerms.map(canonical))];
|
|
59
|
+
for (const symptom of element.symptoms) {
|
|
60
|
+
symptom.ctcaeTerm = canonical(symptom.ctcaeTerm);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function reportedSymptoms(catalog, terms = []) {
|
|
65
|
+
return [...new Set(terms.filter(Boolean))].map((term) => {
|
|
66
|
+
const record = symptomRecord(catalog, term);
|
|
67
|
+
return {
|
|
68
|
+
ctcaeTerm: spellingOf(record, term),
|
|
69
|
+
label: record?.es || record?.en || term,
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function labelFor(catalog, term) {
|
|
75
|
+
const key = keyOf(term);
|
|
76
|
+
for (const candidate of Object.keys(catalog?.symptoms || {})) {
|
|
77
|
+
if (aliasKeysOf(catalog, candidate).has(key)) return catalog.symptoms[candidate].es || candidate;
|
|
78
|
+
}
|
|
79
|
+
return term;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function setCardSurface(element, labels) {
|
|
83
|
+
const surface = [...new Set(labels.filter(Boolean))].slice(0, SURFACE_MAX);
|
|
84
|
+
element.nameShort = surface.join(' · ');
|
|
85
|
+
element.recommendation.symptomsPatientFacing = surface;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Naming a symptom she did not report today reads to her as an error about who we are treating.
|
|
89
|
+
// With nothing reported the anchor is unverifiable, and dropping every card helps nobody.
|
|
90
|
+
const survives = (key, { deniedKeys, reportedKeys }) => !deniedKeys.has(key)
|
|
91
|
+
&& (!reportedKeys.size || reportedKeys.has(key));
|
|
92
|
+
|
|
93
|
+
function breachOf(element, boundary) {
|
|
94
|
+
const targets = targetKeysOf(element);
|
|
95
|
+
if (!targets.length) return null;
|
|
96
|
+
const removed = targets.filter((key) => !survives(key, boundary));
|
|
97
|
+
if (removed.length < targets.length) {
|
|
98
|
+
return removed.length
|
|
99
|
+
? { drop: false, why: `síntomas no reportados hoy retirados del objetivo (${removed.join(', ')})` }
|
|
100
|
+
: null;
|
|
101
|
+
}
|
|
102
|
+
const denied = [...new Set(targets.filter((key) => boundary.deniedKeys.has(key)))];
|
|
103
|
+
if (denied.length) return { drop: true, why: `apunta solo a síntomas negados hoy (${denied.join(', ')})` };
|
|
104
|
+
const fromDenial = [...new Set(targets.filter((key) => boundary.deniedAeKeys.has(key)))];
|
|
105
|
+
if (fromDenial.length) {
|
|
106
|
+
return { drop: true, why: `construida sobre una bandera negada (${fromDenial.join(', ')}) sin síntoma reportado que la sostenga` };
|
|
107
|
+
}
|
|
108
|
+
const unresolved = targets.filter((key) => !resolveTerm(boundary.catalog, key));
|
|
109
|
+
return {
|
|
110
|
+
drop: true,
|
|
111
|
+
unanchored: unresolved.length === targets.length,
|
|
112
|
+
why: `no nombra ningún síntoma reportado en este triaje (${targets.join(', ')})`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function stripToReportedTargets(element, boundary) {
|
|
117
|
+
element.targetedCtcaeTerms = element.targetedCtcaeTerms.filter((term) => survives(keyOf(term), boundary));
|
|
118
|
+
element.symptoms = element.symptoms.filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary));
|
|
119
|
+
if (!element.targetedCtcaeTerms.length) {
|
|
120
|
+
// targeted_ctcae_terms is min(1) in the DTO: an emptied target fails the whole plan, not the card.
|
|
121
|
+
element.targetedCtcaeTerms = [...new Set(element.symptoms.map((symptom) => symptom.ctcaeTerm).filter(Boolean))];
|
|
122
|
+
}
|
|
123
|
+
if (!element.targetedCtcaeTerms.length) return false;
|
|
124
|
+
setCardSurface(element, element.targetedCtcaeTerms.map((term) => labelFor(boundary.catalog, term)));
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const deniedToday = (term, { deniedKeys, deniedAeKeys }) => deniedKeys.has(keyOf(term)) || deniedAeKeys.has(keyOf(term));
|
|
129
|
+
|
|
130
|
+
const ownTargetsOf = (element, boundary) => element.targetedCtcaeTerms.filter((term) => !deniedToday(term, boundary));
|
|
131
|
+
|
|
132
|
+
function keepTargets(element, targets, boundary) {
|
|
133
|
+
if (!targets.length) return false;
|
|
134
|
+
element.targetedCtcaeTerms = targets;
|
|
135
|
+
element.symptoms = element.symptoms.filter((symptom) => !deniedToday(symptom.ctcaeTerm, boundary));
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const urgentCardName = (gate) => URGENT_CARD_NAMES[gate.escalationRoute] || URGENT_CARD_NAMES.urgencias;
|
|
140
|
+
|
|
141
|
+
// El gate urgente viaja en esta tarjeta: se le cambia el rótulo, no se descarta.
|
|
142
|
+
function reframeOnGate(element, boundary) {
|
|
143
|
+
if (boundary.gate?.urgentUnder24h !== true || element.escalation?.urgentUnder24h !== true) return false;
|
|
144
|
+
const own = ownTargetsOf(element, boundary);
|
|
145
|
+
const anchors = (boundary.reported || [])
|
|
146
|
+
.filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary))
|
|
147
|
+
.slice(0, SURFACE_MAX)
|
|
148
|
+
.map((symptom) => symptom.ctcaeTerm);
|
|
149
|
+
const touchesDenial = [...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)]
|
|
150
|
+
.some((term) => deniedToday(term, boundary));
|
|
151
|
+
const catalogLabels = own.map((term) => symptomRecord(boundary.catalog, resolveTerm(boundary.catalog, term))?.es);
|
|
152
|
+
const header = catalogLabels.every(Boolean) || touchesDenial
|
|
153
|
+
? catalogLabels.filter(Boolean)
|
|
154
|
+
: strList(element.recommendation.symptomsPatientFacing);
|
|
155
|
+
if (!keepTargets(element, own.length ? own : anchors, boundary)) return false;
|
|
156
|
+
const name = urgentCardName(boundary.gate);
|
|
157
|
+
element.nameShort = name;
|
|
158
|
+
element.recommendation.symptomsPatientFacing = header.length ? [...new Set(header)].slice(0, SURFACE_MAX) : [name];
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = false } = {}) {
|
|
163
|
+
if (!boundary) return { elements, dropped: 0, stripped: 0, urgentReframed: [] };
|
|
164
|
+
const kept = [];
|
|
165
|
+
const unanchored = [];
|
|
166
|
+
const urgentReframed = [];
|
|
167
|
+
let dropped = 0;
|
|
168
|
+
let stripped = 0;
|
|
169
|
+
for (const element of elements) {
|
|
170
|
+
canonicaliseTerms(element, boundary.catalog, boundary.uncodedKeys);
|
|
171
|
+
const breach = breachOf(element, boundary);
|
|
172
|
+
if (!breach) {
|
|
173
|
+
kept.push(element);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (!breach.drop && stripToReportedTargets(element, boundary)) {
|
|
177
|
+
repairs.push(`elemento (rank ${element.rank}): ${breach.why}`);
|
|
178
|
+
stripped += 1;
|
|
179
|
+
kept.push(element);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (reframeOnGate(element, boundary)) {
|
|
183
|
+
repairs.push(`elemento (rank ${element.rank}) urgente conservado con un título genérico para mantener el gate: ${breach.why}`);
|
|
184
|
+
stripped += 1;
|
|
185
|
+
urgentReframed.push(element);
|
|
186
|
+
kept.push(element);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
repairs.push(`elemento (rank ${element.rank}) descartado: ${breach.why}`);
|
|
190
|
+
if (breach.unanchored) unanchored.push(element);
|
|
191
|
+
dropped += 1;
|
|
192
|
+
}
|
|
193
|
+
const rescued = rescue && !kept.length
|
|
194
|
+
? unanchored.sort((a, b) => a.rank - b.rank).find((element) => keepTargets(element, ownTargetsOf(element, boundary), boundary))
|
|
195
|
+
: null;
|
|
196
|
+
if (rescued) {
|
|
197
|
+
repairs.push(`elemento (rank ${rescued.rank}) conservado sobre su propio objetivo en vez de descartar el plan entero`);
|
|
198
|
+
kept.push(rescued);
|
|
199
|
+
stripped += 1;
|
|
200
|
+
dropped -= 1;
|
|
201
|
+
}
|
|
202
|
+
if (dropped) {
|
|
203
|
+
kept.sort((a, b) => a.rank - b.rank);
|
|
204
|
+
kept.forEach((element, index) => { element.rank = index + 1; });
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
elements: kept, dropped, stripped, urgentReframed,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
module.exports = {
|
|
212
|
+
canonicalCtcaeTerm,
|
|
213
|
+
symptomKeySet,
|
|
214
|
+
deniedAeKeySet,
|
|
215
|
+
resolveAdditionalSymptoms,
|
|
216
|
+
reportedSymptoms,
|
|
217
|
+
applyCardSurfaceBoundary,
|
|
218
|
+
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
const { DispatchedEscalation } = require('../../shared/dtos/DispatchedEscalation');
|
|
2
|
+
const { projectDispatchedEscalation } = require('../../fhir/projections/dispatchedEscalationProjection');
|
|
3
|
+
const { storeResources } = require('../../fhir/services/fhirService');
|
|
4
|
+
|
|
5
|
+
const SLA_MINUTES_BY_SEVERITY = {
|
|
6
|
+
critical: 10,
|
|
7
|
+
high: 30,
|
|
8
|
+
medium: 240,
|
|
9
|
+
low: 1440,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const CRISIS_FOLLOWUP_DELAY_MINUTES = 120;
|
|
13
|
+
const CRISIS_FOLLOWUP_PURPOSE = 'crisis_followup_check';
|
|
14
|
+
|
|
15
|
+
const MEDICAL_URGENCY_TO_SEVERITY = {
|
|
16
|
+
stat: 'critical',
|
|
17
|
+
asap: 'high',
|
|
18
|
+
urgent: 'high',
|
|
19
|
+
routine: 'medium',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const EMERGENCY_LEVELS = new Set(['stat', 'asap']);
|
|
23
|
+
|
|
24
|
+
function pageNavigator({ severity, priority = null, reason }) {
|
|
25
|
+
return {
|
|
26
|
+
kind: 'page_navigator',
|
|
27
|
+
severity,
|
|
28
|
+
priority,
|
|
29
|
+
reason,
|
|
30
|
+
requiresAck: severity === 'critical' || severity === 'high',
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function pageOncologist({ severity, priority = null, reason }) {
|
|
35
|
+
return {
|
|
36
|
+
kind: 'page_oncologist',
|
|
37
|
+
severity,
|
|
38
|
+
priority,
|
|
39
|
+
reason,
|
|
40
|
+
requiresAck: true,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function openTicket({ severity, priority = null, title, reason }) {
|
|
45
|
+
return {
|
|
46
|
+
kind: 'open_ticket',
|
|
47
|
+
severity,
|
|
48
|
+
priority,
|
|
49
|
+
title,
|
|
50
|
+
reason,
|
|
51
|
+
slaMinutes: SLA_MINUTES_BY_SEVERITY[severity] ?? null,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function scheduleFollowup({ delayMinutes, purpose, reason, now }) {
|
|
56
|
+
return {
|
|
57
|
+
kind: 'schedule_followup',
|
|
58
|
+
severity: 'medium',
|
|
59
|
+
reason,
|
|
60
|
+
fireAt: new Date(new Date(now).getTime() + delayMinutes * 60000).toISOString(),
|
|
61
|
+
followupPurpose: purpose,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function planMedicalUrgent(signal) {
|
|
66
|
+
const level = (signal?.urgencyLevel || 'urgent').toLowerCase();
|
|
67
|
+
const indicators = Array.isArray(signal?.indicators) ? signal.indicators : [];
|
|
68
|
+
const label = signal?.category || signal?.symptom || signal?.suspectedCondition || 'medical';
|
|
69
|
+
const priority = MEDICAL_URGENCY_TO_SEVERITY[level] ? level : null;
|
|
70
|
+
if (EMERGENCY_LEVELS.has(level)) {
|
|
71
|
+
const severity = MEDICAL_URGENCY_TO_SEVERITY[level];
|
|
72
|
+
const reason = `emergency gate fired: ${indicators.join(', ') || 'unspecified'} (level=${level})`;
|
|
73
|
+
return [
|
|
74
|
+
pageOncologist({ severity, priority, reason }),
|
|
75
|
+
pageNavigator({ severity, priority, reason }),
|
|
76
|
+
openTicket({ severity, priority, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
const severity = MEDICAL_URGENCY_TO_SEVERITY[level] || 'medium';
|
|
80
|
+
return [
|
|
81
|
+
openTicket({
|
|
82
|
+
severity,
|
|
83
|
+
priority,
|
|
84
|
+
title: `MED-${level.toUpperCase()}: ${String(label).slice(0, 60)}`,
|
|
85
|
+
reason: signal?.urgencyJustification || null,
|
|
86
|
+
}),
|
|
87
|
+
];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function planCrisis(signal, now) {
|
|
91
|
+
const reason = `crisis protocol fired: ${(signal?.signals || []).join(', ') || 'unspecified'}`;
|
|
92
|
+
return [
|
|
93
|
+
pageNavigator({ severity: 'critical', reason }),
|
|
94
|
+
openTicket({ severity: 'critical', title: `CRISIS: ${signal?.crisisLevel || 'unspecified'}`, reason }),
|
|
95
|
+
scheduleFollowup({ delayMinutes: CRISIS_FOLLOWUP_DELAY_MINUTES, purpose: CRISIS_FOLLOWUP_PURPOSE, reason, now }),
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function buildPlan({ escalationKind, trace, now }) {
|
|
100
|
+
const signals = trace?.signals || {};
|
|
101
|
+
if (escalationKind === 'medical_urgent') return planMedicalUrgent(signals.medicalEscalation);
|
|
102
|
+
if (escalationKind === 'crisis') return planCrisis(signals.crisis, now);
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const RECENT_KEYS_CAP = 5000;
|
|
107
|
+
|
|
108
|
+
function createDispatcherService() {
|
|
109
|
+
const recentKeys = new Set();
|
|
110
|
+
|
|
111
|
+
async function dispatch({ trace, escalationKind, turnId, patientCode, now = new Date().toISOString() }) {
|
|
112
|
+
if (!turnId || !patientCode) {
|
|
113
|
+
throw new Error('dispatch requires non-empty turnId and patientCode');
|
|
114
|
+
}
|
|
115
|
+
const plan = buildPlan({ escalationKind, trace, now });
|
|
116
|
+
const fresh = plan.filter((primitive) => !recentKeys.has(`${turnId}:${escalationKind}:${primitive.kind}`));
|
|
117
|
+
if (!fresh.length) return { count: 0, ids: [] };
|
|
118
|
+
|
|
119
|
+
const dispatched = fresh.map((primitive) => DispatchedEscalation.schema.parse({
|
|
120
|
+
...primitive,
|
|
121
|
+
eventId: `disp_${turnId}_${escalationKind}_${primitive.kind}`,
|
|
122
|
+
patientId: patientCode,
|
|
123
|
+
createdAt: now,
|
|
124
|
+
}));
|
|
125
|
+
|
|
126
|
+
const resources = dispatched.flatMap((escalation) => projectDispatchedEscalation(escalation));
|
|
127
|
+
await storeResources(resources);
|
|
128
|
+
|
|
129
|
+
fresh.forEach((primitive) => {
|
|
130
|
+
recentKeys.add(`${turnId}:${escalationKind}:${primitive.kind}`);
|
|
131
|
+
if (recentKeys.size > RECENT_KEYS_CAP) recentKeys.delete(recentKeys.values().next().value);
|
|
132
|
+
});
|
|
133
|
+
return { count: dispatched.length, ids: dispatched.map((escalation) => escalation.eventId) };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { dispatch };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = {
|
|
140
|
+
createDispatcherService,
|
|
141
|
+
dispatcherService: createDispatcherService(),
|
|
142
|
+
};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
const { getEscalationDraft } = require('../config/subAgentsConfig');
|
|
2
|
+
|
|
3
|
+
const { FORMULARY_VERSION, TREATMENT_FORMULARY } = require('../protocols/treatmentFormulary');
|
|
4
|
+
|
|
5
|
+
const { createLLMProvider } = require('../providers/createLLMProvider');
|
|
6
|
+
|
|
7
|
+
const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
|
|
8
|
+
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
9
|
+
|
|
10
|
+
const { getEscalationContext } = require('../../services/escalationContextService');
|
|
11
|
+
|
|
12
|
+
const { normalizedKeyOf } = require('../../utils/coercionUtils');
|
|
13
|
+
const { logger } = require('../../utils/logger');
|
|
14
|
+
const { arrayArg, safeParse } = require('../../utils/jsonUtils');
|
|
15
|
+
const { withTiming } = require('../../utils/tracingDecorator');
|
|
16
|
+
|
|
17
|
+
const { crossSymptomIssues, drugsNamedIn, unproposedDrugsIn, validateProposal } = require('./treatmentProposalService');
|
|
18
|
+
|
|
19
|
+
const CONVERSATION_TURNS = 40;
|
|
20
|
+
const TRIAGE_LIMIT = 3;
|
|
21
|
+
const CALL_LOG_LIMIT = 10;
|
|
22
|
+
|
|
23
|
+
const TECHNICAL_TOKEN = /\b(urgentIfPositive|blocksDrug|null)\b|\b[a-z]+_\w+|\\n/i;
|
|
24
|
+
|
|
25
|
+
const trimmed = (value) => String(value ?? '').trim();
|
|
26
|
+
|
|
27
|
+
function withholds(sections) {
|
|
28
|
+
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(trimmed).filter(Boolean);
|
|
29
|
+
return flagsByStatus(sections).present.length > 0 || modifiers.length > 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function settleProposal(parsed) {
|
|
33
|
+
const raw = parsed?.treatmentProposal;
|
|
34
|
+
const items = Array.isArray(raw?.items) ? raw.items : [];
|
|
35
|
+
const stated = trimmed(parsed?.proposalWithheldReason);
|
|
36
|
+
const conduct = stated && !drugsNamedIn(stated).length ? stated : null;
|
|
37
|
+
if (withholds(parsed)) return { proposal: null, conduct, strippedItems: items.length };
|
|
38
|
+
if (!items.length) return { proposal: null, conduct, strippedItems: 0 };
|
|
39
|
+
|
|
40
|
+
const conditions = Array.isArray(raw.conditions) ? raw.conditions : [];
|
|
41
|
+
const ruledOut = Array.isArray(raw.ruledOut) ? raw.ruledOut : [];
|
|
42
|
+
const proposal = { symptom: raw.symptom, items, conditions, ruledOut };
|
|
43
|
+
const { valid, issues } = validateProposal(proposal, { conditions, ruledOut });
|
|
44
|
+
return valid ? { proposal, conduct, strippedItems: 0 } : { invalid: issues };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const textList = (value) => (Array.isArray(value) ? value.map(trimmed).filter(Boolean) : []);
|
|
48
|
+
|
|
49
|
+
function suggestCallOf(value) {
|
|
50
|
+
if (typeof value?.value !== 'boolean') return null;
|
|
51
|
+
return { value: value.value, reason: trimmed(value.reason) || null };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
|
|
55
|
+
const conversation = Array.isArray(context?.conversation)
|
|
56
|
+
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
57
|
+
: context?.conversation ?? null;
|
|
58
|
+
|
|
59
|
+
const triages = Array.isArray(context?.triages)
|
|
60
|
+
? context.triages.slice(0, TRIAGE_LIMIT)
|
|
61
|
+
: context?.triages ?? null;
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
protocolVersion: FORMULARY_VERSION,
|
|
65
|
+
protocol,
|
|
66
|
+
alarms,
|
|
67
|
+
agentCharacterization,
|
|
68
|
+
patient: {
|
|
69
|
+
clinicalContext: context?.agentContext ?? null,
|
|
70
|
+
conversation,
|
|
71
|
+
triages,
|
|
72
|
+
carePlan: context?.carePlan ?? null,
|
|
73
|
+
history: context?.history ?? null,
|
|
74
|
+
},
|
|
75
|
+
call: callLogs.slice(-CALL_LOG_LIMIT).map((log) => ({
|
|
76
|
+
outcome: log?.outcome ?? null,
|
|
77
|
+
notes: trimmed(log?.notes) || null,
|
|
78
|
+
calledAt: log?.calledAt ?? null,
|
|
79
|
+
})),
|
|
80
|
+
sectionsUnavailable: context?.degradedSections ?? [],
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function draftProvider() {
|
|
85
|
+
try {
|
|
86
|
+
return createLLMProvider({ variant: 'anthropic' });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
logger.warn('[escalationDraft] no provider available; not generating', { error: error.message });
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const MAX_URGENT_FLAGS = 2;
|
|
94
|
+
|
|
95
|
+
// The model does not always keep to two grave flags per symptom. Confirmed flags keep the mark first, then the pending ones the
|
|
96
|
+
// previous draft already held (so their wait keeps running when the model reorders them), then the rest in its order.
|
|
97
|
+
function capUrgentFlags(block, held) {
|
|
98
|
+
const urgent = (Array.isArray(block?.redFlags) ? block.redFlags : []).filter((flag) => flag?.urgentIfPositive === true);
|
|
99
|
+
if (urgent.length <= MAX_URGENT_FLAGS) return block;
|
|
100
|
+
const rank = (flag) => {
|
|
101
|
+
if (flag.present === true) return 0;
|
|
102
|
+
if (flag.present === false) return 3;
|
|
103
|
+
return held.has(normalizedKeyOf(flag.flag)) ? 1 : 2;
|
|
104
|
+
};
|
|
105
|
+
const kept = new Set([...urgent].sort((a, b) => rank(a) - rank(b)).slice(0, MAX_URGENT_FLAGS));
|
|
106
|
+
return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function generateEscalationDraft({
|
|
110
|
+
code, callLogs = [], alarms = [], agentCharacterization = null, heldUrgentFlags = [], provider, trace = null, reviewId = null, now = Date.now(),
|
|
111
|
+
} = {}) {
|
|
112
|
+
const { presetId } = await getEscalationDraft();
|
|
113
|
+
const llm = provider ?? draftProvider();
|
|
114
|
+
|
|
115
|
+
if (!presetId || !llm?.runStructured) {
|
|
116
|
+
return { completed: false, configured: false, reason: 'escalation draft generation is not configured' };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const context = await getEscalationContext({ code, now });
|
|
120
|
+
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms, agentCharacterization });
|
|
121
|
+
|
|
122
|
+
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
123
|
+
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
124
|
+
// its client — so every exit reports `attempted`, meaning a run happened and ended this way, and
|
|
125
|
+
// never that the context was certainly disclosed. Over-recording an attempt is the safe direction
|
|
126
|
+
// for an audit trail; missing a real disclosure is not.
|
|
127
|
+
let result;
|
|
128
|
+
let durationMs;
|
|
129
|
+
try {
|
|
130
|
+
({ result, durationMs } = await withTiming(() => llm.runStructured({
|
|
131
|
+
presetId,
|
|
132
|
+
input: [{ role: 'user', content: JSON.stringify(input) }],
|
|
133
|
+
metadata: { generator: 'escalation-draft', reviewId: reviewId ?? undefined },
|
|
134
|
+
})));
|
|
135
|
+
} catch (error) {
|
|
136
|
+
logger.error('[escalationDraft] the provider failed', { error: error.message, stack: error.stack, reviewId });
|
|
137
|
+
return { completed: false, attempted: true, reason: 'the model could not be reached' };
|
|
138
|
+
}
|
|
139
|
+
trace?.addSubCall({ response: result, durationMs, presetId });
|
|
140
|
+
|
|
141
|
+
if (result?.status && result.status !== 'completed') {
|
|
142
|
+
logger.warn('[escalationDraft] generation did not complete', { status: result.status, reviewId });
|
|
143
|
+
return { completed: false, attempted: true, reason: `generation incomplete: status=${result.status}` };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// From here on a failure is the model's answer being refused, not the model being unreachable:
|
|
147
|
+
// `rejected` tells the caller that asking again right away is likely to succeed.
|
|
148
|
+
const parsed = safeParse(readStructuredText(result), null);
|
|
149
|
+
const patientMessage = trimmed(parsed?.patientMessage);
|
|
150
|
+
// The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
|
|
151
|
+
const held = new Set(heldUrgentFlags.map(normalizedKeyOf));
|
|
152
|
+
const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(block, held));
|
|
153
|
+
if (!blocks.length) {
|
|
154
|
+
const shape = parsed.symptoms;
|
|
155
|
+
logger.warn('[escalationDraft] generation returned a malformed symptom list', {
|
|
156
|
+
reviewId,
|
|
157
|
+
symptomsType: Array.isArray(shape) ? 'array' : typeof shape,
|
|
158
|
+
symptomsLength: Array.isArray(shape) || typeof shape === 'string' ? shape.length : null,
|
|
159
|
+
});
|
|
160
|
+
return { completed: false, attempted: true, rejected: true, reason: 'the model returned a malformed symptoms list' };
|
|
161
|
+
}
|
|
162
|
+
if (parsed?.symptoms !== undefined && blocks.some((block) => !trimmed(block?.symptom))) {
|
|
163
|
+
logger.warn('[escalationDraft] a symptom block came without its symptom', { reviewId });
|
|
164
|
+
return { completed: false, attempted: true, rejected: true, reason: 'the model returned a symptom block without its symptom' };
|
|
165
|
+
}
|
|
166
|
+
if (blocks.some((block) => !trimmed(block?.characterizationSummary))) {
|
|
167
|
+
logger.warn('[escalationDraft] generation did not return the sectioned doctor draft', { reviewId });
|
|
168
|
+
return { completed: false, attempted: true, rejected: true, reason: 'the model did not return the sectioned doctor draft (characterizationSummary missing)' };
|
|
169
|
+
}
|
|
170
|
+
const settled = blocks.map((block) => ({ block, ...settleProposal(block) }));
|
|
171
|
+
const proposals = settled.map((entry) => entry.proposal).filter(Boolean);
|
|
172
|
+
|
|
173
|
+
const issues = settled.flatMap((entry) => entry.invalid ?? []);
|
|
174
|
+
if (!issues.length) issues.push(...crossSymptomIssues(proposals));
|
|
175
|
+
const isConfirmed = ({ block, proposal }) => {
|
|
176
|
+
const { drugSafety, urgent } = flagsByStatus(block);
|
|
177
|
+
return proposal && !drugSafety.length && !urgent.length;
|
|
178
|
+
};
|
|
179
|
+
const confirmed = settled.filter(isConfirmed).map((entry) => entry.proposal);
|
|
180
|
+
const patientDrugs = unproposedDrugsIn(patientMessage, confirmed);
|
|
181
|
+
if (!issues.length && patientDrugs.length) {
|
|
182
|
+
issues.push(`el mensaje al paciente menciona ${patientDrugs.join(', ')}, que no está en la propuesta de tratamiento`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (issues.length) {
|
|
186
|
+
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues });
|
|
187
|
+
return { completed: false, attempted: true, rejected: true, reason: `the treatment proposal broke the formulary rules: ${issues.join('; ')}` };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const draft = {
|
|
191
|
+
shared: parsed,
|
|
192
|
+
symptoms: settled.map(({ block, proposal, conduct }) => ({ sections: block, proposal, conduct })),
|
|
193
|
+
};
|
|
194
|
+
const doctorText = composeDoctorBody({ ...draft, alarm: alarms[alarms.length - 1] ?? null });
|
|
195
|
+
|
|
196
|
+
if (!doctorText || !patientMessage) {
|
|
197
|
+
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
198
|
+
return { completed: false, attempted: true, rejected: true, reason: 'the model returned no usable text' };
|
|
199
|
+
}
|
|
200
|
+
// The token goes into the reason because the audit log keeps the reason: it says which prompt rule leaked.
|
|
201
|
+
const leaked = TECHNICAL_TOKEN.exec(`${composeDoctorBody({ ...draft, alarm: null })}\n${patientMessage}`)?.[0].slice(0, 40);
|
|
202
|
+
if (leaked) {
|
|
203
|
+
logger.warn('[escalationDraft] generation leaked a technical token into the text', { reviewId, token: leaked });
|
|
204
|
+
return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const urgentPresent = [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgentPresent))];
|
|
208
|
+
// A grave flag the patient confirmed is enough for the doctor, whatever else is still pending.
|
|
209
|
+
const sufficientForDoctor = urgentPresent.length ? true : (typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null);
|
|
210
|
+
return {
|
|
211
|
+
completed: true,
|
|
212
|
+
attempted: true,
|
|
213
|
+
doctorText,
|
|
214
|
+
patientMessage,
|
|
215
|
+
protocolVersion: FORMULARY_VERSION,
|
|
216
|
+
keyQuestions: textList(parsed?.keyQuestions),
|
|
217
|
+
unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
|
|
218
|
+
urgentUnassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgent))],
|
|
219
|
+
unobtainableRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unobtainable))],
|
|
220
|
+
urgentPresentRedFlags: urgentPresent,
|
|
221
|
+
missingCharacterization: textList(parsed?.missingCharacterization),
|
|
222
|
+
sufficientForDoctor,
|
|
223
|
+
blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
|
|
224
|
+
suggestCall: suggestCallOf(parsed?.suggestCall),
|
|
225
|
+
sectionsUnavailable: context.degradedSections ?? [],
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
module.exports = { generateEscalationDraft, buildDraftInput };
|