@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,471 @@
|
|
|
1
|
+
const { randomUUID } = require('crypto');
|
|
2
|
+
|
|
3
|
+
const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
|
|
4
|
+
const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
|
|
5
|
+
const { isShadowRun } = require('../helpers/shadowHelper');
|
|
6
|
+
const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
|
|
7
|
+
const { dispatcherService } = require('../services/dispatcherService');
|
|
8
|
+
const { armEscalationNet } = require('../services/contingencyDispatchService');
|
|
9
|
+
const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
10
|
+
const { escalationAssessmentLive, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
|
|
11
|
+
const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
|
|
12
|
+
const { URGENCY_RANK } = require('../../models/escalationReviewModel');
|
|
13
|
+
const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
14
|
+
const { logger } = require('../../utils/logger');
|
|
15
|
+
|
|
16
|
+
const FEVER_RUBRIC_STAT = 'neutropenia febril CON inestabilidad, fiebre ≥38.0 °C en la ventana de quimioterapia descrita en la regla de fiebre,';
|
|
17
|
+
|
|
18
|
+
const FEVER_RUBRIC_ASAP = 'riesgo de infección sin fiebre ≥38.0 °C en esa ventana (p. ej. 37.5–37.9 °C con el paciente bien),';
|
|
19
|
+
|
|
20
|
+
const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxic chemotherapy (or a hematologic cancer, transplant, known neutropenia), any fever within 4 weeks of CAR-T or during bispecific step-up dosing, or sepsis signs with or without fever — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message; unknown date on chemo counts as within the window. Fever 37.5–37.9 °C in that window with the patient well is `asap`: remeasure in 30–60 min. ';
|
|
21
|
+
|
|
22
|
+
const definition = {
|
|
23
|
+
'name': 'reportMedicalEscalation',
|
|
24
|
+
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go and asks nothing. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias outside a must-go `stat`). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
25
|
+
'strict': true,
|
|
26
|
+
'parameters': {
|
|
27
|
+
'type': 'object',
|
|
28
|
+
'properties': {
|
|
29
|
+
'urgency_level': {
|
|
30
|
+
'type': 'string',
|
|
31
|
+
'enum': [
|
|
32
|
+
'stat',
|
|
33
|
+
'asap',
|
|
34
|
+
'urgent',
|
|
35
|
+
'routine'
|
|
36
|
+
],
|
|
37
|
+
'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo, anafilaxia confirmada (hinchazón de lengua o garganta, dificultad para tragar, respirar o hablar, o ronchas en todo el cuerpo con mareo), choque (piel fría y sudorosa, manchada o grisácea junto con mareo al pararse, mucha debilidad, corazón acelerado o casi no orinar). Cualquier dato confirmado de la lista de ir sí o sí (descrita en la descripción de la herramienta, incluida la posible compresión medular aunque venga en horas o días) es `stat`, nunca `asap`.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias (salvo que una instrucción interna del sistema lo indique); el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
|
|
38
|
+
},
|
|
39
|
+
'patient_check_in': {
|
|
40
|
+
'anyOf': [
|
|
41
|
+
{
|
|
42
|
+
'type': 'string',
|
|
43
|
+
'description': 'Nullable. The check-in this patient receives ONLY IF they go silent for hours after this escalation — the safety net writes to them again so the thread is not lost. Write it now, for delivery later: in their voice and language, short, warm, asking how they are and how the symptom has evolved since. Never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did. Reference what they told you in their own words. NO diagnosis, NO grades or CTCAE terms, NO internal phrasing — they never see `details`. Always send the key: pass `null` when you have nothing better than the neutral fallback, which is what gets used then — a bad check-in is worse than none.'
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
'type': 'null'
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
},
|
|
50
|
+
'urgency_justification': {
|
|
51
|
+
'type': 'string',
|
|
52
|
+
'description': 'Por qué ESTE nivel — y explícitamente por qué no el inmediato superior ni el inferior (qué dato objetivo define el tier). Es el registro auditable de la decisión. Una o dos frases. INTERNO; el paciente nunca lo ve. '
|
|
53
|
+
+ MEDICATION_NAMING_RULE
|
|
54
|
+
},
|
|
55
|
+
'details': {
|
|
56
|
+
'type': 'object',
|
|
57
|
+
'description': 'Structured clinical payload for the team. All fields are for INTERNAL review — never surfaced to the patient. '
|
|
58
|
+
+ MEDICATION_NAMING_RULE,
|
|
59
|
+
'properties': {
|
|
60
|
+
'category': {
|
|
61
|
+
'anyOf': [
|
|
62
|
+
{
|
|
63
|
+
'type': 'string',
|
|
64
|
+
'enum': [
|
|
65
|
+
'febrile_neutropenia',
|
|
66
|
+
'neuro_constellation',
|
|
67
|
+
'spinal_cord_compression',
|
|
68
|
+
'treatment_concern',
|
|
69
|
+
'persistent_symptom_72h',
|
|
70
|
+
'stale_clinical_context'
|
|
71
|
+
],
|
|
72
|
+
'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: fiebre o sospecha de infección en ventana de quimioterapia.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: déficit agudo — no puede caminar o mantenerse en pie, pérdida de esfínteres, debilidad bilateral de piernas.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
'type': 'null'
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
},
|
|
79
|
+
'symptom': {
|
|
80
|
+
'type': 'string',
|
|
81
|
+
'description': 'Síntoma o cluster principal, con temporalidad confirmada. Un grado que escribas aquí se lee como confirmado: si tu propia `possible_range` no se cierra en un solo grado, nombra el rango entero y el dato que lo estrecharía — «Disnea G2–G3; G3 no confirmado: sin disnea en reposo, SpO2 pendiente» — nunca sólo el extremo alto.'
|
|
82
|
+
},
|
|
83
|
+
'evidence_quote': {
|
|
84
|
+
'type': 'string',
|
|
85
|
+
'description': 'Cita textual del paciente que sustenta la escalación.'
|
|
86
|
+
},
|
|
87
|
+
'indicators': {
|
|
88
|
+
'anyOf': [
|
|
89
|
+
{
|
|
90
|
+
'type': 'array',
|
|
91
|
+
'items': {
|
|
92
|
+
'type': 'string'
|
|
93
|
+
},
|
|
94
|
+
'description': 'Indicadores del catálogo (e.g. \'fever_on_chemo\', \'neuro_constellation\').'
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
'type': 'null'
|
|
98
|
+
}
|
|
99
|
+
]
|
|
100
|
+
},
|
|
101
|
+
'suspected_condition': {
|
|
102
|
+
'anyOf': [
|
|
103
|
+
{
|
|
104
|
+
'type': 'string',
|
|
105
|
+
'description': 'Sospecha operativa interna para triage. NUNCA se menciona al paciente.'
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
'type': 'null'
|
|
109
|
+
}
|
|
110
|
+
]
|
|
111
|
+
},
|
|
112
|
+
'recommended_action': {
|
|
113
|
+
'anyOf': [
|
|
114
|
+
{
|
|
115
|
+
'type': 'string',
|
|
116
|
+
'description': 'Acción recomendada para el equipo. Dirígela al equipo tratante — no le asignes la decisión a un médico concreto salvo que sea el que aparece como `Médico tratante` en el contexto clínico. Nombrar a otros clínicos está bien cuando es para decir qué hicieron y cuándo (quién realizó un procedimiento, quién dejó una indicación): eso es contexto, no destinatario.'
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
'type': 'null'
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
'required': [
|
|
125
|
+
'category',
|
|
126
|
+
'symptom',
|
|
127
|
+
'evidence_quote',
|
|
128
|
+
'indicators',
|
|
129
|
+
'suspected_condition',
|
|
130
|
+
'recommended_action'
|
|
131
|
+
],
|
|
132
|
+
'additionalProperties': false
|
|
133
|
+
},
|
|
134
|
+
'reasoning': auditReasoningSchema(),
|
|
135
|
+
},
|
|
136
|
+
'required': [
|
|
137
|
+
'urgency_level',
|
|
138
|
+
'patient_check_in',
|
|
139
|
+
'urgency_justification',
|
|
140
|
+
'details',
|
|
141
|
+
'reasoning'
|
|
142
|
+
],
|
|
143
|
+
'additionalProperties': false
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const nullable = (schema) => ({ 'anyOf': [schema, { 'type': 'null' }] });
|
|
148
|
+
const nullableEnum = (values) => nullable({ 'type': 'string', 'enum': values });
|
|
149
|
+
|
|
150
|
+
const MODE_PROPERTY = {
|
|
151
|
+
'type': 'string',
|
|
152
|
+
'enum': ['new', 'update'],
|
|
153
|
+
'description': '`new`: primer aviso de este episodio. `update`: agrega lo nuevo a la escalación que sigue abierta para este paciente, sin generar otro aviso al equipo si el nivel no sube. El nivel aplicado es el mayor entre el abierto y el que pides: uno menor no baja la escalación, queda registrado como sugerencia para el equipo. Usa `update` para sumar lo que respondió el paciente y para subir el nivel en cuanto un dato nuevo haga plausible algo más grave.',
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
|
|
157
|
+
|
|
158
|
+
// with the timer the fever rule sends to urgencias only from `stat`, like every other case
|
|
159
|
+
const FEVER_SIGNS = 'Outside a must-go `stat` and the fever rule, no warning signs';
|
|
160
|
+
const FEVER_SIGNS_TIMER = 'Outside a must-go `stat`, no warning signs';
|
|
161
|
+
const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
|
|
162
|
+
const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
|
|
163
|
+
|
|
164
|
+
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid, or ≤36.0 °C with malaise, chills or shivering — is `asap` with `category: febrile_neutropenia`. A low reading (≤36.0 °C) on its own is not fever: ask for an oral re-measure before escalating; still ≤36.0 °C with no other symptom is `urgent`, confirmed ≤35.0 °C is `asap`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
|
|
165
|
+
|
|
166
|
+
const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
|
|
167
|
+
|
|
168
|
+
const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o ≤36.0 °C con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
|
|
169
|
+
|
|
170
|
+
const CLINICAL_ASSESSMENT_PROPERTY = nullable({
|
|
171
|
+
'type': 'object',
|
|
172
|
+
'description': 'Tu razonamiento clínico, estructurado para auditoría. Todos los campos aceptan `null`. No cambia el nivel: el nivel lo decides tú en `urgency_level`.',
|
|
173
|
+
'properties': {
|
|
174
|
+
'serious_hypotheses': nullable({
|
|
175
|
+
'type': 'array',
|
|
176
|
+
'items': {
|
|
177
|
+
'type': 'object',
|
|
178
|
+
'properties': {
|
|
179
|
+
'label': { 'type': 'string' },
|
|
180
|
+
'status': { 'type': 'string', 'enum': ['ruled_out', 'not_ruled_out', 'supported', 'unknown'] },
|
|
181
|
+
'key_evidence': nullable({ 'type': 'string' }),
|
|
182
|
+
},
|
|
183
|
+
'required': ['label', 'status', 'key_evidence'],
|
|
184
|
+
'additionalProperties': false,
|
|
185
|
+
},
|
|
186
|
+
'description': 'Cuadros graves que consideraste y en qué quedaron.',
|
|
187
|
+
}),
|
|
188
|
+
'known_explanation': nullable({
|
|
189
|
+
'type': 'object',
|
|
190
|
+
'properties': {
|
|
191
|
+
'present': nullable({ 'type': 'boolean' }),
|
|
192
|
+
'plan_in_course': nullable({ 'type': 'boolean' }),
|
|
193
|
+
'what': nullable({ 'type': 'string' }),
|
|
194
|
+
},
|
|
195
|
+
'required': ['present', 'plan_in_course', 'what'],
|
|
196
|
+
'additionalProperties': false,
|
|
197
|
+
'description': 'Si el síntoma tiene una explicación conocida (cirugía, procedimiento, efecto esperado) y si ya hay un manejo indicado.',
|
|
198
|
+
}),
|
|
199
|
+
'response_to_prior_management': nullableEnum(['complete', 'partial', 'none', 'worse', 'not_applicable', 'unknown']),
|
|
200
|
+
'trajectory': nullableEnum(['better', 'same', 'worse', 'unknown']),
|
|
201
|
+
'temporality': nullableEnum(['current', 'recent_resolved', 'past', 'unknown']),
|
|
202
|
+
'missing_to_rule_out': nullable({ 'type': 'array', 'items': { 'type': 'string' }, 'description': 'Lo que falta preguntar para descartar lo grave.' }),
|
|
203
|
+
'characterization_incomplete': nullable({ 'type': 'boolean', 'description': '`true` si el paciente dejó de responder antes de completar la caracterización.' }),
|
|
204
|
+
},
|
|
205
|
+
'required': ['serious_hypotheses', 'known_explanation', 'response_to_prior_management', 'trajectory', 'temporality', 'missing_to_rule_out', 'characterization_incomplete'],
|
|
206
|
+
'additionalProperties': false,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
function liveDefinition() {
|
|
210
|
+
const updateMode = escalationUpdateModeLive();
|
|
211
|
+
const assessment = escalationAssessmentLive();
|
|
212
|
+
const feverTimer = feverPatientTimerLive();
|
|
213
|
+
if (!updateMode && !assessment && !feverTimer) return definition;
|
|
214
|
+
const live = structuredClone(definition);
|
|
215
|
+
const { properties, required } = live.parameters;
|
|
216
|
+
if (updateMode) {
|
|
217
|
+
live.description += MODE_DESCRIPTION;
|
|
218
|
+
properties.mode = MODE_PROPERTY;
|
|
219
|
+
required.push('mode');
|
|
220
|
+
}
|
|
221
|
+
if (assessment) {
|
|
222
|
+
properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
|
|
223
|
+
properties.details.required.push('clinical_assessment');
|
|
224
|
+
}
|
|
225
|
+
if (feverTimer) {
|
|
226
|
+
live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER).replace(FEVER_SIGNS, FEVER_SIGNS_TIMER).replace(FEVER_URGENCIAS, FEVER_URGENCIAS_TIMER);
|
|
227
|
+
properties.urgency_level.description = properties.urgency_level.description
|
|
228
|
+
.replace(FEVER_RUBRIC_STAT, FEVER_RUBRIC_STAT_TIMER)
|
|
229
|
+
.replace(FEVER_RUBRIC_ASAP, FEVER_RUBRIC_ASAP_TIMER);
|
|
230
|
+
}
|
|
231
|
+
return live;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const yesNo = (value) => (value === true ? 'sí' : value === false ? 'no' : null);
|
|
235
|
+
|
|
236
|
+
function knownExplanationNote(known) {
|
|
237
|
+
if (!isPlainObject(known)) return '';
|
|
238
|
+
const parts = [
|
|
239
|
+
yesNo(known.present) && `presente: ${yesNo(known.present)}`,
|
|
240
|
+
known.what,
|
|
241
|
+
yesNo(known.plan_in_course) && `manejo en curso: ${yesNo(known.plan_in_course)}`,
|
|
242
|
+
].filter(Boolean);
|
|
243
|
+
return parts.length ? `Explicación conocida: ${parts.join(', ')}` : '';
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function assessmentNote(assessment) {
|
|
247
|
+
if (!isPlainObject(assessment)) return '';
|
|
248
|
+
const hypotheses = (Array.isArray(assessment.serious_hypotheses) ? assessment.serious_hypotheses : [])
|
|
249
|
+
.filter((hypothesis) => hypothesis?.label)
|
|
250
|
+
.map((hypothesis) => `${hypothesis.label} (${hypothesis.status || 'unknown'})`)
|
|
251
|
+
.join('; ');
|
|
252
|
+
const missing = Array.isArray(assessment.missing_to_rule_out) ? assessment.missing_to_rule_out.filter(Boolean).join('; ') : '';
|
|
253
|
+
return [
|
|
254
|
+
assessment.temporality && `Temporalidad: ${assessment.temporality}`,
|
|
255
|
+
assessment.trajectory && `Trayectoria: ${assessment.trajectory}`,
|
|
256
|
+
assessment.response_to_prior_management && `Respuesta al manejo: ${assessment.response_to_prior_management}`,
|
|
257
|
+
hypotheses && `Hipótesis graves: ${hypotheses}`,
|
|
258
|
+
knownExplanationNote(assessment.known_explanation),
|
|
259
|
+
missing && `Falta para descartar: ${missing}`,
|
|
260
|
+
yesNo(assessment.characterization_incomplete) && `Caracterización incompleta: ${yesNo(assessment.characterization_incomplete)}`,
|
|
261
|
+
].filter(Boolean).join(' · ');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function followUpNote(armed, reason) {
|
|
265
|
+
if (armed) {
|
|
266
|
+
return 'An automatic check-in is armed for this escalation: if the patient goes silent, they will be contacted again about it.';
|
|
267
|
+
}
|
|
268
|
+
if (armed === null) {
|
|
269
|
+
return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient: invite them to write again if it changes or worries them, with no time and no urgencias.';
|
|
270
|
+
}
|
|
271
|
+
if (reason === 'level_without_check_in' && escalationPatientTimerLive()) {
|
|
272
|
+
return 'This level gets no automatic check-in by design: if nobody takes the case, the patient timer sends the numbers to call. Do not add a timed fallback; keep to the instruction for this level.';
|
|
273
|
+
}
|
|
274
|
+
if (reason === 'active_net_exists') {
|
|
275
|
+
return 'No check-in was armed for THIS escalation because one is already open for this patient — it may be tracking a different concern, so do not assume the patient will be asked about this one.';
|
|
276
|
+
}
|
|
277
|
+
return `No automatic check-in is in place (${reason}). Nobody will write again on its own — make the fallback explicit in your message to the patient: invite them to write again if it changes or worries them, with no time and no urgencias.`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const CATEGORIES = definition.parameters.properties.details.properties.category.anyOf.find((v) => v.enum).enum;
|
|
281
|
+
const LEVELS = definition.parameters.properties.urgency_level.enum;
|
|
282
|
+
|
|
283
|
+
async function handler(args, context = {}) {
|
|
284
|
+
try {
|
|
285
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
286
|
+
const trace = runtime?.trace || null;
|
|
287
|
+
if (!trace) {
|
|
288
|
+
logger.error('[reportMedicalEscalation] Medical escalation dropped — no active turn trace', { patientCode: runtime?.patientCode || null });
|
|
289
|
+
return JSON.stringify({ success: false, error: 'reportMedicalEscalation requires an active turn context (trace).' });
|
|
290
|
+
}
|
|
291
|
+
const requested = (args?.urgency_level || '').trim().toLowerCase();
|
|
292
|
+
const isCoerced = !LEVELS.includes(requested);
|
|
293
|
+
const requestedLevel = isCoerced ? 'urgent' : requested;
|
|
294
|
+
const updateMode = escalationUpdateModeLive() && args?.mode === 'update';
|
|
295
|
+
const rawDetails = args?.details;
|
|
296
|
+
const parsedDetails = objectArg(rawDetails);
|
|
297
|
+
const details = parsedDetails || {};
|
|
298
|
+
const rawCategory = details.category ?? null;
|
|
299
|
+
const requestedCategory = typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory;
|
|
300
|
+
const category = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
|
|
301
|
+
const categoryCoerced = rawCategory !== null && category === null;
|
|
302
|
+
const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
|
|
303
|
+
const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
|
|
304
|
+
const detailsArg = typeof rawDetails === 'string'
|
|
305
|
+
? (parsedDetails ? (strictlyParsed ? 'decoded' : 'recovered') : 'unreadable')
|
|
306
|
+
: (parsedDetails ? 'object' : 'absent');
|
|
307
|
+
if (detailsArg === 'recovered') {
|
|
308
|
+
logger.warn('[reportMedicalEscalation] details arrived as malformed JSON and was recovered from its balanced prefix', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
|
|
309
|
+
}
|
|
310
|
+
if (detailsArg === 'unreadable') {
|
|
311
|
+
logger.error('[reportMedicalEscalation] details arrived as a string that is not valid JSON', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
|
|
312
|
+
const justification = String(args?.urgency_justification || '').trim();
|
|
313
|
+
if (justification) details.symptom = `Sin síntoma estructurado — ${justification}`;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const alarmId = randomUUID();
|
|
317
|
+
const recordsAlarm = Boolean(runtime.patientCode) && requestedLevel !== 'routine' && !isShadowRun() && runtime.isLive?.() !== false;
|
|
318
|
+
const review = recordsAlarm
|
|
319
|
+
? await recordEscalationAlarm({
|
|
320
|
+
code: runtime.patientCode,
|
|
321
|
+
alarm: {
|
|
322
|
+
alarmId,
|
|
323
|
+
urgencyLevel: requestedLevel,
|
|
324
|
+
category,
|
|
325
|
+
symptom: details.symptom || null,
|
|
326
|
+
evidenceQuote: details.evidence_quote || null,
|
|
327
|
+
suspectedCondition: details.suspected_condition || null,
|
|
328
|
+
recommendedAction: details.recommended_action || null,
|
|
329
|
+
justification: args?.urgency_justification || null,
|
|
330
|
+
indicators: (Array.isArray(details.indicators) ? details.indicators : [])
|
|
331
|
+
.filter((indicator) => typeof indicator === 'string' && indicator.trim()),
|
|
332
|
+
turnId: runtime.turnId || null,
|
|
333
|
+
...(clinicalAssessment ? { clinicalAssessment } : {}),
|
|
334
|
+
},
|
|
335
|
+
})
|
|
336
|
+
: null;
|
|
337
|
+
const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
|
|
338
|
+
const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
|
|
339
|
+
const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
|
|
340
|
+
const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
|
|
341
|
+
|
|
342
|
+
trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
|
|
343
|
+
trace.setSignals({
|
|
344
|
+
medicalEscalation: {
|
|
345
|
+
urgencyLevel,
|
|
346
|
+
category,
|
|
347
|
+
categoryCoerced,
|
|
348
|
+
requestedCategory,
|
|
349
|
+
symptom: details.symptom || null,
|
|
350
|
+
evidenceQuote: details.evidence_quote || null,
|
|
351
|
+
evidenceQuoteAnchoring: evidenceQuoteAnchoring(details.evidence_quote, trace),
|
|
352
|
+
indicators: details.indicators ?? null,
|
|
353
|
+
suspectedCondition: details.suspected_condition ?? null,
|
|
354
|
+
recommendedAction: details.recommended_action ?? null,
|
|
355
|
+
urgencyJustification: args?.urgency_justification || null,
|
|
356
|
+
reasoning: objectArg(args?.reasoning) || null,
|
|
357
|
+
coercedUrgency: isCoerced,
|
|
358
|
+
requestedUrgencyLevel: requested,
|
|
359
|
+
detailsArg,
|
|
360
|
+
...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
|
|
361
|
+
...(clinicalAssessment ? { clinicalAssessment } : {}),
|
|
362
|
+
},
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
if (runtime.turnId && runtime.patientCode && raisesOpen) {
|
|
366
|
+
try {
|
|
367
|
+
await dispatcherService.dispatch({
|
|
368
|
+
trace,
|
|
369
|
+
escalationKind: 'medical_urgent',
|
|
370
|
+
turnId: runtime.turnId,
|
|
371
|
+
patientCode: runtime.patientCode,
|
|
372
|
+
});
|
|
373
|
+
} catch (dispatchErr) {
|
|
374
|
+
logger.warn('reportMedicalEscalation dispatch failed', { message: dispatchErr?.message });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
let queued = false;
|
|
379
|
+
let netArmed = null;
|
|
380
|
+
let netReason = null;
|
|
381
|
+
|
|
382
|
+
if (runtime.patientCode) {
|
|
383
|
+
if (urgencyLevel === 'routine') {
|
|
384
|
+
const { written, duplicate } = await writeUnresolvedRequest({
|
|
385
|
+
code: runtime.patientCode,
|
|
386
|
+
trace,
|
|
387
|
+
question: details.symptom || '',
|
|
388
|
+
details: args?.urgency_justification || '',
|
|
389
|
+
category: 'medical_routine',
|
|
390
|
+
urgency: 'routine',
|
|
391
|
+
});
|
|
392
|
+
queued = written || duplicate;
|
|
393
|
+
} else {
|
|
394
|
+
let emergencyRecordId = null;
|
|
395
|
+
let merging = false;
|
|
396
|
+
queued = await recordEmergency({
|
|
397
|
+
code: runtime.patientCode,
|
|
398
|
+
trace,
|
|
399
|
+
symptom: details.symptom || '',
|
|
400
|
+
suspectedCondition: details.suspected_condition || '',
|
|
401
|
+
recommendedAction: details.recommended_action || '',
|
|
402
|
+
urgencyFhir: urgencyLevel,
|
|
403
|
+
documentation: [
|
|
404
|
+
keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
|
|
405
|
+
args?.urgency_justification || '',
|
|
406
|
+
details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
|
|
407
|
+
assessmentNote(clinicalAssessment),
|
|
408
|
+
].filter(Boolean).join('\n'),
|
|
409
|
+
anchor: anchor?.emergencyRecordId ? { recordId: anchor.emergencyRecordId, urgencyFhir: anchor.urgencyLevel } : null,
|
|
410
|
+
keepOpenRow: keptOpenLevel,
|
|
411
|
+
onRecorded: (recordId) => { emergencyRecordId = recordId; },
|
|
412
|
+
onMerging: (into) => { merging = into; },
|
|
413
|
+
});
|
|
414
|
+
if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
|
|
415
|
+
// A merge into an open row never alerts; any other failed write may have left the team without one.
|
|
416
|
+
if (review && !queued && !merging) {
|
|
417
|
+
alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
|
|
418
|
+
}
|
|
419
|
+
if (urgencyLevel !== 'routine') {
|
|
420
|
+
try {
|
|
421
|
+
const net = queued ? await armEscalationNet({
|
|
422
|
+
patientCode: runtime.patientCode,
|
|
423
|
+
urgencyLevel,
|
|
424
|
+
symptom: details.symptom || '',
|
|
425
|
+
suspectedCondition: details.suspected_condition || null,
|
|
426
|
+
checkIn: args?.patient_check_in || null,
|
|
427
|
+
trace,
|
|
428
|
+
isLive: runtime.isLive?.bind(runtime),
|
|
429
|
+
}) : { armed: false, reason: 'emergency_row_not_recorded' };
|
|
430
|
+
netArmed = Boolean(net?.armed);
|
|
431
|
+
netReason = netArmed ? null : (net?.reason || 'unknown');
|
|
432
|
+
logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
|
|
433
|
+
} catch (netErr) {
|
|
434
|
+
netArmed = false;
|
|
435
|
+
netReason = 'arm_failed';
|
|
436
|
+
logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
} else if (urgencyLevel !== 'routine') {
|
|
441
|
+
netArmed = false;
|
|
442
|
+
netReason = 'patient_context_missing';
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const data = {
|
|
446
|
+
urgency_level: urgencyLevel,
|
|
447
|
+
queued_for_team: queued,
|
|
448
|
+
safety_net_armed: netArmed,
|
|
449
|
+
safety_net_reason: netReason,
|
|
450
|
+
team_has_reviewed: false,
|
|
451
|
+
means: queued
|
|
452
|
+
? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
|
|
453
|
+
: 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
|
|
454
|
+
follow_up: followUpNote(netArmed, netReason),
|
|
455
|
+
...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
|
|
456
|
+
...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
|
|
457
|
+
...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
|
|
458
|
+
...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
|
|
459
|
+
...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
|
|
460
|
+
};
|
|
461
|
+
return JSON.stringify({ success: true, data });
|
|
462
|
+
} catch (err) {
|
|
463
|
+
return JSON.stringify({ success: false, error: err?.message || 'reportMedicalEscalation failed' });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
module.exports = {
|
|
468
|
+
definition,
|
|
469
|
+
liveDefinition,
|
|
470
|
+
handler,
|
|
471
|
+
};
|