@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
|
@@ -1,23 +1,79 @@
|
|
|
1
|
+
const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
|
|
2
|
+
const { compactTriageResult, isTriageResultMessage } = require('../helpers/triageResultMessageHelper');
|
|
3
|
+
const { parseChemoContext, renderChemoContext, withChemoContext } = require('../helpers/chemoContextHelper');
|
|
1
4
|
const { handlePendingFunctionCalls: handlePendingFunctionCallsUtil } = require('../providers/OpenAIResponsesProviderTools');
|
|
5
|
+
|
|
6
|
+
const { assembleRiskHeadline } = require('../services/riskHeadlineService');
|
|
7
|
+
const { resolveNutritionPlan } = require('../services/nutritionPlanService');
|
|
8
|
+
const { identityError } = require('../services/patientIdentityService');
|
|
9
|
+
const { resolveProfileIdentity } = require('../services/patientProfileService');
|
|
10
|
+
const { chemoContextLive } = require('../flags/clinicalContextFlags');
|
|
2
11
|
const { Follow_Up_ID } = require('../../config/airtableConfig');
|
|
12
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
3
13
|
|
|
4
14
|
const { logger } = require('../../utils/logger');
|
|
15
|
+
const { escapePatientMessageMarkers, formatPatientMessage } = require('../../helpers/patientMessageHelper');
|
|
5
16
|
|
|
6
17
|
const { getMessageTools, formatMessage } = require('../../helpers/messageHelper');
|
|
18
|
+
const { messagesWithAcceptedAttempt } = require('../../helpers/deliveryAttemptHelper');
|
|
7
19
|
|
|
20
|
+
const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
21
|
+
const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
|
|
8
22
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
9
|
-
const {
|
|
10
|
-
const
|
|
23
|
+
const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
|
|
24
|
+
const { getMessages, countMessages } = require('../../services/messageService');
|
|
25
|
+
const { hasInstructionInFlight } = require('../../services/instructionInFlightService');
|
|
26
|
+
const { isStaffSend } = require('../../helpers/staffSendHelper');
|
|
27
|
+
const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
|
|
28
|
+
const { CURRENT_TURN } = require('../promptPlacement');
|
|
29
|
+
|
|
30
|
+
const { DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../../models/deliveryAttemptModel');
|
|
31
|
+
|
|
11
32
|
const { MemoryManager } = require('./MemoryManager');
|
|
12
33
|
|
|
13
34
|
const DEFAULT_MAX_HISTORICAL_MESSAGES = 50;
|
|
14
|
-
const
|
|
35
|
+
const DEFAULT_CONTEXT_ANCHOR_STEP = 50;
|
|
36
|
+
const OPERATOR_TURN_PREFIX = '[sistema]';
|
|
37
|
+
const TEAM_TURN_PREFIX = '[equipo]';
|
|
38
|
+
const PLATFORM_TURN_PREFIX = '[plataforma]';
|
|
39
|
+
const CAREGIVER_TURN_PREFIX = '[cuidador]';
|
|
40
|
+
const CURRENT_TURN_GAP_MS = 15 * 60 * 1000;
|
|
41
|
+
const CURRENT_TURN_MAX_MESSAGES = 15;
|
|
42
|
+
const OUTBOUND_TAIL_MAX_MESSAGES = 10;
|
|
43
|
+
const OUTBOUND_TAIL_SCAN_MESSAGES = 50;
|
|
44
|
+
const TURN_TIMESTAMP_PREFIX_RX = /^\[[^\]]*\]\s*/;
|
|
45
|
+
|
|
46
|
+
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|
|
47
|
+
|
|
48
|
+
const inline = (value) => sanitizeInlineText(value, Infinity);
|
|
49
|
+
|
|
50
|
+
const PENDING_INSTRUCTION_NOTE = `${OPERATOR_TURN_PREFIX} Hay un mensaje del sistema en curso para el paciente (por ejemplo, la confirmación de los botones que acaba de tocar) que se le enviará por separado. No lo anticipes ni lo confirmes tú; responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
|
|
51
|
+
|
|
52
|
+
const deliveredWhileWaitingNote = (text) =>
|
|
53
|
+
`${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
|
|
54
|
+
|
|
55
|
+
function readComorbidities(value) {
|
|
56
|
+
const parsed = typeof value === 'string' ? safeParse(value, null) : value;
|
|
57
|
+
if (!isPlainObject(parsed)) return inline(value);
|
|
58
|
+
const current = inline(parsed.current);
|
|
59
|
+
const previous = inline(parsed.previous);
|
|
60
|
+
return [current, previous && `Previas: ${previous}`].filter(Boolean).join(' ');
|
|
61
|
+
}
|
|
15
62
|
|
|
16
63
|
class DefaultMemoryManager extends MemoryManager {
|
|
17
64
|
constructor(options = {}) {
|
|
18
65
|
super(options);
|
|
19
66
|
const maxHistoricalMessages = parseInt(runtimeConfig.get('MAX_HISTORICAL_MESSAGES'), 10) || DEFAULT_MAX_HISTORICAL_MESSAGES;
|
|
20
67
|
this.maxHistoricalMessages = options.maxHistoricalMessages || maxHistoricalMessages;
|
|
68
|
+
const anchorStep = parseInt(runtimeConfig.get('MAX_HISTORICAL_ANCHOR_STEP'), 10) || DEFAULT_CONTEXT_ANCHOR_STEP;
|
|
69
|
+
this.contextAnchorStep = Math.max(1, options.contextAnchorStep || anchorStep);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
_windowSize(total) {
|
|
73
|
+
if (!Number.isFinite(total) || total <= 0) return this.maxHistoricalMessages;
|
|
74
|
+
const overflow = Math.max(0, total - this.maxHistoricalMessages);
|
|
75
|
+
const anchor = Math.floor(overflow / this.contextAnchorStep) * this.contextAnchorStep;
|
|
76
|
+
return total - anchor;
|
|
21
77
|
}
|
|
22
78
|
|
|
23
79
|
async buildContext({ thread, message = null, config = {} }) {
|
|
@@ -27,25 +83,68 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
27
83
|
const beforeCheckpoint = config.beforeCheckpoint ?? message?.createdAt ?? null;
|
|
28
84
|
const query = { numero: thread.code, origin: { $ne: 'instruction' } };
|
|
29
85
|
if (beforeCheckpoint) query.createdAt = { [config.beforeOperator || '$lte']: beforeCheckpoint };
|
|
30
|
-
const
|
|
86
|
+
const total = await countMessages(query);
|
|
87
|
+
const allMessages = await getMessages(query, {
|
|
88
|
+
sort: { createdAt: -1 },
|
|
89
|
+
limit: this._windowSize(total),
|
|
90
|
+
});
|
|
31
91
|
const additional = config.additionalMessages || [];
|
|
32
92
|
|
|
33
93
|
if (!allMessages?.length) {
|
|
34
94
|
return additional;
|
|
35
95
|
}
|
|
36
96
|
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
97
|
+
const ordered = allMessages.reverse();
|
|
98
|
+
const currentTurn = this._currentTurnMessages(ordered);
|
|
99
|
+
const turnStart = ordered.length - currentTurn.length;
|
|
100
|
+
|
|
101
|
+
const skipTools = new Set(getTurnScopedToolNames());
|
|
102
|
+
const replayArgs = getReplayArgsByTool();
|
|
103
|
+
const latestTriage = config.compactOlderTriage ? ordered.findLastIndex(msg => isTriageResultMessage(msg.body)) : -1;
|
|
104
|
+
|
|
105
|
+
const context = ordered.flatMap((msg, index) => {
|
|
106
|
+
const toolItems = getMessageTools(msg, { skipTools, replayArgs });
|
|
107
|
+
if (index >= turnStart) return toolItems;
|
|
108
|
+
const role = this._resolveContextRole(msg);
|
|
109
|
+
const prefix = this._speakerPrefix(msg, role);
|
|
110
|
+
const shown = index < latestTriage ? { ...msg, body: compactTriageResult(msg.body) } : msg;
|
|
111
|
+
const contentItems = formatMessage(shown)
|
|
112
|
+
.filter(Boolean)
|
|
40
113
|
.map(content => ({
|
|
41
|
-
role
|
|
42
|
-
content: content
|
|
114
|
+
role,
|
|
115
|
+
content: `${prefix}${content}`,
|
|
43
116
|
type: 'message'
|
|
44
|
-
}))
|
|
45
|
-
.filter(item => item.content);
|
|
117
|
+
}));
|
|
46
118
|
return [...toolItems, ...contentItems];
|
|
47
119
|
});
|
|
48
120
|
|
|
121
|
+
const turnLines = currentTurn
|
|
122
|
+
.flatMap(msg => formatMessage(msg)
|
|
123
|
+
.filter(Boolean)
|
|
124
|
+
.map(line => `${this._speakerPrefix(msg, 'user')}${line.replace(TURN_TIMESTAMP_PREFIX_RX, '')}`))
|
|
125
|
+
.map(escapePatientMessageMarkers);
|
|
126
|
+
if (turnLines.length) {
|
|
127
|
+
context.push({
|
|
128
|
+
[CURRENT_TURN]: true,
|
|
129
|
+
role: 'user',
|
|
130
|
+
content: formatPatientMessage(turnLines),
|
|
131
|
+
type: 'message'
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
for (const msg of await this._outboundTail(thread.code, beforeCheckpoint, config)) {
|
|
136
|
+
for (const content of formatMessage(msg).filter(Boolean)) {
|
|
137
|
+
const line = msg.origin === 'assistant'
|
|
138
|
+
? deliveredWhileWaitingNote(content.replace(TURN_TIMESTAMP_PREFIX_RX, ''))
|
|
139
|
+
: `${this._speakerPrefix(msg, null)}${content}`;
|
|
140
|
+
context.push({ [CURRENT_TURN]: true, role: 'user', content: line, type: 'message' });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (this._hasPendingInstruction(thread.code, beforeCheckpoint, config)) {
|
|
145
|
+
context.push({ [CURRENT_TURN]: true, role: 'user', content: PENDING_INSTRUCTION_NOTE, type: 'message' });
|
|
146
|
+
}
|
|
147
|
+
|
|
49
148
|
return [...context, ...additional];
|
|
50
149
|
} catch (error) {
|
|
51
150
|
logger.error('[DefaultMemoryManager] Context building failed', { threadCode: thread.code, error: error.message });
|
|
@@ -53,17 +152,76 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
53
152
|
}
|
|
54
153
|
}
|
|
55
154
|
|
|
155
|
+
_hasPendingInstruction(code, beforeCheckpoint, config) {
|
|
156
|
+
return Boolean(beforeCheckpoint) && !config.beforeCheckpoint && hasInstructionInFlight(code);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async _outboundTail(code, beforeCheckpoint, config) {
|
|
160
|
+
const upperBound = config.tailUpperBound ?? (config.beforeCheckpoint ? null : new Date());
|
|
161
|
+
if (!beforeCheckpoint || !upperBound) return [];
|
|
162
|
+
|
|
163
|
+
const window = { numero: code, createdAt: { $gt: beforeCheckpoint, $lte: upperBound } };
|
|
164
|
+
const newest = { sort: { createdAt: -1 }, limit: OUTBOUND_TAIL_MAX_MESSAGES };
|
|
165
|
+
const [team, replies] = await Promise.all([
|
|
166
|
+
getMessages({ ...window, origin: 'whatsapp_platform' }, newest),
|
|
167
|
+
getMessages(
|
|
168
|
+
{ ...window, origin: 'assistant', 'statusInfo.status': { $nin: UNDELIVERED_STATUSES } },
|
|
169
|
+
{ ...newest, limit: OUTBOUND_TAIL_SCAN_MESSAGES },
|
|
170
|
+
),
|
|
171
|
+
]);
|
|
172
|
+
const transportConfirmed = (msg) => Boolean(msg.message_id) || DELIVERY_ATTEMPT_LANDED_STATUSES.includes(msg.statusInfo?.status);
|
|
173
|
+
const accepted = await messagesWithAcceptedAttempt(replies.filter(m => !transportConfirmed(m)).map(m => m._id));
|
|
174
|
+
const delivered = replies
|
|
175
|
+
.filter(m => transportConfirmed(m) || accepted.has(String(m._id)))
|
|
176
|
+
.slice(0, OUTBOUND_TAIL_MAX_MESSAGES);
|
|
177
|
+
return [...team, ...delivered].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_currentTurnMessages(ordered) {
|
|
181
|
+
const turn = [];
|
|
182
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
183
|
+
const msg = ordered[i];
|
|
184
|
+
if (msg.origin !== 'patient') break;
|
|
185
|
+
if (turn.length) {
|
|
186
|
+
const oldestTimestamp = Date.parse(turn[0].createdAt);
|
|
187
|
+
const candidateTimestamp = Date.parse(msg.createdAt);
|
|
188
|
+
if (!Number.isFinite(oldestTimestamp) || !Number.isFinite(candidateTimestamp)) break;
|
|
189
|
+
if (oldestTimestamp - candidateTimestamp > CURRENT_TURN_GAP_MS) break;
|
|
190
|
+
}
|
|
191
|
+
turn.unshift(msg);
|
|
192
|
+
if (turn.length >= CURRENT_TURN_MAX_MESSAGES) break;
|
|
193
|
+
}
|
|
194
|
+
return turn;
|
|
195
|
+
}
|
|
196
|
+
|
|
56
197
|
_resolveContextRole(msg) {
|
|
57
198
|
if (msg.origin === 'patient') return 'user';
|
|
58
199
|
if (msg.origin === 'system' && msg.raw?.role) {
|
|
59
200
|
const role = String(msg.raw.role).trim().toLowerCase();
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
201
|
+
if (role === 'developer') return 'developer';
|
|
202
|
+
if (role !== 'system') {
|
|
203
|
+
logger.warn('[DefaultMemoryManager] Unrecognized operator role, treating as an inline turn', { role: msg.raw.role });
|
|
204
|
+
}
|
|
205
|
+
return 'user';
|
|
63
206
|
}
|
|
64
207
|
return 'assistant';
|
|
65
208
|
}
|
|
66
209
|
|
|
210
|
+
_isInlineOperatorTurn(msg, role) {
|
|
211
|
+
return msg.origin === 'system' && role === 'user';
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
_speakerPrefix(msg, role) {
|
|
215
|
+
if (this._isInlineOperatorTurn(msg, role)) return `${OPERATOR_TURN_PREFIX} `;
|
|
216
|
+
if (msg.origin === 'patient' && msg.contact_role === 'caregiver') {
|
|
217
|
+
const label = String(msg.contact_label || '').replace(/[[\]\n]/g, '').trim();
|
|
218
|
+
return label ? `${CAREGIVER_TURN_PREFIX.slice(0, -1)}: ${label}] ` : `${CAREGIVER_TURN_PREFIX} `;
|
|
219
|
+
}
|
|
220
|
+
if (msg.origin !== 'whatsapp_platform') return '';
|
|
221
|
+
// Staff sign what they send with their email; anything else was an automation.
|
|
222
|
+
return isStaffSend(msg.triggeredBy) ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
|
|
223
|
+
}
|
|
224
|
+
|
|
67
225
|
async processResponse(response, thread) {
|
|
68
226
|
this._logActivity('Processing response', { threadCode: thread.code, responseId: response.id });
|
|
69
227
|
try {
|
|
@@ -118,21 +276,23 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
118
276
|
|
|
119
277
|
async _getClinicalContext(whatsappId) {
|
|
120
278
|
try {
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
279
|
+
const identity = await resolveProfileIdentity(whatsappId);
|
|
280
|
+
if (identity.kind === 'ambiguous') throw identityError(identity.kind);
|
|
281
|
+
const record = identity.record || {};
|
|
282
|
+
const symptomsRecords = await getRecordByFilter(Follow_Up_ID, 'all_triages_last_month', fieldEquals('whatsapp_id', whatsappId));
|
|
125
283
|
|
|
126
|
-
const clinicalContext =
|
|
127
|
-
? JSON.parse(
|
|
284
|
+
const clinicalContext = record['clinical-context-json']
|
|
285
|
+
? JSON.parse(record['clinical-context-json'])
|
|
128
286
|
: null;
|
|
287
|
+
const treatingPhysician = sanitizeInlineText(record.doctor || '', Infinity);
|
|
288
|
+
const chemo = chemoContextLive() ? parseChemoContext(record.quimio_context) : null;
|
|
129
289
|
|
|
130
290
|
const sortedSymptoms = symptomsRecords?.filter(r => r.Date)
|
|
131
291
|
.sort((a, b) => new Date(b.Date) - new Date(a.Date)).slice(0, 3) || [];
|
|
132
292
|
|
|
133
293
|
const symptoms = this._parseSymptoms(sortedSymptoms);
|
|
134
294
|
|
|
135
|
-
return { ...clinicalContext, symptoms };
|
|
295
|
+
return { ...clinicalContext, symptoms, treatingPhysician, chemo };
|
|
136
296
|
} catch (error) {
|
|
137
297
|
logger.error('[DefaultMemoryManager] Error fetching clinical context', { error: error.message });
|
|
138
298
|
return null;
|
|
@@ -142,53 +302,65 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
142
302
|
_parseSymptoms(records) {
|
|
143
303
|
if (!records?.length) return [];
|
|
144
304
|
|
|
145
|
-
const toArray = (val, parser = v => v) => {
|
|
146
|
-
if (typeof val === 'string') return val.split(',').map(s => parser(s.trim()));
|
|
147
|
-
return Array.isArray(val) ? val.map(parser) : [parser(val)];
|
|
148
|
-
};
|
|
149
|
-
|
|
150
305
|
return records.map(record => {
|
|
151
|
-
const { Date: date,
|
|
152
|
-
|
|
306
|
+
const { Date: date, short_recommendations: recs } = record;
|
|
307
|
+
const { symptoms: paired } = pairTriageSymptoms(record, 'DefaultMemoryManager');
|
|
308
|
+
if (!paired.length) return null;
|
|
153
309
|
|
|
154
|
-
const nameArr = toArray(names);
|
|
155
|
-
const gradeArr = toArray(grades, v => parseInt(v));
|
|
156
310
|
const recArr = recs == null ? [] : typeof recs === 'string'
|
|
157
311
|
? recs.split('.,').map(r => r.trim())
|
|
158
312
|
: Array.isArray(recs) ? recs.map(r => String(r).trim()) : [];
|
|
313
|
+
const recsAligned = paired.length === recArr.length;
|
|
159
314
|
|
|
160
|
-
const symptoms =
|
|
161
|
-
.
|
|
315
|
+
const symptoms = paired
|
|
316
|
+
.map((s, i) => ({ ...s, recommendation: recsAligned ? recArr[i] || '' : '' }))
|
|
317
|
+
.filter(s => s.grade === null || s.grade > 0);
|
|
162
318
|
|
|
163
319
|
return { date, symptoms };
|
|
164
320
|
}).filter(Boolean);
|
|
165
321
|
}
|
|
166
322
|
|
|
323
|
+
async _getRiskHeadline(whatsappId) {
|
|
324
|
+
try {
|
|
325
|
+
return await assembleRiskHeadline(whatsappId);
|
|
326
|
+
} catch (error) {
|
|
327
|
+
logger.warn('[DefaultMemoryManager] risk headline unavailable', { error: error.message });
|
|
328
|
+
return '';
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
167
332
|
async getClinicalData(whatsappId) {
|
|
168
333
|
try {
|
|
169
|
-
const data = await
|
|
334
|
+
const [data, riskHeadline] = await Promise.all([
|
|
335
|
+
this._getClinicalContext(whatsappId),
|
|
336
|
+
this._getRiskHeadline(whatsappId),
|
|
337
|
+
]);
|
|
170
338
|
if (!data) return null;
|
|
171
339
|
|
|
172
340
|
const contextParts = [];
|
|
173
341
|
const d = data.demografia;
|
|
174
|
-
const c = data.datos_clinicos;
|
|
342
|
+
const c = withChemoContext(data.datos_clinicos, data.chemo);
|
|
175
343
|
if (d?.edad) contextParts.push(`Edad: ${d.edad}`);
|
|
176
344
|
if (d?.sexo) contextParts.push(`Sexo: ${d.sexo}`);
|
|
345
|
+
if (data.treatingPhysician) contextParts.push(`Médico tratante: ${data.treatingPhysician}`);
|
|
177
346
|
if (c?.diagnostico) contextParts.push(`Diagnóstico: ${c.diagnostico}`);
|
|
178
347
|
if (c?.tratamiento_actual) contextParts.push(`Tratamiento actual: ${c.tratamiento_actual}`);
|
|
348
|
+
if (c?.tratamientos_previos) contextParts.push(`Tratamientos previos: ${c.tratamientos_previos}`);
|
|
179
349
|
if (c?.medicacion_actual) contextParts.push(`Medicación: ${c.medicacion_actual}`);
|
|
180
350
|
if (c?.alergias_medicamentos) contextParts.push(`Alergias: ${c.alergias_medicamentos}`);
|
|
181
|
-
|
|
351
|
+
const comorbidities = readComorbidities(c?.comorbilidades);
|
|
352
|
+
if (comorbidities) contextParts.push(`Comorbilidades: ${comorbidities}`);
|
|
182
353
|
|
|
183
354
|
const symptomParts = (data.symptoms || []).map(t => {
|
|
184
355
|
const dateStr = new Date(t.date).toLocaleDateString('es-PE');
|
|
185
|
-
const symptomsStr = t.symptoms.map(s => `${s.name} (grado ${s.grade})`).join(', ');
|
|
356
|
+
const symptomsStr = t.symptoms.map(s => (s.grade === null ? s.name : `${s.name} (grado ${s.grade})`)).join(', ');
|
|
186
357
|
return symptomsStr ? `${dateStr}: ${symptomsStr}` : null;
|
|
187
358
|
}).filter(Boolean);
|
|
188
359
|
|
|
189
360
|
return {
|
|
190
|
-
clinicalContext: contextParts.join('. ')
|
|
191
|
-
lastSymptoms: symptomParts.join('; ') || 'Sin síntomas reportados recientemente'
|
|
361
|
+
clinicalContext: [contextParts.join('. '), renderChemoContext(data.chemo), riskHeadline].filter(Boolean).join('\n\n'),
|
|
362
|
+
lastSymptoms: symptomParts.join('; ') || 'Sin síntomas reportados recientemente',
|
|
363
|
+
nutritionPlan: await resolveNutritionPlan(data.nutricion),
|
|
192
364
|
};
|
|
193
365
|
} catch (error) {
|
|
194
366
|
logger.error('[DefaultMemoryManager] Error getting clinical data', { error: error.message });
|
|
@@ -197,4 +369,4 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
197
369
|
}
|
|
198
370
|
}
|
|
199
371
|
|
|
200
|
-
module.exports = { DefaultMemoryManager };
|
|
372
|
+
module.exports = { DefaultMemoryManager, OPERATOR_TURN_PREFIX };
|
|
@@ -18,6 +18,15 @@ const CATEGORY_LABELS = {
|
|
|
18
18
|
const DEFAULT_MAX_CONVERSATION_SUMMARIES = 5;
|
|
19
19
|
const DEFAULT_MAX_PATIENT_MEMORIES = 20;
|
|
20
20
|
|
|
21
|
+
const PROMPT_DATE_LOCALE = 'es-MX';
|
|
22
|
+
const PROMPT_DATE_OPTIONS = { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'America/Mexico_City' };
|
|
23
|
+
|
|
24
|
+
const promptDate = (value) => {
|
|
25
|
+
if (value === null || value === undefined) return '';
|
|
26
|
+
const date = new Date(value);
|
|
27
|
+
return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString(PROMPT_DATE_LOCALE, PROMPT_DATE_OPTIONS);
|
|
28
|
+
};
|
|
29
|
+
|
|
21
30
|
class EnhancedMemoryManager extends DefaultMemoryManager {
|
|
22
31
|
constructor(options = {}) {
|
|
23
32
|
super(options);
|
|
@@ -40,6 +49,7 @@ class EnhancedMemoryManager extends DefaultMemoryManager {
|
|
|
40
49
|
return {
|
|
41
50
|
clinicalContext: baseClinicalData?.clinicalContext ?? '',
|
|
42
51
|
lastSymptoms: baseClinicalData?.lastSymptoms ?? '',
|
|
52
|
+
nutritionPlan: baseClinicalData?.nutritionPlan ?? '',
|
|
43
53
|
patientMemories: formattedMemories,
|
|
44
54
|
conversationSummaries: formattedSummaries,
|
|
45
55
|
};
|
|
@@ -77,7 +87,8 @@ class EnhancedMemoryManager extends DefaultMemoryManager {
|
|
|
77
87
|
return memories
|
|
78
88
|
.map(m => {
|
|
79
89
|
const label = CATEGORY_LABELS[m.category] || m.category;
|
|
80
|
-
|
|
90
|
+
const reinforcedAt = promptDate(m.last_reinforced_at);
|
|
91
|
+
return `[${reinforcedAt ? `${label} · ${reinforcedAt}` : label}] ${m.content}`;
|
|
81
92
|
})
|
|
82
93
|
.join('\n');
|
|
83
94
|
}
|
|
@@ -87,14 +98,9 @@ class EnhancedMemoryManager extends DefaultMemoryManager {
|
|
|
87
98
|
|
|
88
99
|
return summaries
|
|
89
100
|
.map(s => {
|
|
90
|
-
const date =
|
|
91
|
-
day: 'numeric',
|
|
92
|
-
month: 'short',
|
|
93
|
-
year: 'numeric',
|
|
94
|
-
timeZone: 'America/Mexico_City',
|
|
95
|
-
});
|
|
101
|
+
const date = promptDate(s.session_end);
|
|
96
102
|
const topics = s.topics?.length ? `Temas: ${s.topics.join(', ')}. ` : '';
|
|
97
|
-
return `[${date}] ${topics}Resumen: ${s.summary}`;
|
|
103
|
+
return `${date ? `[${date}] ` : ''}${topics}Resumen: ${s.summary}`;
|
|
98
104
|
})
|
|
99
105
|
.join('\n');
|
|
100
106
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { getDb, getModelDatabase } = require('../../config/mongoConfig');
|
|
4
|
+
|
|
5
|
+
const llmCallSchema = new mongoose.Schema({
|
|
6
|
+
metadata: { type: mongoose.Schema.Types.Mixed },
|
|
7
|
+
request: { type: mongoose.Schema.Types.Mixed },
|
|
8
|
+
response: { type: mongoose.Schema.Types.Mixed },
|
|
9
|
+
durationMs: { type: Number, default: null },
|
|
10
|
+
}, { timestamps: true });
|
|
11
|
+
llmCallSchema.index({ 'metadata.code': 1, createdAt: -1 });
|
|
12
|
+
llmCallSchema.index({ 'metadata.turnId': 1 });
|
|
13
|
+
|
|
14
|
+
function getLlmCallModel() {
|
|
15
|
+
const conn = getDb(getModelDatabase('LlmCall'));
|
|
16
|
+
return conn.models.LlmCall || conn.model('LlmCall', llmCallSchema, 'llmCall');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
module.exports = { getLlmCallModel, llmCallSchema };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const llmMonitorCheckpointSchema = new mongoose.Schema({
|
|
6
|
+
key: { type: String, required: true, unique: true },
|
|
7
|
+
highWatermark: { type: Date, default: null },
|
|
8
|
+
lastStartedAt: { type: Date, default: null },
|
|
9
|
+
lastCompletedAt: { type: Date, default: null },
|
|
10
|
+
lastError: { type: String, default: null },
|
|
11
|
+
lastFailedSteps: { type: Number, default: 0 },
|
|
12
|
+
}, { timestamps: true });
|
|
13
|
+
|
|
14
|
+
function getLlmMonitorCheckpointModel() {
|
|
15
|
+
const conn = clinicalConnection();
|
|
16
|
+
return conn.models.LlmMonitorCheckpoint
|
|
17
|
+
|| conn.model('LlmMonitorCheckpoint', llmMonitorCheckpointSchema, 'llmMonitorCheckpoint');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
module.exports = { getLlmMonitorCheckpointModel, llmMonitorCheckpointSchema };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const reviewSchema = new mongoose.Schema({
|
|
6
|
+
findingId: { type: String, required: true },
|
|
7
|
+
status: { type: String, default: 'pending' },
|
|
8
|
+
reviewer: { type: String, default: null },
|
|
9
|
+
reviewedAt: { type: Date, default: null },
|
|
10
|
+
notes: { type: String, default: null },
|
|
11
|
+
airtableRecordId: { type: String, default: null },
|
|
12
|
+
}, { _id: false });
|
|
13
|
+
|
|
14
|
+
const llmMonitorEvaluationSchema = new mongoose.Schema({
|
|
15
|
+
monitorId: { type: String, required: true },
|
|
16
|
+
monitorVersion: { type: String, required: true },
|
|
17
|
+
turnId: { type: String, required: true },
|
|
18
|
+
patientCode: { type: String, required: true },
|
|
19
|
+
turnCreatedAt: { type: Date, default: null },
|
|
20
|
+
status: { type: String, required: true, default: 'pending' },
|
|
21
|
+
eligible: { type: Boolean, default: false },
|
|
22
|
+
evidence: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
23
|
+
judge: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
24
|
+
findings: { type: [mongoose.Schema.Types.Mixed], default: [] },
|
|
25
|
+
passSampled: { type: Boolean, default: false },
|
|
26
|
+
preset: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
27
|
+
model: { type: String, default: null },
|
|
28
|
+
usage: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
29
|
+
attempts: { type: Number, default: 0 },
|
|
30
|
+
retries: { type: Number, default: 0 },
|
|
31
|
+
processingStartedAt: { type: Date, default: null },
|
|
32
|
+
processingLeaseUntil: { type: Date, default: null },
|
|
33
|
+
judgePrompt: { type: String, default: null },
|
|
34
|
+
error: { type: String, default: null },
|
|
35
|
+
airtableSyncStatus: { type: String, default: 'not_required' },
|
|
36
|
+
airtableRenderVersion: { type: String, default: null },
|
|
37
|
+
airtableLastError: { type: String, default: null },
|
|
38
|
+
reviews: { type: [reviewSchema], default: [] },
|
|
39
|
+
evaluatedAt: { type: Date, default: null },
|
|
40
|
+
}, { timestamps: true });
|
|
41
|
+
|
|
42
|
+
llmMonitorEvaluationSchema.index(
|
|
43
|
+
{ monitorId: 1, monitorVersion: 1, turnId: 1 },
|
|
44
|
+
{ unique: true },
|
|
45
|
+
);
|
|
46
|
+
llmMonitorEvaluationSchema.index({ status: 1, airtableSyncStatus: 1, updatedAt: 1, airtableRenderVersion: 1 });
|
|
47
|
+
llmMonitorEvaluationSchema.index({ status: 1, processingLeaseUntil: 1, updatedAt: 1 });
|
|
48
|
+
llmMonitorEvaluationSchema.index({ turnCreatedAt: 1, monitorId: 1 });
|
|
49
|
+
|
|
50
|
+
function getLlmMonitorEvaluationModel() {
|
|
51
|
+
const conn = clinicalConnection();
|
|
52
|
+
return conn.models.LlmMonitorEvaluation
|
|
53
|
+
|| conn.model('LlmMonitorEvaluation', llmMonitorEvaluationSchema, 'llmMonitorEvaluation');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = { getLlmMonitorEvaluationModel, llmMonitorEvaluationSchema };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const patternConsultSchema = new mongoose.Schema({
|
|
6
|
+
consultationId: { type: String, required: true },
|
|
7
|
+
patientCode: { type: String, required: true },
|
|
8
|
+
turnId: { type: String, default: null },
|
|
9
|
+
concern: { type: String, default: null },
|
|
10
|
+
impressions: { type: Array, default: [] },
|
|
11
|
+
recommendedProbes: { type: [String], default: [] },
|
|
12
|
+
watchFor: { type: [String], default: [] },
|
|
13
|
+
escalationAdvice: { type: Object, default: null },
|
|
14
|
+
degraded: { type: Boolean, default: false },
|
|
15
|
+
degradedReasons: { type: [String], default: [] },
|
|
16
|
+
}, { timestamps: true });
|
|
17
|
+
|
|
18
|
+
patternConsultSchema.index({ consultationId: 1 }, { unique: true });
|
|
19
|
+
patternConsultSchema.index({ patientCode: 1, createdAt: -1 });
|
|
20
|
+
|
|
21
|
+
function patternConsultStore() {
|
|
22
|
+
const conn = clinicalConnection();
|
|
23
|
+
const model = conn.models.PatternConsult || conn.model('PatternConsult', patternConsultSchema, 'patternConsult');
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
get(consultationId) {
|
|
27
|
+
return model.findOne({ consultationId }).lean();
|
|
28
|
+
},
|
|
29
|
+
put(doc) {
|
|
30
|
+
return model.create(doc);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = {
|
|
36
|
+
patternConsultStore,
|
|
37
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const riskWarmupEventSchema = new mongoose.Schema({
|
|
6
|
+
patientCode: { type: String, required: true },
|
|
7
|
+
stored: { type: Boolean, required: true },
|
|
8
|
+
reason: { type: String, default: null },
|
|
9
|
+
trigger: { type: String, default: null },
|
|
10
|
+
assessmentId: { type: String, default: null },
|
|
11
|
+
turnId: { type: String, default: null },
|
|
12
|
+
durationMs: { type: Number, default: null },
|
|
13
|
+
}, { timestamps: true });
|
|
14
|
+
riskWarmupEventSchema.index({ patientCode: 1, createdAt: -1 });
|
|
15
|
+
riskWarmupEventSchema.index({ createdAt: -1 });
|
|
16
|
+
riskWarmupEventSchema.index({ turnId: 1 });
|
|
17
|
+
|
|
18
|
+
function getRiskWarmupEventModel() {
|
|
19
|
+
const conn = clinicalConnection();
|
|
20
|
+
return conn.models.RiskWarmupEvent || conn.model('RiskWarmupEvent', riskWarmupEventSchema, 'riskWarmupEvent');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = { getRiskWarmupEventModel, riskWarmupEventSchema };
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const evidenceSchema = new mongoose.Schema({
|
|
6
|
+
key: { type: String, required: true },
|
|
7
|
+
source: { type: String, required: true, enum: ['triage', 'chat', 'fhir', 'airtable'] },
|
|
8
|
+
sourceId: { type: String, required: true },
|
|
9
|
+
code: { type: String, required: true },
|
|
10
|
+
summary: { type: String, default: null },
|
|
11
|
+
confidence: { type: Number, default: null },
|
|
12
|
+
}, { _id: false });
|
|
13
|
+
|
|
14
|
+
const invitationAttemptSchema = new mongoose.Schema({
|
|
15
|
+
idempotencyKey: { type: String, required: true },
|
|
16
|
+
invitationClass: { type: String, required: true, enum: ['first', 'followup'] },
|
|
17
|
+
invitationCycle: { type: String, required: true },
|
|
18
|
+
templateVersion: { type: String, required: true },
|
|
19
|
+
status: { type: String, enum: ['queued', 'sent', 'delivered', 'read', 'failed', 'unknown'], default: 'queued' },
|
|
20
|
+
providerMessageId: { type: String, default: null },
|
|
21
|
+
error: { type: String, default: null },
|
|
22
|
+
createdAt: { type: Date, default: Date.now },
|
|
23
|
+
settledAt: { type: Date, default: null },
|
|
24
|
+
}, { _id: false });
|
|
25
|
+
|
|
26
|
+
const supportCandidateSchema = new mongoose.Schema({
|
|
27
|
+
candidateId: { type: String, required: true, unique: true },
|
|
28
|
+
patientId: { type: String, required: true },
|
|
29
|
+
service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
|
|
30
|
+
disposition: {
|
|
31
|
+
type: String,
|
|
32
|
+
required: true,
|
|
33
|
+
enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'],
|
|
34
|
+
},
|
|
35
|
+
engagement: {
|
|
36
|
+
state: { type: String, enum: ['notInvited', 'invited', 'registered', 'attended', 'declined'], default: 'notInvited' },
|
|
37
|
+
lastInvitedAt: { type: Date, default: null },
|
|
38
|
+
cooldownUntil: { type: Date, default: null },
|
|
39
|
+
registrationEvidenceId: { type: String, default: null },
|
|
40
|
+
registeredAt: { type: Date, default: null },
|
|
41
|
+
attendanceEvidenceId: { type: String, default: null },
|
|
42
|
+
attendedAt: { type: Date, default: null },
|
|
43
|
+
declineEvidenceId: { type: String, default: null },
|
|
44
|
+
declinedAt: { type: Date, default: null },
|
|
45
|
+
declinePreference: { type: String, enum: [null, 'another_date', 'not_now', 'never'], default: null },
|
|
46
|
+
},
|
|
47
|
+
groupEligible: { type: Boolean, required: true },
|
|
48
|
+
urgentIntakeEligible: { type: Boolean, default: false },
|
|
49
|
+
priority: { type: String, enum: ['routine', 'soon', 'urgent'], default: 'routine' },
|
|
50
|
+
confidence: { type: Number, required: true },
|
|
51
|
+
nutritionRisk: { type: String, default: null },
|
|
52
|
+
psychologyRisk: { type: String, default: null },
|
|
53
|
+
reasonCodes: { type: [String], default: [] },
|
|
54
|
+
operationalReviews: { type: [new mongoose.Schema({
|
|
55
|
+
reasonCode: { type: String, required: true, enum: ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'] },
|
|
56
|
+
sourceId: { type: String, required: true, maxlength: 256 },
|
|
57
|
+
detectedAt: { type: Date, required: true },
|
|
58
|
+
}, { _id: false })], default: [] },
|
|
59
|
+
operationalReviewOverflow: { type: Boolean, default: false },
|
|
60
|
+
evidence: { type: [evidenceSchema], default: [] },
|
|
61
|
+
sourceEventIds: { type: [String], default: [] },
|
|
62
|
+
latestSourceId: { type: String, required: true },
|
|
63
|
+
latestOrigin: { type: String, required: true },
|
|
64
|
+
decisionVersion: { type: String, required: true },
|
|
65
|
+
invitationAttempts: { type: [invitationAttemptSchema], default: [] },
|
|
66
|
+
activeInvitationKey: { type: String, default: null },
|
|
67
|
+
cooldownInvitationKey: { type: String, default: null },
|
|
68
|
+
specialistClearedAt: { type: Date, default: null },
|
|
69
|
+
escalation: {
|
|
70
|
+
risk: { type: String, default: null },
|
|
71
|
+
sourceId: { type: String, default: null },
|
|
72
|
+
origin: { type: String, default: null },
|
|
73
|
+
detectedAt: { type: Date, default: null },
|
|
74
|
+
clearedAt: { type: Date, default: null },
|
|
75
|
+
},
|
|
76
|
+
revision: { type: Number, default: 0 },
|
|
77
|
+
lastEvaluatedAt: { type: Date, required: true },
|
|
78
|
+
}, { timestamps: true });
|
|
79
|
+
|
|
80
|
+
supportCandidateSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_candidate_per_service' });
|
|
81
|
+
supportCandidateSchema.index({ disposition: 1, service: 1, priority: 1, updatedAt: -1 });
|
|
82
|
+
supportCandidateSchema.index({ 'invitationAttempts.idempotencyKey': 1 }, { sparse: true });
|
|
83
|
+
|
|
84
|
+
function getSupportCandidateModel() {
|
|
85
|
+
const conn = clinicalConnection();
|
|
86
|
+
return conn.models.SupportCandidate
|
|
87
|
+
|| conn.model('SupportCandidate', supportCandidateSchema, 'supportCandidates');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { getSupportCandidateModel, supportCandidateSchema };
|