@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,136 @@
|
|
|
1
|
+
const { assembleLandscape } = require('../services/symptomLandscapeService');
|
|
2
|
+
const { assembleHistory, SUPPORTED_SCOPES, TIMEFRAME_DAYS } = require('../services/patientHistoryService');
|
|
3
|
+
const { assembleRiskProfile } = require('../services/riskAssessmentService');
|
|
4
|
+
const { buildTurnRiskBrief, escalationLookbackSince } = require('../services/turnRiskBriefService');
|
|
5
|
+
const { readDispatchedEscalations, readEscalationCases, readSymptomCases } = require('../../fhir');
|
|
6
|
+
const { logger } = require('../../utils/logger');
|
|
7
|
+
|
|
8
|
+
const ALLOWED_SECTIONS = ['landscape', 'history', 'risk'];
|
|
9
|
+
const REQUIRED_SECTION = 'risk';
|
|
10
|
+
|
|
11
|
+
const definition = {
|
|
12
|
+
name: 'getRouterContextBundle',
|
|
13
|
+
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
|
|
14
|
+
strict: false,
|
|
15
|
+
replayScope: 'turn',
|
|
16
|
+
parameters: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
include: {
|
|
20
|
+
type: 'array',
|
|
21
|
+
items: { type: 'string', enum: ALLOWED_SECTIONS },
|
|
22
|
+
description:
|
|
23
|
+
'Optional sections to fetch. Risk is mandatory and is always added; including risk explicitly is harmless. Omit for all three.',
|
|
24
|
+
},
|
|
25
|
+
landscape_min_priority: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
26
|
+
history_scope: { type: 'array', items: { type: 'string', enum: [...SUPPORTED_SCOPES] } },
|
|
27
|
+
history_filter: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
ctcae_term: { type: 'string' },
|
|
31
|
+
timeframe: { type: 'string', enum: Object.keys(TIMEFRAME_DAYS) },
|
|
32
|
+
case_id: { type: 'string' },
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
required: [],
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
async function handler(args = {}, context = {}) {
|
|
41
|
+
try {
|
|
42
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
43
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
44
|
+
return JSON.stringify({ success: false, error: 'getRouterContextBundle requires an active turn context (turnId, patientCode).', data: {} });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let include;
|
|
48
|
+
if ('include' in args) {
|
|
49
|
+
include = args.include;
|
|
50
|
+
if (!Array.isArray(include) || !include.length) {
|
|
51
|
+
return JSON.stringify({ success: false, error: `include must be a non-empty list of ${JSON.stringify(ALLOWED_SECTIONS)}.`, data: {} });
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
include = [...ALLOWED_SECTIONS];
|
|
55
|
+
}
|
|
56
|
+
const unknown = include.filter((section) => !ALLOWED_SECTIONS.includes(section));
|
|
57
|
+
if (unknown.length) {
|
|
58
|
+
return JSON.stringify({ success: false, error: `unknown include section(s): ${JSON.stringify(unknown)}. Allowed: ['landscape','history','risk'].`, data: {} });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const sections = [...new Set([...include, REQUIRED_SECTION])];
|
|
62
|
+
|
|
63
|
+
const patientId = runtime.patientCode;
|
|
64
|
+
const historyArgs = {};
|
|
65
|
+
if (args.history_scope != null) historyArgs.scope = args.history_scope;
|
|
66
|
+
if (args.history_filter != null) historyArgs.filter = args.history_filter;
|
|
67
|
+
|
|
68
|
+
const [symptomCases, escalations, escalationCases] = await Promise.all([
|
|
69
|
+
readSymptomCases({ patientId }).catch((error) => {
|
|
70
|
+
logger.warn('[routerContextBundle] symptom cases unavailable', { code: patientId, error: error?.message });
|
|
71
|
+
return null;
|
|
72
|
+
}),
|
|
73
|
+
readDispatchedEscalations({ patientId, since: escalationLookbackSince() }).catch((error) => {
|
|
74
|
+
logger.warn('[routerContextBundle] escalation recall unavailable', { code: patientId, error: error?.message });
|
|
75
|
+
return [];
|
|
76
|
+
}),
|
|
77
|
+
readEscalationCases({ patientId }).catch((error) => {
|
|
78
|
+
logger.warn('[routerContextBundle] team cases unavailable', { code: patientId, error: error?.message });
|
|
79
|
+
return [];
|
|
80
|
+
}),
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
const readers = {
|
|
84
|
+
landscape: () => assembleLandscape(patientId, args.landscape_min_priority || 'low', symptomCases),
|
|
85
|
+
history: () => assembleHistory(patientId, historyArgs),
|
|
86
|
+
risk: () => assembleRiskProfile(patientId),
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const outcomes = await Promise.allSettled(sections.map((section) => readers[section]()));
|
|
90
|
+
|
|
91
|
+
const bundle = { patient_id: patientId, sections_requested: sections, sections_returned: [] };
|
|
92
|
+
const diagnostics = {};
|
|
93
|
+
|
|
94
|
+
sections.forEach((section, index) => {
|
|
95
|
+
const outcome = outcomes[index];
|
|
96
|
+
if (outcome.status === 'fulfilled') {
|
|
97
|
+
bundle[section] = outcome.value;
|
|
98
|
+
bundle.sections_returned.push(section);
|
|
99
|
+
if (section === 'risk') {
|
|
100
|
+
const turnFocus = buildTurnRiskBrief(outcome.value.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases: symptomCases || [], escalations, escalationCases });
|
|
101
|
+
bundle[section] = { ...outcome.value, turn_focus: turnFocus };
|
|
102
|
+
// Same signal shape as getPatientRiskAssessmentTool: utilization metrics must count both read paths.
|
|
103
|
+
runtime.trace?.setSignals?.({
|
|
104
|
+
riskAssessmentChecked: true,
|
|
105
|
+
riskAssessment: {
|
|
106
|
+
status: outcome.value.status,
|
|
107
|
+
predictedAes: outcome.value.profile?.predicted_aes?.length ?? 0,
|
|
108
|
+
assessmentId: outcome.value.profile?.assessment_id ?? null,
|
|
109
|
+
processed: true,
|
|
110
|
+
focusedConcerns: turnFocus.current_concerns.length,
|
|
111
|
+
relevantRisks: turnFocus.relevant_risks.length,
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
} else {
|
|
116
|
+
diagnostics[`${section}_error`] = outcome.reason?.message || `${section} failed`;
|
|
117
|
+
if (section === 'risk') {
|
|
118
|
+
runtime.trace?.setSignals?.({
|
|
119
|
+
riskAssessmentChecked: true,
|
|
120
|
+
riskAssessment: { status: 'error', predictedAes: 0, assessmentId: null, processed: false },
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
if (Object.keys(diagnostics).length) bundle._diagnostics = diagnostics;
|
|
127
|
+
return JSON.stringify({ success: true, data: bundle });
|
|
128
|
+
} catch (err) {
|
|
129
|
+
return JSON.stringify({ success: false, error: err?.message || 'getRouterContextBundle failed', data: {} });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
module.exports = {
|
|
134
|
+
definition,
|
|
135
|
+
handler,
|
|
136
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
|
|
2
|
+
|
|
3
|
+
const definition = {
|
|
4
|
+
name: 'lookupCtcaeEntry',
|
|
5
|
+
description: '**Does:** Looks up the CTCAE entry for a canonical symptom term (e.g. `nausea`, `diarrhea`, `fatigue`). Returns grade-by-grade severity definitions and validated PRO-CTCAE patient-language anchors (when present).\n\n**Required inputs:** `term` (canonical CTCAE symptom term in English snake_case, e.g. `nausea`, `diarrhea`; use `other` only when no catalog term fits).\n\n**When to call:** when the curated grade rubric already on intake (`extractClinicalInfo.clinical_facts[i].grade_scale`) is missing or insufficient — PRO-CTCAE patient-language disambiguation, or a boundary case needing the validated PRO-CTCAE anchors. Read-only; parallelisable with other router-side reads.\n\n**When NOT to call:**\n- When `grade_scale` on the clinical fact is already sufficient — grading from that avoids a wasted lookup.\n- Non-symptom turns (pure educational questions, emotional-only, out-of-scope admin, casual chat) — no concrete symptom to grade.\n\n**Returns:** `entry` (with `found: true`) — the CTCAE record carrying `grades` (grade-by-grade severity definitions; may be `null` for a curated term without a defined ladder) and `patient_phrases_validated` (validated patient-language anchors, when present). Unknown term → `{found: false, nearest_terms[]}` — pick the right key and re-issue. The grading workflow (Grade 0–5 mapping, ≥ 3 → escalate via `reportMedicalEscalation`, etc.) lives in the `clinical_routing` `SKILL.md` — read the returned entry against those rules.\n\n**Side effects:** none — read-only catalog lookup.',
|
|
6
|
+
strict: true,
|
|
7
|
+
replayScope: 'turn',
|
|
8
|
+
parameters: {
|
|
9
|
+
type: 'object',
|
|
10
|
+
properties: {
|
|
11
|
+
term: {
|
|
12
|
+
type: 'string',
|
|
13
|
+
description: 'Canonical CTCAE term to look up severity grading for.',
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
required: ['term'],
|
|
17
|
+
additionalProperties: false,
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
async function handler(args) {
|
|
22
|
+
const term = args?.term;
|
|
23
|
+
if (typeof term !== 'string' || !term.trim()) {
|
|
24
|
+
return JSON.stringify({ success: false, error: 'lookupCtcaeEntry requires `term`.' });
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
return JSON.stringify({ success: true, data: getCtcaeCatalog().lookupEntry(term) });
|
|
28
|
+
} catch (err) {
|
|
29
|
+
return JSON.stringify({ success: false, error: err?.message || 'lookupCtcaeEntry failed' });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = {
|
|
34
|
+
definition,
|
|
35
|
+
handler,
|
|
36
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
const { patternConsultStore } = require('../models/patternConsultModel');
|
|
4
|
+
const { readSymptomCases, readClusters, storeCluster } = require('../../fhir');
|
|
5
|
+
const { ClusterImpression, HYPOTHESIS_TYPES, CONFIDENCE_LEVELS, CLINICAL_SIGNIFICANCE } = require('../../shared/dtos/ClusterImpression');
|
|
6
|
+
const { ClusterHistoryRecord } = require('../../shared/dtos/ClusterHistoryRecord');
|
|
7
|
+
const { patternConsultLive } = require('../flags/patternConsultFlags');
|
|
8
|
+
const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
9
|
+
|
|
10
|
+
const definition = {
|
|
11
|
+
name: 'openClusterHypothesis',
|
|
12
|
+
description: '**Does:** Opens a NEW cluster hypothesis (ClusterImpression) grouping 2+ open symptom cases the agent believes are one clinical pattern (an AE profile, a syndrome, a disease complication, or a causal chain).\n\n**Required inputs:** `label` (short human name, unique among active clusters), `hypothesis_type` (`ae_profile` | `symptom_syndrome` | `disease_complication` | `relational_causal`), `member_case_ids` (2+ open case_ids), `relationship_model` (how the members relate), `initial_confidence` (`speculative` | `moderate` | `strong`), `clinical_significance` (`benign` | `moderate` | `safety_relevant` | `emergency`), `opening_reasoning`. Optional `strengthens_if`, `weakens_if`, `consultation_id`.\n\n**When to call:** when 2+ open cases co-occur as a coherent pattern with routing implications.\n\n**When NOT to call:** for a single case, or when an active cluster already carries this `label` — use `updateClusterHypothesis` instead.\n\n**Returns:** `cluster_id`, and `member_case_ids` ONLY when input dedup changed the list you sent. Fails hard with `cluster_already_open_with_label` (+`existing_cluster_id`), fewer than 2 unique members, an unknown/non-open/wrong-patient member, or an invalid vocab value.\n\n**Side effects:** writes a FHIR ClusterImpression + an \'opened\' Provenance.',
|
|
13
|
+
strict: false,
|
|
14
|
+
parameters: {
|
|
15
|
+
type: 'object',
|
|
16
|
+
properties: {
|
|
17
|
+
label: {
|
|
18
|
+
type: 'string',
|
|
19
|
+
description: 'Short human name for the cluster. Must be unique among the patient\'s active clusters.',
|
|
20
|
+
},
|
|
21
|
+
hypothesis_type: {
|
|
22
|
+
type: 'string',
|
|
23
|
+
enum: HYPOTHESIS_TYPES,
|
|
24
|
+
description: 'The kind of pattern: `ae_profile`, `symptom_syndrome`, `disease_complication`, or `relational_causal`.',
|
|
25
|
+
},
|
|
26
|
+
member_case_ids: {
|
|
27
|
+
type: 'array',
|
|
28
|
+
items: { type: 'string' },
|
|
29
|
+
description: 'At least 2 open case_ids (NCI symptom-cluster definition). Duplicates are silently deduped.',
|
|
30
|
+
},
|
|
31
|
+
relationship_model: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'How the member cases relate (the clinical model behind the cluster).',
|
|
34
|
+
},
|
|
35
|
+
initial_confidence: {
|
|
36
|
+
type: 'string',
|
|
37
|
+
enum: CONFIDENCE_LEVELS,
|
|
38
|
+
description: '`speculative`, `moderate`, or `strong`.',
|
|
39
|
+
},
|
|
40
|
+
clinical_significance: {
|
|
41
|
+
type: 'string',
|
|
42
|
+
enum: CLINICAL_SIGNIFICANCE,
|
|
43
|
+
description: '`benign`, `moderate`, `safety_relevant`, or `emergency`.',
|
|
44
|
+
},
|
|
45
|
+
opening_reasoning: {
|
|
46
|
+
type: 'string',
|
|
47
|
+
description: 'Why this cluster is being opened now.',
|
|
48
|
+
},
|
|
49
|
+
strengthens_if: {
|
|
50
|
+
type: 'array',
|
|
51
|
+
items: { type: 'string' },
|
|
52
|
+
description: 'Optional. Observations that would raise confidence in this hypothesis.',
|
|
53
|
+
},
|
|
54
|
+
weakens_if: {
|
|
55
|
+
type: 'array',
|
|
56
|
+
items: { type: 'string' },
|
|
57
|
+
description: 'Optional. Observations that would lower confidence in this hypothesis.',
|
|
58
|
+
},
|
|
59
|
+
consultation_id: {
|
|
60
|
+
type: 'string',
|
|
61
|
+
description: 'Optional. The pattern-consult id that anchors this hypothesis, if any.',
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
required: ['label', 'hypothesis_type', 'member_case_ids', 'relationship_model', 'initial_confidence', 'clinical_significance', 'opening_reasoning'],
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function fail(error, data = {}) {
|
|
69
|
+
return JSON.stringify({ success: false, error, data });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function handler(args = {}, context = {}) {
|
|
73
|
+
try {
|
|
74
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
75
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
76
|
+
return fail('openClusterHypothesis requires an active turn context (turnId, patientCode).');
|
|
77
|
+
}
|
|
78
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
79
|
+
const label = str(args?.label).trim();
|
|
80
|
+
const hypothesisType = str(args?.hypothesis_type).trim().toLowerCase();
|
|
81
|
+
const relationshipModel = str(args?.relationship_model).trim();
|
|
82
|
+
const initialConfidence = str(args?.initial_confidence).trim().toLowerCase();
|
|
83
|
+
const clinicalSignificance = str(args?.clinical_significance).trim().toLowerCase();
|
|
84
|
+
const openingReasoning = str(args?.opening_reasoning).trim();
|
|
85
|
+
const strList = (raw) => (Array.isArray(raw) ? raw.filter((item) => typeof item === 'string') : []);
|
|
86
|
+
const requested = strList(args?.member_case_ids);
|
|
87
|
+
|
|
88
|
+
const missing = [['label', label], ['hypothesis_type', hypothesisType], ['member_case_ids', Array.isArray(args?.member_case_ids) ? args.member_case_ids : ''], ['relationship_model', relationshipModel], ['initial_confidence', initialConfidence], ['clinical_significance', clinicalSignificance], ['opening_reasoning', openingReasoning]]
|
|
89
|
+
.filter(([, v]) => !v).map(([n]) => n);
|
|
90
|
+
if (missing.length) return fail(`missing required field(s): ${missing.join(', ')}`);
|
|
91
|
+
|
|
92
|
+
if (!HYPOTHESIS_TYPES.includes(hypothesisType)) return fail(`invalid hypothesis_type: '${hypothesisType}'. Must be one of ${HYPOTHESIS_TYPES.join(' | ')}.`, { hypothesis_type: hypothesisType });
|
|
93
|
+
if (!CONFIDENCE_LEVELS.includes(initialConfidence)) return fail(`invalid initial_confidence: '${initialConfidence}'. Must be one of ${CONFIDENCE_LEVELS.join(' | ')}.`, { initial_confidence: initialConfidence });
|
|
94
|
+
if (!CLINICAL_SIGNIFICANCE.includes(clinicalSignificance)) return fail(`invalid clinical_significance: '${clinicalSignificance}'. Must be one of ${CLINICAL_SIGNIFICANCE.join(' | ')}.`, { clinical_significance: clinicalSignificance });
|
|
95
|
+
|
|
96
|
+
const consultationId = str(args?.consultation_id).trim() || null;
|
|
97
|
+
|
|
98
|
+
if (requested.length < 2) return fail('cluster requires at least 2 member_case_ids (NCI symptom-cluster definition).', { member_case_ids: requested });
|
|
99
|
+
const memberCaseIds = [...new Set(requested)];
|
|
100
|
+
if (memberCaseIds.length < 2) return fail('after dedup, fewer than 2 unique member_case_ids remain');
|
|
101
|
+
|
|
102
|
+
if (patternConsultLive() && initialConfidence !== 'speculative') {
|
|
103
|
+
if (!consultationId) {
|
|
104
|
+
return fail('unanchored_hypothesis_must_start_speculative', {
|
|
105
|
+
initial_confidence: initialConfidence,
|
|
106
|
+
hint: 'open at speculative confidence, or anchor to a requestPatternConsult consultation_id',
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const consult = await patternConsultStore().get(consultationId);
|
|
110
|
+
if (!consult || consult.patientCode !== runtime.patientCode) {
|
|
111
|
+
return fail('invalid_consultation_id', {
|
|
112
|
+
consultation_id: consultationId,
|
|
113
|
+
hint: 'anchor to a real requestPatternConsult consultation for this patient, or open at speculative confidence',
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const patientId = runtime.patientCode;
|
|
119
|
+
const active = await readClusters({ patientId, label });
|
|
120
|
+
const existing = active.find((c) => c.status === 'active');
|
|
121
|
+
if (existing) {
|
|
122
|
+
return fail('cluster_already_open_with_label', {
|
|
123
|
+
existing_cluster_id: existing.clusterId,
|
|
124
|
+
existing_status: existing.status,
|
|
125
|
+
hint: 'call updateClusterHypothesis on the existing cluster instead of opening a duplicate',
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const cases = await readSymptomCases({ patientId });
|
|
130
|
+
for (const caseId of memberCaseIds) {
|
|
131
|
+
const managedSymptom = cases.find((c) => c.condition.conditionId === caseId);
|
|
132
|
+
if (!managedSymptom) return fail('member_case_not_found_or_wrong_patient', { member_case_id: caseId });
|
|
133
|
+
if (!OPEN_STATUSES.includes(managedSymptom.condition.clinicalStatus)) return fail('member_case_not_open', { case_id: caseId, status: managedSymptom.condition.clinicalStatus });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const now = new Date().toISOString();
|
|
137
|
+
const clusterId = `cluster_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
138
|
+
const cluster = new ClusterImpression({
|
|
139
|
+
clusterId,
|
|
140
|
+
patientId,
|
|
141
|
+
label,
|
|
142
|
+
hypothesisType,
|
|
143
|
+
status: 'active',
|
|
144
|
+
confidence: initialConfidence,
|
|
145
|
+
clinicalSignificance,
|
|
146
|
+
memberCaseIds,
|
|
147
|
+
consultationId,
|
|
148
|
+
relationshipModel,
|
|
149
|
+
strengthensIf: strList(args?.strengthens_if),
|
|
150
|
+
weakensIf: strList(args?.weakens_if),
|
|
151
|
+
openingReasoning,
|
|
152
|
+
openedAt: now,
|
|
153
|
+
});
|
|
154
|
+
const history = [new ClusterHistoryRecord({
|
|
155
|
+
clusterId,
|
|
156
|
+
turnId: runtime.turnId,
|
|
157
|
+
action: 'opened',
|
|
158
|
+
transitionReason: openingReasoning,
|
|
159
|
+
recordedAt: now,
|
|
160
|
+
})];
|
|
161
|
+
|
|
162
|
+
await storeCluster({ patientId, cluster, history });
|
|
163
|
+
|
|
164
|
+
const out = { cluster_id: clusterId };
|
|
165
|
+
if (memberCaseIds.length !== requested.length) out.member_case_ids = [...memberCaseIds];
|
|
166
|
+
return JSON.stringify({ success: true, data: out });
|
|
167
|
+
} catch (err) {
|
|
168
|
+
return fail(err?.message || 'openClusterHypothesis failed');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = {
|
|
173
|
+
definition,
|
|
174
|
+
handler,
|
|
175
|
+
};
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
const { GRADE_CONFIDENCE_LEVELS, GRADE_MIN, GRADE_MAX, gradeEstimateSchema, parseGradeEstimate, projectGradeEstimate, hasGradeSignal, malformedGradeEstimate } = require('../helpers/gradeEstimateHelper');
|
|
4
|
+
const { ceilingGapError } = require('../helpers/ceilingGapHelper');
|
|
5
|
+
const { mentionProvenanceError } = require('../helpers/evidenceAnchorHelper');
|
|
6
|
+
const { ctcaeTermError } = require('../services/ctcaeTermService');
|
|
7
|
+
const { gradeClaimError, gradeClaimNotice } = require('../services/gradeClaimService');
|
|
8
|
+
const { armOpenCeilingNet } = require('../services/contingencyDispatchService');
|
|
9
|
+
const { readSymptomCases, storeSymptomCase } = require('../../fhir');
|
|
10
|
+
const { ManagedSymptom, OPEN_STATUSES, CLOSED_STATUSES, FUNCTIONAL_ANCHORS } = require('../../shared/dtos/ManagedSymptom');
|
|
11
|
+
const { logger } = require('../../utils/logger');
|
|
12
|
+
const { isArmOnOpenCeilingLive } = require('../flags/contingencyFlags');
|
|
13
|
+
|
|
14
|
+
const definition = {
|
|
15
|
+
name: 'openCondition',
|
|
16
|
+
description: '**Does:** Opens a NEW agent-tracked symptom case (Condition + initial ClinicalImpression) for a symptom term with no open case — the longitudinal expediente that groups 1..N episodes of the same `ctcae_term`.\n\n**Required inputs:** `ctcae_term` (English snake_case catalog key — e.g. `fever`, `pain`, `dyspnea`; use `other` only when no catalog term fits), `episode_id` (the intake episode this case wraps), `mention_id` (the intake mention that opened the case), `verbatim_quote` (exact substring of the patient message). Optional `temporality`, `grade_estimate` (`{best_estimate, confidence, possible_range, reasoning}`).\n\n**When to call:** when the turn surfaces a symptom with no open case on this `ctcae_term`. Use `recordClinicalImpression` if a case is already open — do NOT call `openCondition` twice for the same symptom.\n\n**When NOT to call:**\n- For a new episode or subsequent assessment of an EXISTING open case — use `recordClinicalImpression`.\n- For a symptom that already has a case which was closed, resolved or deactivated — the same symptom returning is a recurrence of that case, not a new one. Reopen it with `updateConditionStatus(transition=\'reactivate\')`. This tool refuses the duplicate with `DORMANT_CASE_EXISTS` and names the case.\n\n**Returns:** `case_id`, `action_taken` (`opened`), `status`, `ctcae_term`, `episode_ids`, `current_episode_id`, `grade_estimate`, `temporality`, `trajectory`, and `grade_notice` when the grade was recorded without the ADL limitation its clause mentions — advisory: the grade was stored as given. Fails hard with `case_already_open_for_term` + `existing_case_id` when an open case already exists for the term — recover via `recordClinicalImpression`.\n\n**Side effects:** writes a FHIR `Condition` + head `ClinicalImpression` + `Provenance`.',
|
|
17
|
+
strict: false,
|
|
18
|
+
parameters: {
|
|
19
|
+
type: 'object',
|
|
20
|
+
properties: {
|
|
21
|
+
ctcae_term: {
|
|
22
|
+
type: 'string',
|
|
23
|
+
description: 'English snake_case key from the CTCAE catalog (e.g. \'fever\', \'pain\', \'dyspnea\'). Use \'other\' only when no catalog term fits.',
|
|
24
|
+
},
|
|
25
|
+
episode_id: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'The intake episode id this case wraps.',
|
|
28
|
+
},
|
|
29
|
+
mention_id: {
|
|
30
|
+
type: 'string',
|
|
31
|
+
description: 'The intake mention id that opened the case.',
|
|
32
|
+
},
|
|
33
|
+
verbatim_quote: {
|
|
34
|
+
type: 'string',
|
|
35
|
+
description: 'Exact substring of the patient\'s message.',
|
|
36
|
+
},
|
|
37
|
+
temporality: {
|
|
38
|
+
type: 'string',
|
|
39
|
+
description: 'Optional. Onset/course descriptor (e.g. \'ongoing\', \'acute\', \'progressive\').',
|
|
40
|
+
},
|
|
41
|
+
grade_estimate: gradeEstimateSchema('Optional. The provisional graded severity read that seeds the case.'),
|
|
42
|
+
missing_for_higher_grade: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
description: 'REQUIRED whenever you send a `grade_estimate`. The one thing you would need to know to rule out a grade above your best estimate, read against this term\'s grade_scale — a value, a functional limit, whether something got worse overnight. Write it as the patient could answer it, e.g. \'si la fiebre pasó de 38.5\'. Write \'none\' only when the ladder is already settled by what the patient told you.',
|
|
45
|
+
},
|
|
46
|
+
check_in_question: {
|
|
47
|
+
type: 'string',
|
|
48
|
+
description: 'REQUIRED whenever missing_for_higher_grade is not \'none\'. The same datum, rewritten as the question the patient would be asked if they go quiet — their words, their language, one question, no clinical jargon and no acronyms. This one is sent over WhatsApp, so write it for the patient, not for the record.',
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
required: ['ctcae_term', 'episode_id', 'mention_id', 'verbatim_quote'],
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const uid = (prefix) => `${prefix}_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
56
|
+
|
|
57
|
+
async function handler(args = {}, context = {}) {
|
|
58
|
+
try {
|
|
59
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
60
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
61
|
+
return JSON.stringify({ success: false, error: 'openCondition requires an active turn context (turnId, patientCode).', data: {} });
|
|
62
|
+
}
|
|
63
|
+
const asString = (value) => (typeof value === 'string' ? value : '');
|
|
64
|
+
const ctcaeTerm = asString(args?.ctcae_term).trim().toLowerCase();
|
|
65
|
+
const episodeId = asString(args?.episode_id).trim();
|
|
66
|
+
const mentionId = asString(args?.mention_id).trim();
|
|
67
|
+
const verbatim = asString(args?.verbatim_quote).trim();
|
|
68
|
+
|
|
69
|
+
const missing = [['ctcae_term', ctcaeTerm], ['episode_id', episodeId], ['mention_id', mentionId], ['verbatim_quote', verbatim]]
|
|
70
|
+
.filter(([, value]) => !value).map(([name]) => name);
|
|
71
|
+
if (missing.length) {
|
|
72
|
+
return JSON.stringify({ success: false, error: `missing required field(s): ${missing.join(', ')}`, data: {} });
|
|
73
|
+
}
|
|
74
|
+
const termGap = ctcaeTermError(ctcaeTerm);
|
|
75
|
+
if (termGap) {
|
|
76
|
+
return JSON.stringify({ success: false, error: termGap.error, data: { use_instead: termGap.useInstead } });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const patientId = runtime.patientCode;
|
|
80
|
+
const casesForTerm = await readSymptomCases({ patientId, ctcaeTerm });
|
|
81
|
+
const openCase = casesForTerm.find((symptomCase) => OPEN_STATUSES.includes(symptomCase.condition.clinicalStatus));
|
|
82
|
+
if (openCase) {
|
|
83
|
+
return JSON.stringify({
|
|
84
|
+
success: false,
|
|
85
|
+
error: 'case_already_open_for_term',
|
|
86
|
+
data: {
|
|
87
|
+
existing_case_id: openCase.condition.conditionId,
|
|
88
|
+
existing_status: openCase.condition.clinicalStatus,
|
|
89
|
+
hint: 'call recordClinicalImpression with event=\'add_evidence\' or \'new_episode\' to attach to the existing case',
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const dormantCase = casesForTerm.find((symptomCase) => CLOSED_STATUSES.includes(symptomCase.condition.clinicalStatus));
|
|
95
|
+
if (dormantCase) {
|
|
96
|
+
const { condition } = dormantCase;
|
|
97
|
+
return JSON.stringify({
|
|
98
|
+
success: false,
|
|
99
|
+
error: 'DORMANT_CASE_EXISTS',
|
|
100
|
+
data: {
|
|
101
|
+
existing_case_id: condition.conditionId,
|
|
102
|
+
existing_status: condition.clinicalStatus,
|
|
103
|
+
close_reason: condition.closeReason,
|
|
104
|
+
dormant_since: condition.abatementAt || condition.lastUpdatedAt || null,
|
|
105
|
+
hint: `this symptom already has a case — reopen it instead of forking the record: updateConditionStatus(case_id='${condition.conditionId}', transition='reactivate', episode_id='${episodeId}', reasoning=…), then recordClinicalImpression on the same case_id`,
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const provenance = mentionProvenanceError(mentionId, { trace: runtime?.trace || null });
|
|
111
|
+
if (provenance) return JSON.stringify({ success: false, error: provenance, data: {} });
|
|
112
|
+
|
|
113
|
+
const now = new Date().toISOString();
|
|
114
|
+
const caseId = uid('case');
|
|
115
|
+
const temporality = typeof args?.temporality === 'string' ? args.temporality : null;
|
|
116
|
+
const malformedGrade = malformedGradeEstimate(args?.grade_estimate);
|
|
117
|
+
if (malformedGrade) return JSON.stringify({ success: false, error: malformedGrade, data: {} });
|
|
118
|
+
const grade = parseGradeEstimate(args?.grade_estimate);
|
|
119
|
+
if (grade.error) {
|
|
120
|
+
const data = { invalid_grade_confidence: { allowed: GRADE_CONFIDENCE_LEVELS },
|
|
121
|
+
invalid_functional_anchor: { allowed: FUNCTIONAL_ANCHORS } }[grade.error]
|
|
122
|
+
|| { allowed_range: [GRADE_MIN, GRADE_MAX] };
|
|
123
|
+
return JSON.stringify({ success: false, error: grade.error, data });
|
|
124
|
+
}
|
|
125
|
+
const gradesTheCase = hasGradeSignal(args?.grade_estimate);
|
|
126
|
+
const claimGap = gradesTheCase ? gradeClaimError({ ctcaeTerm, grade, trace: runtime?.trace || null }) : null;
|
|
127
|
+
if (claimGap) return JSON.stringify({ success: false, error: claimGap, data: {} });
|
|
128
|
+
const gradeNotice = gradesTheCase ? gradeClaimNotice({ ctcaeTerm, grade }) : null;
|
|
129
|
+
const ceilingGap = gradesTheCase ? ceilingGapError(args, 'openCondition') : null;
|
|
130
|
+
if (ceilingGap) return JSON.stringify({ success: false, error: ceilingGap, data: {} });
|
|
131
|
+
const managedSymptom = new ManagedSymptom({
|
|
132
|
+
condition: {
|
|
133
|
+
conditionId: caseId,
|
|
134
|
+
patientId,
|
|
135
|
+
ctcaeTerm,
|
|
136
|
+
clinicalStatus: 'characterizing',
|
|
137
|
+
onsetAt: now,
|
|
138
|
+
temporality,
|
|
139
|
+
evidenceEpisodeIds: [episodeId],
|
|
140
|
+
currentEpisodeId: episodeId,
|
|
141
|
+
evidenceMentionIds: [mentionId],
|
|
142
|
+
},
|
|
143
|
+
latestAssessment: {
|
|
144
|
+
assessmentId: uid('assessment'),
|
|
145
|
+
conditionId: caseId,
|
|
146
|
+
patientId,
|
|
147
|
+
performedAt: now,
|
|
148
|
+
previousId: null,
|
|
149
|
+
grade,
|
|
150
|
+
trajectory: null,
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
await storeSymptomCase({ patientId, managedSymptom });
|
|
155
|
+
const { condition, latestAssessment } = managedSymptom;
|
|
156
|
+
|
|
157
|
+
if (gradesTheCase && isArmOnOpenCeilingLive()) {
|
|
158
|
+
try {
|
|
159
|
+
const net = await armOpenCeilingNet({
|
|
160
|
+
patientCode: runtime.patientCode,
|
|
161
|
+
caseId: condition.conditionId,
|
|
162
|
+
symptom: condition.ctcaeTerm,
|
|
163
|
+
missing: args?.missing_for_higher_grade,
|
|
164
|
+
checkIn: args?.check_in_question,
|
|
165
|
+
grade: latestAssessment.grade?.bestEstimate ?? null,
|
|
166
|
+
trace: runtime.trace || null,
|
|
167
|
+
isLive: runtime.isLive?.bind(runtime),
|
|
168
|
+
});
|
|
169
|
+
logger.info('[openCondition] open-ceiling net', { turnId: runtime.turnId, caseId: condition.conditionId, ...net });
|
|
170
|
+
} catch (netErr) {
|
|
171
|
+
logger.error('[openCondition] open-ceiling net not armed', { turnId: runtime.turnId, caseId: condition.conditionId, error: netErr?.message });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return JSON.stringify({
|
|
176
|
+
success: true,
|
|
177
|
+
data: {
|
|
178
|
+
case_id: condition.conditionId,
|
|
179
|
+
action_taken: 'opened',
|
|
180
|
+
status: condition.clinicalStatus,
|
|
181
|
+
ctcae_term: condition.ctcaeTerm,
|
|
182
|
+
episode_ids: [...condition.evidenceEpisodeIds],
|
|
183
|
+
current_episode_id: condition.currentEpisodeId,
|
|
184
|
+
grade_estimate: projectGradeEstimate(latestAssessment.grade),
|
|
185
|
+
temporality: condition.temporality,
|
|
186
|
+
trajectory: { direction: latestAssessment.trajectory || 'unknown' },
|
|
187
|
+
...(gradeNotice ? { grade_notice: gradeNotice } : {}),
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
} catch (err) {
|
|
191
|
+
return JSON.stringify({ success: false, error: err?.message || 'openCondition failed', data: {} });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = {
|
|
196
|
+
definition,
|
|
197
|
+
handler,
|
|
198
|
+
};
|