@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,149 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
+
const { applyChatSupportReadings } = require('../services/supportLightService');
|
|
5
|
+
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
6
|
+
|
|
7
|
+
const decisionProperties = {
|
|
8
|
+
service: { type: 'string', enum: ['nutrition', 'psychology'] },
|
|
9
|
+
nutritionRisk: { type: ['string', 'null'], enum: ['green', 'yellow', 'red', 'unknown', null] },
|
|
10
|
+
psychologyRisk: { type: ['string', 'null'], enum: ['green', 'orange', 'red', 'unknown', null] },
|
|
11
|
+
disposition: { type: 'string', enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'] },
|
|
12
|
+
groupEligible: { type: 'boolean' },
|
|
13
|
+
urgentIntakeEligible: { type: 'boolean' },
|
|
14
|
+
priority: { type: 'string', enum: ['routine', 'soon', 'urgent'] },
|
|
15
|
+
confidence: { type: 'number', minimum: 0, maximum: 1 },
|
|
16
|
+
reasonCodes: { type: 'array', items: { type: 'string' }, maxItems: 20 },
|
|
17
|
+
evidence: {
|
|
18
|
+
type: 'array',
|
|
19
|
+
minItems: 1,
|
|
20
|
+
maxItems: 20,
|
|
21
|
+
items: {
|
|
22
|
+
type: 'object',
|
|
23
|
+
properties: {
|
|
24
|
+
source: { type: 'string', enum: ['chat', 'triage', 'fhir', 'airtable'] },
|
|
25
|
+
sourceId: { type: 'string' },
|
|
26
|
+
code: { type: 'string' },
|
|
27
|
+
summary: { type: ['string', 'null'] },
|
|
28
|
+
confidence: { type: ['number', 'null'], minimum: 0, maximum: 1 },
|
|
29
|
+
},
|
|
30
|
+
required: ['source', 'sourceId', 'code'],
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
safety: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
suicidalIdeation: { type: 'boolean' },
|
|
37
|
+
immediateRisk: { type: 'boolean' },
|
|
38
|
+
urgentMedicalRisk: { type: 'boolean' },
|
|
39
|
+
needsHumanConfirmation: { type: 'boolean' },
|
|
40
|
+
},
|
|
41
|
+
required: ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk', 'needsHumanConfirmation'],
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const definition = {
|
|
46
|
+
name: 'submitSupportRoutingRecommendation',
|
|
47
|
+
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. The specialty risk also updates the patient support light: a higher risk applies at once, a lower one waits for a specialist to confirm. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
48
|
+
strict: false,
|
|
49
|
+
parameters: {
|
|
50
|
+
type: 'object',
|
|
51
|
+
properties: {
|
|
52
|
+
decisions: {
|
|
53
|
+
type: 'array',
|
|
54
|
+
minItems: 1,
|
|
55
|
+
maxItems: 2,
|
|
56
|
+
items: { type: 'object', properties: decisionProperties, required: ['service', 'disposition', 'groupEligible', 'confidence', 'evidence', 'safety'] },
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
required: ['decisions'],
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function normalizedDecision(raw, turnId) {
|
|
64
|
+
const common = {
|
|
65
|
+
service: raw.service,
|
|
66
|
+
disposition: raw.disposition,
|
|
67
|
+
groupEligible: raw.groupEligible,
|
|
68
|
+
priority: raw.priority || 'routine',
|
|
69
|
+
confidence: raw.confidence,
|
|
70
|
+
reasonCodes: raw.reasonCodes || [],
|
|
71
|
+
evidence: (raw.evidence || []).map((item) => ({
|
|
72
|
+
source: 'chat',
|
|
73
|
+
sourceId: turnId,
|
|
74
|
+
code: item.code,
|
|
75
|
+
summary: item.summary ?? null,
|
|
76
|
+
confidence: item.confidence ?? null,
|
|
77
|
+
})),
|
|
78
|
+
safety: raw.safety,
|
|
79
|
+
};
|
|
80
|
+
return raw.service === 'nutrition'
|
|
81
|
+
? { ...common, nutritionRisk: raw.nutritionRisk || 'unknown', urgentIntakeEligible: raw.urgentIntakeEligible ?? false }
|
|
82
|
+
: { ...common, psychologyRisk: raw.psychologyRisk || 'unknown' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function inactiveTurn() {
|
|
86
|
+
return JSON.stringify({ success: false, error: 'support_routing_turn_inactive', data: {} });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isRuntimeLive(runtime) {
|
|
90
|
+
if (typeof runtime?.isLive !== 'function') return false;
|
|
91
|
+
try {
|
|
92
|
+
return runtime.isLive() === true;
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function handler(args = {}, context = {}) {
|
|
99
|
+
const runtime = context?.toolRuntimeContext;
|
|
100
|
+
if (!runtime?.turnId || !runtime?.patientCode || runtime.turnKind !== 'patient') {
|
|
101
|
+
return inactiveTurn();
|
|
102
|
+
}
|
|
103
|
+
if (!isRuntimeLive(runtime)) {
|
|
104
|
+
return inactiveTurn();
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const observedAt = runtime.patientInput?.observedAt;
|
|
108
|
+
if (typeof observedAt !== 'string' || Number.isNaN(new Date(observedAt).getTime())) {
|
|
109
|
+
return JSON.stringify({ success: false, error: 'support_routing_source_time_missing', data: {} });
|
|
110
|
+
}
|
|
111
|
+
const recommendation = new SupportRoutingRecommendation({
|
|
112
|
+
patientId: runtime.patientCode,
|
|
113
|
+
origin: 'chat',
|
|
114
|
+
sourceId: runtime.turnId,
|
|
115
|
+
createdAt: new Date(observedAt).toISOString(),
|
|
116
|
+
decisions: (args.decisions || []).map((decision) => normalizedDecision(decision, runtime.turnId)),
|
|
117
|
+
});
|
|
118
|
+
if (!isRuntimeLive(runtime)) return inactiveTurn();
|
|
119
|
+
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
120
|
+
const lights = isRuntimeLive(runtime)
|
|
121
|
+
? await applyChatSupportReadings(recommendation, {
|
|
122
|
+
acceptedServices: candidates.map((candidate) => candidate.service), isTurnLive: () => isRuntimeLive(runtime),
|
|
123
|
+
})
|
|
124
|
+
: [];
|
|
125
|
+
runtime.trace?.setSignals?.({
|
|
126
|
+
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
127
|
+
});
|
|
128
|
+
return JSON.stringify({
|
|
129
|
+
success: true,
|
|
130
|
+
data: {
|
|
131
|
+
accepted: true,
|
|
132
|
+
candidates: candidates.map((candidate) => ({
|
|
133
|
+
candidate_id: candidate.candidateId,
|
|
134
|
+
service: candidate.service,
|
|
135
|
+
disposition: candidate.disposition,
|
|
136
|
+
})),
|
|
137
|
+
lights,
|
|
138
|
+
invitation_sent: false,
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error instanceof ZodError) {
|
|
143
|
+
return JSON.stringify({ success: false, error: 'support_routing_schema_invalid', data: { issues: error.issues.map((issue) => ({ path: issue.path.join('.'), problem: issue.message })) } });
|
|
144
|
+
}
|
|
145
|
+
return JSON.stringify({ success: false, error: error?.message || 'support routing failed', data: {} });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
module.exports = { definition, handler };
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
const { autoResolveNets } = require('../services/contingencyDispatchService');
|
|
2
|
+
const { readSymptomCases, readClusters, storeCluster, readContingencies } = require('../../fhir');
|
|
3
|
+
const { ClusterImpression, CLUSTER_STATUSES, CONFIDENCE_LEVELS, CLINICAL_SIGNIFICANCE } = require('../../shared/dtos/ClusterImpression');
|
|
4
|
+
const { ClusterHistoryRecord } = require('../../shared/dtos/ClusterHistoryRecord');
|
|
5
|
+
const { RESOLVED_REASONS } = require('../../shared/dtos/ContingencySafetyNet');
|
|
6
|
+
const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
7
|
+
const { logger } = require('../../utils/logger');
|
|
8
|
+
|
|
9
|
+
const UPDATE_KEYS = ['add_members', 'remove_members', 'label_new', 'confidence_new', 'status_new', 'clinical_significance_new', 'relationship_model_new', 'strengthens_if_new', 'weakens_if_new'];
|
|
10
|
+
|
|
11
|
+
const definition = {
|
|
12
|
+
name: 'updateClusterHypothesis',
|
|
13
|
+
description: '**Does:** Evolves an ACTIVE cluster hypothesis — add/remove member cases, rename, re-grade confidence or clinical significance, revise the relationship model or the strengthens/weakens signals, or dissolve it. Dissolve is terminal.\n\n**Required inputs:** `cluster_id`, `transition_reason` (audit trail), `update` (an object with at least one of `add_members`, `remove_members`, `label_new`, `confidence_new`, `status_new`, `clinical_significance_new`, `relationship_model_new`, `strengthens_if_new`, `weakens_if_new`).\n\n**When to call:** when new evidence changes the cluster, or to end it (`status_new: \'dissolved\'`).\n\n**When NOT to call:** on a dissolved cluster (terminal), or to open a new cluster (use `openClusterHypothesis`).\n\n**Returns:** `cluster_id`, `what_changed` (list of applied deltas); a dissolve adds `auto_resolved_plans[]` and `cascade_errors[]` (each present only when non-empty). Fails hard on `cluster_not_found_or_wrong_patient`, `cluster_already_dissolved`, invalid vocab, `label_already_in_use`, a bad member mutation, dropping below 2 members without dissolving, or a noop.\n\n**Side effects:** re-projects the ClusterImpression and appends an \'updated\'/\'dissolved\' Provenance. On dissolve, auto-resolves any active contingency safety net linked to the cluster.',
|
|
14
|
+
strict: false,
|
|
15
|
+
parameters: {
|
|
16
|
+
type: 'object',
|
|
17
|
+
properties: {
|
|
18
|
+
cluster_id: {
|
|
19
|
+
type: 'string',
|
|
20
|
+
description: 'The cluster_id returned by openClusterHypothesis (or from getActiveSymptomLandscape.active_clusters[]).',
|
|
21
|
+
},
|
|
22
|
+
transition_reason: {
|
|
23
|
+
type: 'string',
|
|
24
|
+
description: 'Why the cluster is changing this turn (audit trail).',
|
|
25
|
+
},
|
|
26
|
+
update: {
|
|
27
|
+
type: 'object',
|
|
28
|
+
description: 'At least one mutation key: `add_members`, `remove_members`, `label_new`, `confidence_new`, `status_new` (`active`|`dissolved`), `clinical_significance_new`, `relationship_model_new`, `strengthens_if_new`, `weakens_if_new`.',
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
required: ['cluster_id', 'transition_reason', 'update'],
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const strList = (raw) => (Array.isArray(raw) ? raw.filter((s) => typeof s === 'string') : []);
|
|
36
|
+
const normLower = (v) => (typeof v === 'string' && v.trim() ? v.trim().toLowerCase() : null);
|
|
37
|
+
|
|
38
|
+
function fail(error, data = {}) {
|
|
39
|
+
return JSON.stringify({ success: false, error, data });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function runDissolveCascade(patientId, clusterId, trace = null) {
|
|
43
|
+
try {
|
|
44
|
+
const nets = await readContingencies({ patientId, clusterId });
|
|
45
|
+
return await autoResolveNets({ patientCode: patientId, nets, resolvedReason: RESOLVED_REASONS.LINKED_CLUSTER_DISSOLVED, trace });
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return { autoResolvedPlans: [], cascadeErrors: [`contingency_auto_resolve_failed: ${error?.message || error}`] };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function handler(args = {}, context = {}) {
|
|
52
|
+
try {
|
|
53
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
54
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
55
|
+
return fail('updateClusterHypothesis requires an active turn context (turnId, patientCode).');
|
|
56
|
+
}
|
|
57
|
+
const clusterId = (typeof args?.cluster_id === 'string' ? args.cluster_id : '').trim();
|
|
58
|
+
const transitionReason = (typeof args?.transition_reason === 'string' ? args.transition_reason : '').trim();
|
|
59
|
+
const update = args?.update;
|
|
60
|
+
if (!clusterId) return fail('cluster_id is required');
|
|
61
|
+
if (!transitionReason) return fail('transition_reason is required (audit trail)');
|
|
62
|
+
if (!update || typeof update !== 'object' || Array.isArray(update) || !Object.keys(update).length) {
|
|
63
|
+
return fail('update object with at least one mutation key is required');
|
|
64
|
+
}
|
|
65
|
+
const unknown = Object.keys(update).filter((k) => !UPDATE_KEYS.includes(k));
|
|
66
|
+
if (unknown.length) return fail(`unknown update keys: ${unknown.join(', ')}`, { unknown_keys: unknown });
|
|
67
|
+
|
|
68
|
+
const patientId = runtime.patientCode;
|
|
69
|
+
const cluster = (await readClusters({ patientId })).find((c) => c.clusterId === clusterId);
|
|
70
|
+
if (!cluster) return fail('cluster_not_found_or_wrong_patient', { cluster_id: clusterId });
|
|
71
|
+
if (cluster.status === 'dissolved') {
|
|
72
|
+
return fail('cluster_already_dissolved — dissolve is terminal', { cluster_id: clusterId, dissolved_at: cluster.dissolvedAt, dissolve_reason: cluster.dissolveReason });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const labelNew = 'label_new' in update ? (typeof update.label_new === 'string' ? update.label_new : '').trim() : null;
|
|
76
|
+
const confidenceNew = 'confidence_new' in update ? normLower(update.confidence_new) : null;
|
|
77
|
+
const statusNew = 'status_new' in update ? normLower(update.status_new) : null;
|
|
78
|
+
const significanceNew = 'clinical_significance_new' in update ? normLower(update.clinical_significance_new) : null;
|
|
79
|
+
const relModelNew = update.relationship_model_new;
|
|
80
|
+
const strengthensNew = update.strengthens_if_new;
|
|
81
|
+
const weakensNew = update.weakens_if_new;
|
|
82
|
+
|
|
83
|
+
if (confidenceNew !== null && !CONFIDENCE_LEVELS.includes(confidenceNew)) return fail(`invalid confidence_new. Must be one of ${CONFIDENCE_LEVELS.join(' | ')}.`, { confidence_new: confidenceNew });
|
|
84
|
+
if (statusNew !== null && !CLUSTER_STATUSES.includes(statusNew)) return fail(`invalid status_new. Must be one of ${CLUSTER_STATUSES.join(' | ')}.`, { status_new: statusNew });
|
|
85
|
+
if (significanceNew !== null && !CLINICAL_SIGNIFICANCE.includes(significanceNew)) return fail(`invalid clinical_significance_new. Must be one of ${CLINICAL_SIGNIFICANCE.join(' | ')}.`, { clinical_significance_new: significanceNew });
|
|
86
|
+
if (relModelNew !== undefined && (typeof relModelNew !== 'string' || !relModelNew.trim())) return fail('relationship_model_new must be a non-empty string');
|
|
87
|
+
|
|
88
|
+
const currentLabel = cluster.label || '';
|
|
89
|
+
if (labelNew && labelNew !== currentLabel) {
|
|
90
|
+
const clash = (await readClusters({ patientId, label: labelNew })).find((c) => c.status === 'active' && c.clusterId !== clusterId);
|
|
91
|
+
if (clash) return fail('label_already_in_use', { existing_cluster_id: clash.clusterId, label_new: labelNew });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const currentMembers = [...cluster.memberCaseIds];
|
|
95
|
+
const addMembers = [...new Set(strList(update.add_members))];
|
|
96
|
+
const removeMembers = [...new Set(strList(update.remove_members))];
|
|
97
|
+
|
|
98
|
+
const cases = await readSymptomCases({ patientId });
|
|
99
|
+
for (const caseId of addMembers) {
|
|
100
|
+
if (currentMembers.includes(caseId)) return fail('add_member_already_in_cluster', { case_id: caseId });
|
|
101
|
+
const managedSymptom = cases.find((c) => c.condition.conditionId === caseId);
|
|
102
|
+
if (!managedSymptom) return fail('add_member_not_found_or_wrong_patient', { case_id: caseId });
|
|
103
|
+
if (!OPEN_STATUSES.includes(managedSymptom.condition.clinicalStatus)) return fail('add_member_not_open', { case_id: caseId, status: managedSymptom.condition.clinicalStatus });
|
|
104
|
+
}
|
|
105
|
+
for (const caseId of removeMembers) {
|
|
106
|
+
if (!currentMembers.includes(caseId)) return fail('remove_member_not_in_cluster', { case_id: caseId });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const finalMembers = currentMembers.filter((m) => !removeMembers.includes(m)).concat(addMembers.filter((m) => !currentMembers.includes(m)));
|
|
110
|
+
const isDissolving = statusNew === 'dissolved';
|
|
111
|
+
if (!isDissolving && finalMembers.length < 2) {
|
|
112
|
+
return fail('would_leave_cluster_below_2_members — call updateClusterHypothesis again with status_new=\'dissolved\' to end the cluster instead', { would_be_members: finalMembers, n: finalMembers.length });
|
|
113
|
+
}
|
|
114
|
+
if (isDissolving && finalMembers.length === 0) {
|
|
115
|
+
return fail('would_leave_cluster_with_0_members', { cluster_id: clusterId, removed_members: removeMembers });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const changes = [];
|
|
119
|
+
if (addMembers.length) changes.push(`added_members:${addMembers.join(',')}`);
|
|
120
|
+
if (removeMembers.length) changes.push(`removed_members:${removeMembers.join(',')}`);
|
|
121
|
+
if (labelNew && labelNew !== currentLabel) changes.push(`label:${currentLabel}→${labelNew}`);
|
|
122
|
+
if (confidenceNew && confidenceNew !== cluster.confidence) changes.push(`confidence:${cluster.confidence}→${confidenceNew}`);
|
|
123
|
+
if (statusNew && statusNew !== cluster.status) changes.push(`status:${cluster.status}→${statusNew}`);
|
|
124
|
+
if (significanceNew && significanceNew !== cluster.clinicalSignificance) changes.push(`significance:${cluster.clinicalSignificance}→${significanceNew}`);
|
|
125
|
+
if (typeof relModelNew === 'string' && relModelNew.trim() !== (cluster.relationshipModel || '')) changes.push('relationship_model_updated');
|
|
126
|
+
if (Array.isArray(strengthensNew)) changes.push('strengthens_if_replaced');
|
|
127
|
+
if (Array.isArray(weakensNew)) changes.push('weakens_if_replaced');
|
|
128
|
+
if (!changes.length) return fail('noop — update produced no changes vs current state');
|
|
129
|
+
|
|
130
|
+
const now = new Date().toISOString();
|
|
131
|
+
const patch = {
|
|
132
|
+
...cluster,
|
|
133
|
+
memberCaseIds: finalMembers,
|
|
134
|
+
};
|
|
135
|
+
if (labelNew && labelNew !== currentLabel) patch.label = labelNew;
|
|
136
|
+
if (confidenceNew && confidenceNew !== cluster.confidence) patch.confidence = confidenceNew;
|
|
137
|
+
if (significanceNew && significanceNew !== cluster.clinicalSignificance) patch.clinicalSignificance = significanceNew;
|
|
138
|
+
if (typeof relModelNew === 'string' && relModelNew.trim()) patch.relationshipModel = relModelNew.trim();
|
|
139
|
+
if (Array.isArray(strengthensNew)) patch.strengthensIf = strList(strengthensNew);
|
|
140
|
+
if (Array.isArray(weakensNew)) patch.weakensIf = strList(weakensNew);
|
|
141
|
+
if (isDissolving) {
|
|
142
|
+
patch.status = 'dissolved';
|
|
143
|
+
patch.dissolvedAt = now;
|
|
144
|
+
patch.dissolveReason = transitionReason;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const patched = new ClusterImpression(patch);
|
|
148
|
+
const action = isDissolving ? 'dissolved' : 'updated';
|
|
149
|
+
const history = [new ClusterHistoryRecord({
|
|
150
|
+
clusterId,
|
|
151
|
+
turnId: runtime.turnId,
|
|
152
|
+
action,
|
|
153
|
+
changes: { items: changes },
|
|
154
|
+
transitionReason,
|
|
155
|
+
recordedAt: now,
|
|
156
|
+
})];
|
|
157
|
+
|
|
158
|
+
await storeCluster({ patientId, cluster: patched, history });
|
|
159
|
+
|
|
160
|
+
const data = { cluster_id: clusterId, what_changed: changes };
|
|
161
|
+
if (isDissolving) {
|
|
162
|
+
const cascade = await runDissolveCascade(patientId, clusterId, runtime.trace || null);
|
|
163
|
+
if (cascade.autoResolvedPlans.length) data.auto_resolved_plans = cascade.autoResolvedPlans;
|
|
164
|
+
if (cascade.cascadeErrors.length) {
|
|
165
|
+
data.cascade_errors = cascade.cascadeErrors;
|
|
166
|
+
logger.warn('updateClusterHypothesis dissolve cascade errors', { clusterId, cascadeErrors: cascade.cascadeErrors });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return JSON.stringify({ success: true, data });
|
|
170
|
+
} catch (err) {
|
|
171
|
+
return fail(err?.message || 'updateClusterHypothesis failed');
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
module.exports = {
|
|
176
|
+
definition,
|
|
177
|
+
handler,
|
|
178
|
+
};
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
const {
|
|
2
|
+
isResolutionReason, resolveCloseReason, closePatch, runCloseCascade,
|
|
3
|
+
} = require('../services/conditionCloseService');
|
|
4
|
+
const { readSymptomCases, storeSymptomCase } = require('../../fhir');
|
|
5
|
+
const { ManagedSymptom } = require('../../shared/dtos/ManagedSymptom');
|
|
6
|
+
const { logger } = require('../../utils/logger');
|
|
7
|
+
|
|
8
|
+
const definition = {
|
|
9
|
+
name: 'updateConditionStatus',
|
|
10
|
+
description: '**Does:** Transitions the lifecycle of a symptom `Condition` (FHIR `Condition.clinicalStatus`), selected via `transition`.\n\n**Required inputs:** `case_id`, `transition` (`resolve_episode` | `resolve` | `deactivate` | `reactivate`), and `reasoning` (one short sentence justifying the transition — persisted to the Condition\'s audit record). Per transition:\n- `resolve_episode`: no extra args. Current episode resolved; case → `monitoring`, current episode cleared.\n- `resolve`: the symptom ENDED (patient-confirmed or clinically established) → `resolved` + `abatement_at`.\n- `deactivate`: stop tracking WITHOUT asserting resolution. `close_reason` REQUIRED (`escalated_to_team` | `patient_transferred` | `stale_no_activity`) → `inactive`, no abatement.\n- `reactivate`: a dormant case\'s symptom RETURNED. Requires `episode_id`. Reopens the SAME Condition (→ `characterizing`; FHIR `recurrence` when it had been resolved).\n\n**When NOT to call:**\n- To start a new episode of the same term — that is `recordClinicalImpression` with `event=\'new_episode\'`, which gives the episode its own grade and arms its safety net. This tool refuses it.\n- To register a `ClinicalImpression` — that is `recordClinicalImpression`\'s job; call it separately, in an earlier round.\n- To open a case that does not exist yet — that is `openCondition`.\n\n**Parallelism with `recordClinicalImpression`:** `resolve_episode`, `resolve` and `deactivate` move the case out of `characterizing`, which is the status `recordClinicalImpression` requires. Record the impression carrying the closing read in an EARLIER round; a parallel impression in the same round will fail.\n\n**Returns:** `case_id` + new `status`; `resolve`/`deactivate` add `abatement_at` (null on deactivate) and cascade outcomes — `auto_resolved_plans[]`, `pruned_clusters[]`, `dissolved_clusters[]`, `cascade_errors[]` (each present only when non-empty); `reactivate` adds `is_recurrence` + `recurrence_count`.\n\n**Side effects:** writes the lifecycle patch to the `Condition`. On `resolve`/`deactivate`, auto-resolves any active contingency safety net linked to the case and prunes the case from any active cluster (auto-dissolving a cluster that drops below 2 members, which also auto-resolves that cluster\'s own safety net).',
|
|
11
|
+
strict: false,
|
|
12
|
+
parameters: {
|
|
13
|
+
type: 'object',
|
|
14
|
+
properties: {
|
|
15
|
+
case_id: {
|
|
16
|
+
type: 'string',
|
|
17
|
+
description: 'The case_id whose Condition lifecycle changes (from openCondition or getActiveSymptomLandscape).',
|
|
18
|
+
},
|
|
19
|
+
transition: {
|
|
20
|
+
type: 'string',
|
|
21
|
+
enum: ['resolve_episode', 'resolve', 'deactivate', 'reactivate'],
|
|
22
|
+
description: '`resolve_episode`: current episode resolved (→ monitoring). `resolve`: symptom ended (→ resolved + abatement). `deactivate`: stop tracking without resolution (→ inactive, requires close_reason). `reactivate`: dormant case returned (→ characterizing).',
|
|
23
|
+
},
|
|
24
|
+
reasoning: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
description: 'Required. One short sentence justifying this lifecycle transition — persisted to the Condition\'s audit record.',
|
|
27
|
+
},
|
|
28
|
+
episode_id: {
|
|
29
|
+
type: 'string',
|
|
30
|
+
description: 'Required for reactivate (the new bout\'s intake episode).',
|
|
31
|
+
},
|
|
32
|
+
close_reason: {
|
|
33
|
+
type: 'string',
|
|
34
|
+
description: 'Required for deactivate. One of escalated_to_team | patient_transferred | stale_no_activity.',
|
|
35
|
+
},
|
|
36
|
+
temporality: {
|
|
37
|
+
type: 'string',
|
|
38
|
+
description: 'Optional. Pass only when temporality changed with this transition.',
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
required: ['case_id', 'transition', 'reasoning'],
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const TRANSITIONS = definition.parameters.properties.transition.enum;
|
|
46
|
+
|
|
47
|
+
function fail(error, data = {}) {
|
|
48
|
+
return JSON.stringify({ success: false, error, data });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function returnedStatus(condition) {
|
|
52
|
+
const { clinicalStatus } = condition;
|
|
53
|
+
if (clinicalStatus === 'closed') {
|
|
54
|
+
return isResolutionReason(condition.closeReason) ? 'resolved' : 'inactive';
|
|
55
|
+
}
|
|
56
|
+
return clinicalStatus;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isDormant(condition) {
|
|
60
|
+
return ['closed', 'resolved', 'inactive'].includes(condition.clinicalStatus);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function toManaged(existing, conditionPatch) {
|
|
64
|
+
const condition = { ...existing.condition, ...conditionPatch };
|
|
65
|
+
return new ManagedSymptom({
|
|
66
|
+
condition,
|
|
67
|
+
latestAssessment: existing.latestAssessment,
|
|
68
|
+
priorAssessments: existing.priorAssessments,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function applyResolveEpisode(existing, reasoning, args) {
|
|
73
|
+
if (existing.condition.clinicalStatus !== 'characterizing') {
|
|
74
|
+
return fail('resolve_episode requires status=characterizing (there must be an active episode to resolve).', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus });
|
|
75
|
+
}
|
|
76
|
+
const patch = { clinicalStatus: 'monitoring', currentEpisodeId: null, lastTransitionReason: reasoning };
|
|
77
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
78
|
+
return toManaged(existing, patch);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function applyDormant(existing, reasoning, args, resolving) {
|
|
82
|
+
if (isDormant(existing.condition)) {
|
|
83
|
+
return fail('case_already_dormant', { case_id: existing.condition.conditionId, status: returnedStatus(existing.condition), close_reason: existing.condition.closeReason });
|
|
84
|
+
}
|
|
85
|
+
const close = resolveCloseReason(args?.close_reason, { resolving, caseId: existing.condition.conditionId });
|
|
86
|
+
if (close.error) return fail(close.error.error, close.error.data);
|
|
87
|
+
const patch = closePatch({ closeReason: close.closeReason, resolving: close.resolving, reasoning });
|
|
88
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
89
|
+
return toManaged(existing, patch);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function applyReactivate(existing, reasoning, args) {
|
|
93
|
+
if (!isDormant(existing.condition)) {
|
|
94
|
+
return fail('reactivate requires a dormant case (resolved/inactive). This case is already open — record the new bout with recordClinicalImpression(event=\'new_episode\').', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus });
|
|
95
|
+
}
|
|
96
|
+
const episodeId = (typeof args?.episode_id === 'string' ? args.episode_id : '').trim();
|
|
97
|
+
if (!episodeId) return fail('reactivate requires episode_id');
|
|
98
|
+
const hasBeenResolved = existing.condition.clinicalStatus === 'resolved'
|
|
99
|
+
|| (existing.condition.clinicalStatus === 'closed' && isResolutionReason(existing.condition.closeReason));
|
|
100
|
+
const evidenceEpisodeIds = existing.condition.evidenceEpisodeIds.includes(episodeId)
|
|
101
|
+
? [...existing.condition.evidenceEpisodeIds]
|
|
102
|
+
: [...existing.condition.evidenceEpisodeIds, episodeId];
|
|
103
|
+
const patch = {
|
|
104
|
+
clinicalStatus: 'characterizing',
|
|
105
|
+
abatementAt: null,
|
|
106
|
+
closeReason: null,
|
|
107
|
+
currentEpisodeId: episodeId,
|
|
108
|
+
evidenceEpisodeIds,
|
|
109
|
+
reactivatedAt: new Date().toISOString(),
|
|
110
|
+
lastTransitionReason: reasoning,
|
|
111
|
+
};
|
|
112
|
+
if (hasBeenResolved) patch.recurrenceCount = (existing.condition.recurrenceCount || 0) + 1;
|
|
113
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
114
|
+
return { managed: toManaged(existing, patch), wasResolved: hasBeenResolved };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function handler(args = {}, context = {}) {
|
|
118
|
+
try {
|
|
119
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
120
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
121
|
+
return JSON.stringify({ success: false, error: 'updateConditionStatus requires an active turn context (turnId, patientCode).', data: {} });
|
|
122
|
+
}
|
|
123
|
+
const caseId = (typeof args?.case_id === 'string' ? args.case_id : '').trim();
|
|
124
|
+
const transition = (typeof args?.transition === 'string' ? args.transition : '').trim().toLowerCase();
|
|
125
|
+
const reasoning = (typeof args?.reasoning === 'string' ? args.reasoning : '').trim();
|
|
126
|
+
if (!caseId) return fail('case_id is required');
|
|
127
|
+
if (transition === 'new_episode') {
|
|
128
|
+
return fail('new_episode is not a status transition — use recordClinicalImpression', {
|
|
129
|
+
case_id: caseId,
|
|
130
|
+
recovery: 'call recordClinicalImpression with event=\'new_episode\', episode_id, mention_id, missing_for_higher_grade and a grade_estimate or trajectory_direction, so the new episode carries its own grade',
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (!TRANSITIONS.includes(transition)) {
|
|
134
|
+
return fail(`unknown transition: '${transition}'. Must be one of ${TRANSITIONS.join(' | ')}.`);
|
|
135
|
+
}
|
|
136
|
+
if (!reasoning) return fail('reasoning is required — one short sentence justifying this lifecycle transition.');
|
|
137
|
+
|
|
138
|
+
const patientId = runtime.patientCode;
|
|
139
|
+
const cases = await readSymptomCases({ patientId });
|
|
140
|
+
const existing = cases.find((symptomCase) => symptomCase.condition.conditionId === caseId);
|
|
141
|
+
if (!existing) return fail('case_not_found_or_wrong_patient', { case_id: caseId });
|
|
142
|
+
|
|
143
|
+
if (transition === 'resolve_episode') {
|
|
144
|
+
const result = applyResolveEpisode(existing, reasoning, args);
|
|
145
|
+
if (typeof result === 'string') return result;
|
|
146
|
+
await storeSymptomCase({ patientId, managedSymptom: result });
|
|
147
|
+
return JSON.stringify({ success: true, data: { case_id: result.condition.conditionId, status: returnedStatus(result.condition) } });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (transition === 'reactivate') {
|
|
151
|
+
const result = applyReactivate(existing, reasoning, args);
|
|
152
|
+
if (typeof result === 'string') return result;
|
|
153
|
+
await storeSymptomCase({ patientId, managedSymptom: result.managed });
|
|
154
|
+
return JSON.stringify({
|
|
155
|
+
success: true,
|
|
156
|
+
data: {
|
|
157
|
+
case_id: result.managed.condition.conditionId,
|
|
158
|
+
status: returnedStatus(result.managed.condition),
|
|
159
|
+
is_recurrence: result.wasResolved,
|
|
160
|
+
recurrence_count: result.managed.condition.recurrenceCount || 0,
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const result = applyDormant(existing, reasoning, args, transition === 'resolve');
|
|
166
|
+
if (typeof result === 'string') return result;
|
|
167
|
+
await storeSymptomCase({ patientId, managedSymptom: result });
|
|
168
|
+
const cascade = await runCloseCascade(patientId, result.condition.conditionId, runtime.turnId, runtime.trace || null, 'updateConditionStatus', {
|
|
169
|
+
closeReason: result.condition.closeReason,
|
|
170
|
+
});
|
|
171
|
+
const data = {
|
|
172
|
+
case_id: result.condition.conditionId,
|
|
173
|
+
status: returnedStatus(result.condition),
|
|
174
|
+
abatement_at: result.condition.abatementAt,
|
|
175
|
+
};
|
|
176
|
+
if (cascade.autoResolvedPlans.length) data.auto_resolved_plans = cascade.autoResolvedPlans;
|
|
177
|
+
if (cascade.prunedClusters.length) data.pruned_clusters = cascade.prunedClusters;
|
|
178
|
+
if (cascade.dissolvedClusters.length) data.dissolved_clusters = cascade.dissolvedClusters;
|
|
179
|
+
if (cascade.cascadeErrors.length) {
|
|
180
|
+
data.cascade_errors = cascade.cascadeErrors;
|
|
181
|
+
logger.warn({ caseId: result.condition.conditionId, cascadeErrors: cascade.cascadeErrors }, 'updateConditionStatus close cascade errors');
|
|
182
|
+
}
|
|
183
|
+
return JSON.stringify({ success: true, data });
|
|
184
|
+
} catch (err) {
|
|
185
|
+
return JSON.stringify({ success: false, error: err?.message || 'updateConditionStatus failed', data: {} });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = {
|
|
190
|
+
definition,
|
|
191
|
+
handler,
|
|
192
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const { assessmentUid, buildAssessment } = require('../helpers/palliativeAssessmentHelper');
|
|
2
|
+
const { storePalliativeAssessment, readPalliativeAssessments, readPalliativeCarePlans } = require('../../fhir');
|
|
3
|
+
const { fhirId } = require('../../fhir/helpers/fhirHelper');
|
|
4
|
+
|
|
5
|
+
const definition = {
|
|
6
|
+
name: 'updatePalliativeAssessment',
|
|
7
|
+
description: '**Does:** Full-replacement correction path for the Phase-1 palliative assessment — issues a NEW assessment (new `assessment_id`); it is NOT a field-level patch. The prior assessment_id is returned as `replaced_prior_assessment_id` for audit lineage.\n\n**Required inputs:** `assessment` (one object, identical shape to `submitPalliativeAssessment`).\n\n**When NOT to call:**\n- Before a Phase-1 assessment exists for the turn — returns `no_assessment_to_update`; call `submitPalliativeAssessment` first.\n- After a care plan has been committed for the turn — returns `careplan_already_committed`; the assessment is locked.\n\n**Returns:** `accepted`, `assessment_id` (new), `replaced_prior_assessment_id`, `turn_id`.\n\n**Side effects:** persists a replacement FHIR `ClinicalImpression` (+ a `Task` per urgent finding) + `Provenance`.',
|
|
8
|
+
strict: false,
|
|
9
|
+
parameters: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
assessment: {
|
|
13
|
+
type: 'object',
|
|
14
|
+
description: 'The corrected palliative assessment — full replacement, same shape as submitPalliativeAssessment.',
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
required: ['assessment'],
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function fail(error, data = {}) {
|
|
22
|
+
return JSON.stringify({ success: false, error, data });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function handler(args = {}, context = {}) {
|
|
26
|
+
try {
|
|
27
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
28
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
29
|
+
return fail('updatePalliativeAssessment requires an active turn context (turnId, patientCode).');
|
|
30
|
+
}
|
|
31
|
+
const raw = args?.assessment;
|
|
32
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
33
|
+
return fail('assessment is required (non-empty object)');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const patientId = runtime.patientCode;
|
|
37
|
+
const turnId = runtime.turnId;
|
|
38
|
+
|
|
39
|
+
const [prior] = await readPalliativeAssessments({ patientId, turnId });
|
|
40
|
+
if (!prior) {
|
|
41
|
+
return fail('no_assessment_to_update — call submitPalliativeAssessment first', { turn_id: turnId });
|
|
42
|
+
}
|
|
43
|
+
const [careplan] = await readPalliativeCarePlans({ patientId, turnId });
|
|
44
|
+
if (careplan) {
|
|
45
|
+
return fail('careplan_already_committed — the assessment is locked once a careplan exists for the turn', { turn_id: turnId, careplan_id: careplan.careplanId });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const assessment = buildAssessment({
|
|
49
|
+
raw,
|
|
50
|
+
assessmentId: assessmentUid(),
|
|
51
|
+
patientId,
|
|
52
|
+
turnId,
|
|
53
|
+
committedAt: new Date().toISOString(),
|
|
54
|
+
});
|
|
55
|
+
await storePalliativeAssessment({ patientId, assessment });
|
|
56
|
+
|
|
57
|
+
const assessmentId = fhirId(assessment.assessmentId);
|
|
58
|
+
runtime.setPalliativeAssessment({ assessmentId, turnId });
|
|
59
|
+
runtime.trace.setSignals({ palliativeAssessmentId: assessmentId });
|
|
60
|
+
|
|
61
|
+
return JSON.stringify({
|
|
62
|
+
success: true,
|
|
63
|
+
data: {
|
|
64
|
+
accepted: true,
|
|
65
|
+
assessment_id: assessmentId,
|
|
66
|
+
replaced_prior_assessment_id: fhirId(prior.assessmentId),
|
|
67
|
+
turn_id: turnId,
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
} catch (err) {
|
|
71
|
+
return JSON.stringify({ success: false, error: err?.message || 'updatePalliativeAssessment failed', data: {} });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = {
|
|
76
|
+
definition,
|
|
77
|
+
handler,
|
|
78
|
+
};
|