@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,208 @@
|
|
|
1
|
+
const { ESCALATION_ROUTES, RED_FLAG_STATUSES } = require('../../shared/dtos/RecommendationSafetyGate');
|
|
2
|
+
const { aliasClosure } = require('../../fhir/helpers/symptomAliasHelper');
|
|
3
|
+
const { str, arr, strList } = require('../../utils/coercionUtils');
|
|
4
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
5
|
+
|
|
6
|
+
const ECHO_SHARE = 0.5;
|
|
7
|
+
const ROUTE_FLOOR_UNVERIFIABLE_CODE = 'route_floor_unverifiable';
|
|
8
|
+
|
|
9
|
+
const tokensOf = (text) => foldAccents(str(text)).toLowerCase().match(/[a-z0-9]{4,}/g) || [];
|
|
10
|
+
|
|
11
|
+
function echoesOwnPattern(redFlag) {
|
|
12
|
+
const source = new Set(tokensOf([
|
|
13
|
+
redFlag.name,
|
|
14
|
+
...redFlag.definition.map((event) => event.clinicalEvent),
|
|
15
|
+
...redFlag.eventsDenied,
|
|
16
|
+
].join(' ')));
|
|
17
|
+
if (!source.size) return false;
|
|
18
|
+
return redFlag.relatedAes.every((ae) => {
|
|
19
|
+
const tokens = tokensOf(ae.ctcaeTerm);
|
|
20
|
+
if (!tokens.length) return false;
|
|
21
|
+
return tokens.filter((token) => source.has(token)).length / tokens.length >= ECHO_SHARE;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function statusFromConfirmedEvents(redFlag) {
|
|
26
|
+
if (redFlag.definition.length) {
|
|
27
|
+
const confirmed = new Set(redFlag.eventsConfirmed.map((event) => event.trim()));
|
|
28
|
+
const allDefinedEventsConfirmed = redFlag.definition
|
|
29
|
+
.every((event) => confirmed.has(event.clinicalEvent.trim()));
|
|
30
|
+
return allDefinedEventsConfirmed ? 'confirmed' : 'partially_confirmed';
|
|
31
|
+
}
|
|
32
|
+
if (!['confirmed', 'partially_confirmed'].includes(redFlag.verificationStatus)) return 'partially_confirmed';
|
|
33
|
+
return redFlag.verificationStatus;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function derivedStatus(redFlag) {
|
|
37
|
+
if (!redFlag.eventsConfirmed.length) return redFlag.eventsDenied.length ? 'denied' : 'inconclusive';
|
|
38
|
+
const derived = statusFromConfirmedEvents(redFlag);
|
|
39
|
+
if (derived === 'confirmed' && redFlag.eventsDenied.length) return 'partially_confirmed';
|
|
40
|
+
return derived;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function normalizeStatus(raw) {
|
|
44
|
+
const status = str(raw).trim();
|
|
45
|
+
if (status === 'suspected') return null;
|
|
46
|
+
return RED_FLAG_STATUSES.includes(status) ? status : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function normalizeRelatedAe(raw) {
|
|
50
|
+
const probability = str(raw?.probability_given_patient).trim();
|
|
51
|
+
return {
|
|
52
|
+
ctcaeTerm: str(raw?.ctcae_term).trim(),
|
|
53
|
+
probabilityGivenPatient: ['high', 'medium', 'low'].includes(probability) ? probability : 'low',
|
|
54
|
+
whyIsRelevant: str(raw?.why_is_relevant).trim(),
|
|
55
|
+
groundedIn: strList(raw?.grounded_in),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeRedFlagEvent(raw) {
|
|
60
|
+
return {
|
|
61
|
+
clinicalEvent: str(raw?.clinical_event).trim(),
|
|
62
|
+
ctcaeGradesReference: arr(raw?.ctcae_grades_reference)
|
|
63
|
+
.map((grade) => Number(grade))
|
|
64
|
+
.filter(Number.isInteger),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function buildRedFlag(raw, repairs, index) {
|
|
69
|
+
const requested = str(raw?.verification_status).trim();
|
|
70
|
+
const requestedRoute = str(raw?.escalation_route).trim();
|
|
71
|
+
const base = {
|
|
72
|
+
name: str(raw?.name).trim(),
|
|
73
|
+
verificationStatus: normalizeStatus(raw?.verification_status) || 'inconclusive',
|
|
74
|
+
escalationRoute: ESCALATION_ROUTES.includes(str(raw?.escalation_route).trim()) ? str(raw.escalation_route).trim() : null,
|
|
75
|
+
eventsConfirmed: strList(raw?.events_confirmed),
|
|
76
|
+
eventsDenied: strList(raw?.events_denied),
|
|
77
|
+
relatedAes: arr(raw?.related_aes).map(normalizeRelatedAe),
|
|
78
|
+
definition: arr(raw?.definition).map(normalizeRedFlagEvent).filter((event) => event.clinicalEvent),
|
|
79
|
+
groundedIn: strList(raw?.grounded_in),
|
|
80
|
+
};
|
|
81
|
+
const want = derivedStatus(base);
|
|
82
|
+
if (want !== base.verificationStatus) {
|
|
83
|
+
repairs.push(`red_flags[${index}].verification_status: '${requested || base.verificationStatus}' → '${want}' (aritmética de eventos)`);
|
|
84
|
+
base.verificationStatus = want;
|
|
85
|
+
}
|
|
86
|
+
if (!['confirmed', 'partially_confirmed'].includes(base.verificationStatus) && base.escalationRoute) {
|
|
87
|
+
repairs.push(`red_flags[${index}].escalation_route: '${requestedRoute}' → null (red flag ${base.verificationStatus} no accionable)`);
|
|
88
|
+
base.escalationRoute = null;
|
|
89
|
+
}
|
|
90
|
+
if (base.verificationStatus === 'denied' && !base.eventsConfirmed.length && echoesOwnPattern(base)) {
|
|
91
|
+
repairs.push(`red_flags[${index}] ('${base.name}'): denied sin evento confirmado y sin un related_ae `
|
|
92
|
+
+ 'distinto de su propia definición — la admisión del gate no lo autoriza');
|
|
93
|
+
}
|
|
94
|
+
return base;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function normalizeGateEscalation(raw, repairs) {
|
|
98
|
+
const urgent = raw?.urgent_under_24h === true;
|
|
99
|
+
let maxActionTimeHours = Number.isInteger(raw?.max_action_time_hours) ? raw.max_action_time_hours : null;
|
|
100
|
+
let escalationRoute = ESCALATION_ROUTES.includes(str(raw?.escalation_route).trim()) ? str(raw.escalation_route).trim() : null;
|
|
101
|
+
let reasonForEscalation = str(raw?.reason_for_escalation).trim() || null;
|
|
102
|
+
if (!urgent) {
|
|
103
|
+
const stray = [];
|
|
104
|
+
if (maxActionTimeHours !== null) { stray.push('max_action_time_hours'); maxActionTimeHours = null; }
|
|
105
|
+
if (escalationRoute !== null) { stray.push('escalation_route'); escalationRoute = null; }
|
|
106
|
+
if (reasonForEscalation !== null) { stray.push('reason_for_escalation'); reasonForEscalation = null; }
|
|
107
|
+
if (stray.length) repairs.push(`no urgente ⇒ anulados campos de escalamiento: ${stray.join(', ')}`);
|
|
108
|
+
}
|
|
109
|
+
return { urgent, maxActionTimeHours, escalationRoute, reasonForEscalation };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const routeUrgency = (route) => ESCALATION_ROUTES.indexOf(route);
|
|
113
|
+
|
|
114
|
+
const aliasKeySet = (catalog, terms) => new Set(terms.flatMap((term) => aliasClosure(catalog, term)));
|
|
115
|
+
|
|
116
|
+
function riskSymptomKeys(catalog, riskAssessment) {
|
|
117
|
+
return aliasKeySet(catalog, [
|
|
118
|
+
...arr(riskAssessment?.predictedAes)
|
|
119
|
+
.filter((ae) => ae?.severityIfConfirmed === 'emergency')
|
|
120
|
+
.flatMap((ae) => arr(ae.relatedSymptomTerms)),
|
|
121
|
+
...arr(riskAssessment?.diseaseRisks).flatMap((risk) => arr(risk?.relatedSymptomTerms)),
|
|
122
|
+
]);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const unverifiableFloor = (subject, reason) => ({
|
|
126
|
+
path: 'escalation_route',
|
|
127
|
+
code: ROUTE_FLOOR_UNVERIFIABLE_CODE,
|
|
128
|
+
warning: true,
|
|
129
|
+
problem: `${subject}: ${reason}; el gate no se elevó`,
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
function applyRouteFloor(escalation, {
|
|
133
|
+
catalog,
|
|
134
|
+
rows = [],
|
|
135
|
+
invalidRows = [],
|
|
136
|
+
affirmedKeys = new Set(),
|
|
137
|
+
riskAssessment = null,
|
|
138
|
+
riskReadFailed = false,
|
|
139
|
+
freeTextPending = false,
|
|
140
|
+
configError = null,
|
|
141
|
+
} = {}, repairs = [], warnings = []) {
|
|
142
|
+
if (configError) {
|
|
143
|
+
warnings.push(unverifiableFloor('rutas mínimas no verificables', `no se pudo leer RED_FLAG_MIN_ROUTES (${configError})`));
|
|
144
|
+
return escalation;
|
|
145
|
+
}
|
|
146
|
+
if (invalidRows.length) {
|
|
147
|
+
warnings.push({
|
|
148
|
+
path: 'escalation_route',
|
|
149
|
+
code: ROUTE_FLOOR_UNVERIFIABLE_CODE,
|
|
150
|
+
warning: true,
|
|
151
|
+
problem: `rutas mínimas incompletas: se ignoraron filas inválidas de RED_FLAG_MIN_ROUTES (${invalidRows.join('; ')}); esas filas no pueden elevar el gate`,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const riskKeys = riskSymptomKeys(catalog, riskAssessment);
|
|
155
|
+
const fired = [];
|
|
156
|
+
for (const row of rows) {
|
|
157
|
+
const termKeys = [...aliasKeySet(catalog, row.ctcaeTerms)];
|
|
158
|
+
const eligibleKeys = termKeys.filter((key) => !row.requiresRisk || riskKeys.has(key));
|
|
159
|
+
if (eligibleKeys.some((key) => affirmedKeys.has(key))) {
|
|
160
|
+
fired.push(row);
|
|
161
|
+
} else if (row.requiresRisk && !riskAssessment && termKeys.some((key) => affirmedKeys.has(key))) {
|
|
162
|
+
const reason = riskReadFailed ? 'no se pudo leer el perfil de riesgo' : 'no hay perfil de riesgo';
|
|
163
|
+
warnings.push(unverifiableFloor(`ruta mínima ${row.minRoute} de ${row.flag} no verificable`, reason));
|
|
164
|
+
} else if (freeTextPending && eligibleKeys.length) {
|
|
165
|
+
warnings.push(unverifiableFloor(`ruta mínima ${row.minRoute} de ${row.flag} no verificable`, 'el clasificador del texto libre no ha terminado'));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!fired.length) return escalation;
|
|
169
|
+
const currentRoute = escalation.urgent ? escalation.escalationRoute : null;
|
|
170
|
+
const currentHours = escalation.urgent ? escalation.maxActionTimeHours : null;
|
|
171
|
+
const floorRoute = fired.map((row) => row.minRoute).sort((left, right) => routeUrgency(left) - routeUrgency(right))[0];
|
|
172
|
+
const floorHours = Math.min(...fired.map((row) => row.maxActionTimeHours));
|
|
173
|
+
const route = currentRoute && routeUrgency(currentRoute) <= routeUrgency(floorRoute) ? currentRoute : floorRoute;
|
|
174
|
+
const hours = Number.isInteger(currentHours) ? Math.min(currentHours, floorHours) : floorHours;
|
|
175
|
+
const routeRaised = route !== currentRoute;
|
|
176
|
+
const windowTightened = hours !== currentHours;
|
|
177
|
+
if (!routeRaised && !windowTightened) return escalation;
|
|
178
|
+
const flags = [...new Set(fired
|
|
179
|
+
.filter((row) => (routeRaised && row.minRoute === route) || (windowTightened && row.maxActionTimeHours === hours))
|
|
180
|
+
.map((row) => row.flag))].join(', ');
|
|
181
|
+
const changes = [
|
|
182
|
+
routeRaised ? `escalation_route ${currentRoute ? `'${currentRoute}'` : 'null'} → '${route}'` : null,
|
|
183
|
+
windowTightened ? `max_action_time_hours ${currentHours ?? 'null'} → ${hours}` : null,
|
|
184
|
+
escalation.urgent ? null : 'urgent_under_24h false → true',
|
|
185
|
+
].filter(Boolean);
|
|
186
|
+
repairs.push(`ruta mínima por término reportado (${flags}): ${changes.join(', ')}`);
|
|
187
|
+
return {
|
|
188
|
+
...escalation,
|
|
189
|
+
urgent: true,
|
|
190
|
+
maxActionTimeHours: hours,
|
|
191
|
+
escalationRoute: route,
|
|
192
|
+
reasonForEscalation: escalation.reasonForEscalation || `Término reportado en este triaje (${flags}): ruta mínima ${route}, máximo ${hours} h.`,
|
|
193
|
+
summary: [str(escalation.summary).trim(), `Ruta mínima aplicada por un término reportado en este triaje (${flags}): ${route}, máximo ${hours} h.`]
|
|
194
|
+
.filter(Boolean)
|
|
195
|
+
.join(' '),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = {
|
|
200
|
+
str,
|
|
201
|
+
arr,
|
|
202
|
+
echoesOwnPattern,
|
|
203
|
+
derivedStatus,
|
|
204
|
+
normalizeStatus,
|
|
205
|
+
buildRedFlag,
|
|
206
|
+
normalizeGateEscalation,
|
|
207
|
+
applyRouteFloor,
|
|
208
|
+
};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
const { str, arr, strList } = require('../../utils/coercionUtils');
|
|
2
|
+
|
|
3
|
+
const num = (value) => (Number.isInteger(value) ? value : null);
|
|
4
|
+
const nullableStr = (value) => str(value).trim() || null;
|
|
5
|
+
const inEnum = (value, values) => (values.includes(str(value).trim()) ? str(value).trim() : null);
|
|
6
|
+
|
|
7
|
+
const SENTENCE_END = /[.!?](?=\s|$)/g;
|
|
8
|
+
const SENTENCE_PROTECT = /\b(?:\d+\.\d+|p\.\s?ej\.|Dr\.|Dra\.|etc\.)/gi;
|
|
9
|
+
|
|
10
|
+
function sentenceCount(text) {
|
|
11
|
+
const protectedText = text.trim().replace(SENTENCE_PROTECT, (match) => match.replace(/\./g, '·'));
|
|
12
|
+
return (protectedText.match(SENTENCE_END) || []).length;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Only ";" delimits criteria: a comma usually sits inside one.
|
|
16
|
+
function trimEscalationText(text) {
|
|
17
|
+
if (text.length <= 90) return text;
|
|
18
|
+
let out = '';
|
|
19
|
+
for (const part of text.split(';').map((piece) => piece.trim()).filter(Boolean)) {
|
|
20
|
+
const candidate = out ? `${out}; ${part}` : part;
|
|
21
|
+
if (candidate.length > 90) break;
|
|
22
|
+
out = candidate;
|
|
23
|
+
}
|
|
24
|
+
if (out) return out;
|
|
25
|
+
// A hard slice can turn a clinical condition into an unsafe fragment. Keep
|
|
26
|
+
// the original so validation can request a complete rewrite instead.
|
|
27
|
+
return text;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function buildSymptom(raw) {
|
|
31
|
+
return {
|
|
32
|
+
ctcaeTerm: str(raw?.ctcae_term).trim(),
|
|
33
|
+
grade: num(raw?.grade),
|
|
34
|
+
verificationStatus: str(raw?.verification_status).trim() || 'suspected',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function buildOtcOffer(raw) {
|
|
39
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
40
|
+
return {
|
|
41
|
+
label: str(raw?.label).trim(),
|
|
42
|
+
dose: nullableStr(raw?.dose),
|
|
43
|
+
frequency: nullableStr(raw?.frequency),
|
|
44
|
+
duration: nullableStr(raw?.duration),
|
|
45
|
+
warnings: nullableStr(raw?.warnings),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildElement(raw, repairs) {
|
|
50
|
+
const rawRec = raw?.recommendation || {};
|
|
51
|
+
const rawPatient = rawRec?.patient || {};
|
|
52
|
+
const patient = {
|
|
53
|
+
mainRecommendation: str(rawPatient?.main_recommendation).trim(),
|
|
54
|
+
whenToEscalate: nullableStr(rawPatient?.when_to_escalate),
|
|
55
|
+
contraindications: nullableStr(rawPatient?.contraindications),
|
|
56
|
+
expectedEffectiveness: inEnum(rawPatient?.expected_effectiveness, ['low', 'medium', 'high']),
|
|
57
|
+
};
|
|
58
|
+
if (patient.whenToEscalate && patient.whenToEscalate.length > 90) {
|
|
59
|
+
const trimmed = trimEscalationText(patient.whenToEscalate);
|
|
60
|
+
if (trimmed !== patient.whenToEscalate) {
|
|
61
|
+
repairs.push(`when_to_escalate (rank ${raw?.rank ?? '?'}) recortado de ${patient.whenToEscalate.length} a ≤90 caracteres en límite de criterio completo`);
|
|
62
|
+
patient.whenToEscalate = trimmed;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const recommendation = {
|
|
66
|
+
symptomsPatientFacing: strList(rawRec?.symptoms_patient_facing),
|
|
67
|
+
isPharmacologicalMedNeeded: rawRec?.is_pharmacological_med_needed === true,
|
|
68
|
+
patient,
|
|
69
|
+
otcOffer: buildOtcOffer(rawRec?.otc_offer),
|
|
70
|
+
followup: inEnum(rawRec?.followup, ['checkin_48h', 'team_referral', 'none']),
|
|
71
|
+
followupUrgency: nullableStr(rawRec?.followup_urgency),
|
|
72
|
+
};
|
|
73
|
+
const rawEsc = raw?.escalation || {};
|
|
74
|
+
return {
|
|
75
|
+
rank: num(raw?.rank) || 0,
|
|
76
|
+
type: str(raw?.type).trim(),
|
|
77
|
+
nameShort: str(raw?.name_short).trim(),
|
|
78
|
+
timeWindow: nullableStr(raw?.time_window),
|
|
79
|
+
symptoms: arr(raw?.symptoms).map(buildSymptom),
|
|
80
|
+
targetedCtcaeTerms: strList(raw?.targeted_ctcae_terms),
|
|
81
|
+
whyRelevant: str(raw?.why_relevant).trim(),
|
|
82
|
+
qolImpact: inEnum(raw?.qol_impact, ['low', 'moderate', 'high']),
|
|
83
|
+
improvementCapacity: inEnum(raw?.improvement_capacity, ['low', 'moderate', 'high']),
|
|
84
|
+
characterizationNeeded: typeof raw?.characterization_is_needed === 'boolean' ? raw.characterization_is_needed : null,
|
|
85
|
+
minCharacterizationVariables: strList(raw?.min_characterization_variables),
|
|
86
|
+
escalation: {
|
|
87
|
+
urgentUnder24h: rawEsc?.urgent_under_24h === true,
|
|
88
|
+
maxActionTimeHours: num(rawEsc?.max_action_time_hours),
|
|
89
|
+
routes: strList(rawEsc?.routes).map((route) => route.trim()).filter(Boolean),
|
|
90
|
+
clinicalCriteria: nullableStr(rawEsc?.clinical_criteria),
|
|
91
|
+
},
|
|
92
|
+
recommendation,
|
|
93
|
+
groundedIn: strList(raw?.grounded_in),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = {
|
|
98
|
+
str,
|
|
99
|
+
arr,
|
|
100
|
+
nullableStr,
|
|
101
|
+
sentenceCount,
|
|
102
|
+
trimEscalationText,
|
|
103
|
+
buildElement,
|
|
104
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const DEGRADED_NUMERIC_REASON = 'observations_should_have_been_passed_text_contains_numbers — patient_verbatim contains a numeric+unit pattern (e.g. \'8.5 g/dL\'); pass these as `observations: [{code, value, unit, effective}]` so the audit lane emits FHIR Observation + Provenance per fact.';
|
|
2
|
+
|
|
3
|
+
const DEGRADED_SUPPRESSED_REASON = 'observations_were_supplied_but_not_stored — the audit lane suppressed the FHIR write for this turn, so no Observation or Provenance was persisted. The observations were passed correctly; re-issuing the call will not change this.';
|
|
4
|
+
|
|
5
|
+
const NUMERIC_VALUE_PATTERN = new RegExp(
|
|
6
|
+
'\\d+(?:\\.\\d+)?\\s*(?:'
|
|
7
|
+
+ 'g/dL|mg/dL|mmol/L|umol/L|mEq/L|ng/mL|pg/mL|ug/mL|ug/dL'
|
|
8
|
+
+ '|10\\^?\\*?[0-9]+/[a-zA-Z]+'
|
|
9
|
+
+ '|K/uL|/uL|/mm3'
|
|
10
|
+
+ '|U/L|IU/L'
|
|
11
|
+
+ '|mmHg|cmH2O'
|
|
12
|
+
+ '|bpm|/min|rpm'
|
|
13
|
+
+ '|°C|°F|Cel'
|
|
14
|
+
+ '|(?:kg|mg|ug|mL|dL|cm|mm)\\b'
|
|
15
|
+
+ '|%'
|
|
16
|
+
+ ')',
|
|
17
|
+
'i',
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
function patientVerbatimHasNumericValues(text) {
|
|
21
|
+
if (!text || typeof text !== 'string') return false;
|
|
22
|
+
return NUMERIC_VALUE_PATTERN.test(text);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const VERBATIM_SOURCES = ['patient_text', 'image_analysis', 'audio_transcript'];
|
|
26
|
+
|
|
27
|
+
const SOURCE_PROVENANCE = {
|
|
28
|
+
image_analysis: 'Valores leídos por el sistema de una foto que envió el paciente; NO son palabras suyas',
|
|
29
|
+
audio_transcript: 'Transcripción de un audio que envió el paciente; NO es un mensaje escrito'
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function resolveVerbatimSource(value) {
|
|
33
|
+
return VERBATIM_SOURCES.includes(value) ? value : 'patient_text';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function stampProvenance(text, source) {
|
|
37
|
+
const label = SOURCE_PROVENANCE[source];
|
|
38
|
+
return label ? `[${label}]\n${text}` : text;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function slugify(value, maxLen = 32) {
|
|
42
|
+
if (!value) return '';
|
|
43
|
+
const stripped = value.normalize('NFKD').replace(/[̀-ͯ]/g, '');
|
|
44
|
+
const hyphenated = stripped.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase();
|
|
45
|
+
return hyphenated.slice(0, maxLen).replace(/^-+|-+$/g, '');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
module.exports = {
|
|
49
|
+
DEGRADED_NUMERIC_REASON,
|
|
50
|
+
DEGRADED_SUPPRESSED_REASON,
|
|
51
|
+
VERBATIM_SOURCES,
|
|
52
|
+
patientVerbatimHasNumericValues,
|
|
53
|
+
resolveVerbatimSource,
|
|
54
|
+
slugify,
|
|
55
|
+
stampProvenance,
|
|
56
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const { objectArg } = require('../../utils/jsonUtils');
|
|
2
|
+
const { isToolFailure } = require('./toolResultHelper');
|
|
3
|
+
|
|
4
|
+
const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
|
|
5
|
+
const CHARACTERIZATION_TOOLS = ['extractClinicalInfo', ...IMPRESSION_TOOLS, 'reportMedicalEscalation'];
|
|
6
|
+
const MAX_PATIENT_TEXT = 500;
|
|
7
|
+
|
|
8
|
+
const textOf = (value) => {
|
|
9
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
10
|
+
return text && text.toLowerCase() !== 'none' ? text : null;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const gradeOf = (gradeEstimate) => {
|
|
14
|
+
const grade = objectArg(gradeEstimate)?.best_estimate;
|
|
15
|
+
return Number.isInteger(grade) ? grade : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const impressionOf = (call) => {
|
|
19
|
+
const args = objectArg(call.tool_arguments) || {};
|
|
20
|
+
const result = objectArg(call.tool_output)?.data;
|
|
21
|
+
return {
|
|
22
|
+
caseId: textOf(args.case_id) || textOf(result?.case_id),
|
|
23
|
+
ctcaeTerm: textOf(args.ctcae_term),
|
|
24
|
+
event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
|
|
25
|
+
grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
|
|
26
|
+
trajectory: textOf(args.trajectory_direction),
|
|
27
|
+
missingForHigherGrade: textOf(args.missing_for_higher_grade),
|
|
28
|
+
checkInQuestion: textOf(args.check_in_question),
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
|
|
33
|
+
|
|
34
|
+
function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
|
|
35
|
+
const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
|
|
36
|
+
const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
|
|
37
|
+
const safetyFlags = (Array.isArray(signals?.safetyFlags) ? signals.safetyFlags : []).map(flagNameOf).filter(Boolean);
|
|
38
|
+
const assessed = calls.some((call) => call.tool_name !== 'extractClinicalInfo');
|
|
39
|
+
if (!turnId || (!assessed && mentionCount === 0 && !safetyFlags.length)) return null;
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
turnId,
|
|
43
|
+
tools: [...new Set(calls.map((call) => call.tool_name))],
|
|
44
|
+
patientText: textOf(patientText)?.slice(0, MAX_PATIENT_TEXT) || null,
|
|
45
|
+
impressions: calls.filter((call) => IMPRESSION_TOOLS.includes(call.tool_name)).map(impressionOf),
|
|
46
|
+
safetyFlags,
|
|
47
|
+
at,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function characterizationSeedOf(updates = []) {
|
|
52
|
+
if (!Array.isArray(updates) || !updates.length) return null;
|
|
53
|
+
const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
|
|
54
|
+
const latestByCase = new Map();
|
|
55
|
+
byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
|
|
56
|
+
const key = impression.caseId || impression.ctcaeTerm;
|
|
57
|
+
if (key) latestByCase.set(key, { ...impression, at: update.at });
|
|
58
|
+
}));
|
|
59
|
+
return {
|
|
60
|
+
cases: [...latestByCase.values()],
|
|
61
|
+
safetyFlags: [...new Set(updates.flatMap((update) => update.safetyFlags || []))],
|
|
62
|
+
newSinceEscalation: byTime
|
|
63
|
+
.filter((update) => update.patientText)
|
|
64
|
+
.map((update) => ({ at: update.at, patientText: update.patientText })),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = { characterizationSeedOf, reviewUpdateOf };
|
|
@@ -1,11 +1,7 @@
|
|
|
1
|
-
const { AsyncLocalStorage } = require('async_hooks');
|
|
2
|
-
|
|
3
1
|
const { Thread } = require('../../models/threadModel');
|
|
4
|
-
|
|
2
|
+
const { runInShadowScope, isShadowRun } = require('../../utils/shadowScope');
|
|
5
3
|
const { getShadowPresetId } = require('../flags/shadowConfig');
|
|
6
4
|
|
|
7
|
-
const shadowStorage = new AsyncLocalStorage();
|
|
8
|
-
|
|
9
5
|
function cloneShadowThread(thread) {
|
|
10
6
|
const base = thread.toObject();
|
|
11
7
|
delete base._id;
|
|
@@ -17,14 +13,6 @@ function cloneShadowThread(thread) {
|
|
|
17
13
|
});
|
|
18
14
|
}
|
|
19
15
|
|
|
20
|
-
function runInShadowScope(fn) {
|
|
21
|
-
return shadowStorage.run(true, fn);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function isShadowRun() {
|
|
25
|
-
return shadowStorage.getStore() === true;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
16
|
module.exports = {
|
|
29
17
|
cloneShadowThread,
|
|
30
18
|
runInShadowScope,
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const { loadSkillBody } = require('../services/skillService');
|
|
2
|
+
const { logger } = require('../../utils/logger');
|
|
3
|
+
|
|
4
|
+
const { SKILL_TOOL } = require('./clinicalWorkflowGuard');
|
|
5
|
+
|
|
6
|
+
function markSkillActivated(runtime, name) {
|
|
7
|
+
runtime?.activatedSkills?.add(name);
|
|
8
|
+
if (runtime?.skillActivationIteration && !runtime.skillActivationIteration.has(name)) {
|
|
9
|
+
runtime.skillActivationIteration.set(name, runtime.currentIteration ?? null);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Hands the model a skill the workflow guard is about to require, inside the result of the tool that made it
|
|
14
|
+
// required, so the turn does not spend an iteration being refused and then asking for it. The guard stays the net.
|
|
15
|
+
async function attachRequiredSkill(runtime, name) {
|
|
16
|
+
if (!runtime || !name) return null;
|
|
17
|
+
if (!(runtime.enabledSkills || []).includes(name)) return null;
|
|
18
|
+
if (!(runtime.trace?.signals?.offeredToolIds || []).includes(SKILL_TOOL)) return null;
|
|
19
|
+
if (runtime.activatedSkills?.has(name)) return null;
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
const { skill } = await loadSkillBody(name);
|
|
23
|
+
if (!skill) return null;
|
|
24
|
+
markSkillActivated(runtime, skill.name);
|
|
25
|
+
runtime.trace?.setSignals?.({ attachedSkills: [...(runtime.trace.signals?.attachedSkills || []), skill.name] });
|
|
26
|
+
return { name: skill.name, version: skill.version, body: skill.body };
|
|
27
|
+
} catch (error) {
|
|
28
|
+
logger.warn('[skillActivation] required skill could not be attached; the guard will ask for it', {
|
|
29
|
+
skill: name, turnId: runtime.turnId || null, error: error?.message,
|
|
30
|
+
});
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// A skill body governs only the turn it was handed over in. Outside that turn (history replay, monitor evidence)
|
|
36
|
+
// the attachment is dropped, as for a Skill call, whose output is never replayed.
|
|
37
|
+
function withoutAttachedSkillBodies(output) {
|
|
38
|
+
let parsed = output;
|
|
39
|
+
if (typeof output === 'string') {
|
|
40
|
+
try { parsed = JSON.parse(output); } catch (error) { return output; }
|
|
41
|
+
}
|
|
42
|
+
const skills = parsed?.data?.activated_skills;
|
|
43
|
+
if (!Array.isArray(skills)) return output;
|
|
44
|
+
const { activated_skills: _attached, ...data } = parsed.data;
|
|
45
|
+
const stripped = { ...parsed, data };
|
|
46
|
+
return typeof output === 'string' ? JSON.stringify(stripped) : stripped;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = {
|
|
50
|
+
attachRequiredSkill,
|
|
51
|
+
markSkillActivated,
|
|
52
|
+
withoutAttachedSkillBodies,
|
|
53
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Every structured sub-agent reads its text back the same way: the envelope carries output_text
|
|
2
|
+
// when the provider flattened it, and otherwise the text lives in the first message part. Keeping
|
|
3
|
+
// one copy is what stops two services from disagreeing when a provider envelope changes.
|
|
4
|
+
function readStructuredText(result) {
|
|
5
|
+
if (result?.output_text) return result.output_text;
|
|
6
|
+
const output = Array.isArray(result?.output) ? result.output : [];
|
|
7
|
+
const message = output.find((item) => item.type === 'message');
|
|
8
|
+
const content = Array.isArray(message?.content) ? message.content : [];
|
|
9
|
+
const part = content.find((candidate) => typeof candidate?.text === 'string');
|
|
10
|
+
return part?.text || '';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
module.exports = { readStructuredText };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const { safeParse } = require('../../utils/jsonUtils');
|
|
2
|
+
|
|
3
|
+
function parseToolResult(output) {
|
|
4
|
+
if (typeof output === 'string') return safeParse(output, null);
|
|
5
|
+
if (output && typeof output === 'object' && !Array.isArray(output)) return output;
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function isToolFailure(output) {
|
|
10
|
+
return parseToolResult(output)?.success === false;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function toolFailureError(output, fallback = 'Tool execution failed') {
|
|
14
|
+
const error = parseToolResult(output)?.error;
|
|
15
|
+
return typeof error === 'string' && error ? error : fallback;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function toolRecoveryContract(output) {
|
|
19
|
+
const payload = parseToolResult(output);
|
|
20
|
+
const requiredToolIds = payload?.data?.required_tool_ids;
|
|
21
|
+
if (payload?.success !== false || !Array.isArray(requiredToolIds) || requiredToolIds.length === 0) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
error: typeof payload.error === 'string' ? payload.error : 'tool_recovery_unavailable',
|
|
26
|
+
requiredToolIds,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = {
|
|
31
|
+
isToolFailure,
|
|
32
|
+
parseToolResult,
|
|
33
|
+
toolFailureError,
|
|
34
|
+
toolRecoveryContract,
|
|
35
|
+
};
|