@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
package/lib/core/PhiProcessor.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
const { createHmac } = require('crypto');
|
|
2
2
|
|
|
3
3
|
const { logger } = require('../utils/logger');
|
|
4
|
+
const { collectStringsDeep, mapStringsDeep } = require('../utils/sanitizerUtils');
|
|
4
5
|
|
|
5
6
|
const { PHI_CATEGORIES } = require('../models/tokenMapModel');
|
|
6
7
|
|
|
8
|
+
const { GLOBAL_ENTITY_CATEGORIES } = require('../models/globalEntityMapModel');
|
|
9
|
+
|
|
7
10
|
const { NerClient } = require('../providers/NerClient');
|
|
8
11
|
|
|
9
12
|
const tokenMapService = require('../services/tokenMapService');
|
|
@@ -12,6 +15,121 @@ const { lookupGlobal, lookupGlobalToken } = require('../services/globalEntitySer
|
|
|
12
15
|
|
|
13
16
|
const TOKEN_REGEX = /<<[A-Z_]+_\d+>>/g;
|
|
14
17
|
|
|
18
|
+
const ALL_CATEGORIES = [...PHI_CATEGORIES, ...GLOBAL_ENTITY_CATEGORIES]
|
|
19
|
+
.sort((a, b) => b.length - a.length);
|
|
20
|
+
|
|
21
|
+
const BARE_CATEGORY = 'PERSONA';
|
|
22
|
+
|
|
23
|
+
const PLACEHOLDER_REGEX = new RegExp(
|
|
24
|
+
`(?<!\\w)<{0,2}(${ALL_CATEGORIES.join('|')})_(\\d+)>{0,2}(?!\\w)`,
|
|
25
|
+
'gi',
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
const placeholderToken = (category, index) => `<<${category.toUpperCase()}_${index}>>`;
|
|
29
|
+
|
|
30
|
+
const placeholderIn = (match, category, index) => (
|
|
31
|
+
/[<>]/.test(match) || category.toUpperCase() === BARE_CATEGORY
|
|
32
|
+
? placeholderToken(category, index)
|
|
33
|
+
: null
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
const punctuationBlanked = (body) => body.replace(/[?!]/g, ' ');
|
|
37
|
+
|
|
38
|
+
const spansOfExistingTokens = (body) => [...body.matchAll(TOKEN_REGEX)]
|
|
39
|
+
.map((match) => ({ start: match.index, end: match.index + match[0].length }));
|
|
40
|
+
|
|
41
|
+
const overlaps = (spans, start, end) => spans.find((span) => start < span.end && end > span.start);
|
|
42
|
+
|
|
43
|
+
const WORD_CHAR = /[\p{L}\p{N}\p{M}_]/u;
|
|
44
|
+
|
|
45
|
+
const isHighSurrogate = (unit) => unit >= 0xd800 && unit <= 0xdbff;
|
|
46
|
+
|
|
47
|
+
const isLowSurrogate = (unit) => unit >= 0xdc00 && unit <= 0xdfff;
|
|
48
|
+
|
|
49
|
+
const charBefore = (body, at) => {
|
|
50
|
+
if (at <= 0) return '';
|
|
51
|
+
const paired = at >= 2 && isLowSurrogate(body.charCodeAt(at - 1)) && isHighSurrogate(body.charCodeAt(at - 2));
|
|
52
|
+
return String.fromCodePoint(body.codePointAt(at - (paired ? 2 : 1)));
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const charAt = (body, at) => (at < body.length ? String.fromCodePoint(body.codePointAt(at)) : '');
|
|
56
|
+
|
|
57
|
+
const seamIsWord = (body, at) => WORD_CHAR.test(charBefore(body, at)) && WORD_CHAR.test(charAt(body, at));
|
|
58
|
+
|
|
59
|
+
const insideWord = (body, start, end) => seamIsWord(body, start) || seamIsWord(body, end);
|
|
60
|
+
|
|
61
|
+
const findFrom = (body, blanked, plaintext, from) => {
|
|
62
|
+
const at = Math.max(0, from);
|
|
63
|
+
const direct = body.indexOf(plaintext, at);
|
|
64
|
+
const punctuated = blanked.indexOf(plaintext, at);
|
|
65
|
+
if (direct === -1 || punctuated === -1) return Math.max(direct, punctuated);
|
|
66
|
+
return Math.min(direct, punctuated);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const findWordFrom = (body, blanked, plaintext, from) => {
|
|
70
|
+
let at = findFrom(body, blanked, plaintext, from);
|
|
71
|
+
while (at !== -1 && insideWord(body, at, at + plaintext.length)) {
|
|
72
|
+
at = findFrom(body, blanked, plaintext, at + 1);
|
|
73
|
+
}
|
|
74
|
+
return at;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const spanWidth = (entity) => (entity.plaintext ?? '').length || (entity.end ?? 0) - (entity.start ?? 0);
|
|
78
|
+
|
|
79
|
+
const resolveEntitySpans = (body, entities) => {
|
|
80
|
+
const blanked = punctuationBlanked(body);
|
|
81
|
+
const existing = spansOfExistingTokens(body);
|
|
82
|
+
const eligible = entities
|
|
83
|
+
.filter((entity) => {
|
|
84
|
+
if (PHI_CATEGORIES.includes(entity.label)) return true;
|
|
85
|
+
logger.debug('[PhiProcessor] Unknown label, skipping', { label: entity.label });
|
|
86
|
+
return false;
|
|
87
|
+
})
|
|
88
|
+
.sort((a, b) => (a.start ?? 0) - (b.start ?? 0) || spanWidth(b) - spanWidth(a));
|
|
89
|
+
|
|
90
|
+
const resolved = [];
|
|
91
|
+
let cursor = 0;
|
|
92
|
+
let claimed = { start: -1, end: -1 };
|
|
93
|
+
|
|
94
|
+
for (const entity of eligible) {
|
|
95
|
+
const reported = Number.isInteger(entity.start) ? entity.start : 0;
|
|
96
|
+
const plaintext = entity.plaintext || body.slice(reported, entity.end);
|
|
97
|
+
if (!plaintext) continue;
|
|
98
|
+
|
|
99
|
+
const reportedEnd = Number.isInteger(entity.end) ? entity.end : reported + plaintext.length;
|
|
100
|
+
if (reported >= claimed.start && reportedEnd <= claimed.end) continue;
|
|
101
|
+
|
|
102
|
+
let start = reported >= cursor && body.startsWith(plaintext, reported)
|
|
103
|
+
? reported
|
|
104
|
+
: findWordFrom(body, blanked, plaintext, Math.max(reported, cursor));
|
|
105
|
+
if (start === -1) start = findWordFrom(body, blanked, plaintext, cursor);
|
|
106
|
+
|
|
107
|
+
for (;;) {
|
|
108
|
+
const hit = start === -1 ? null : overlaps(existing, start, start + plaintext.length);
|
|
109
|
+
if (!hit) break;
|
|
110
|
+
start = findWordFrom(body, blanked, plaintext, hit.end);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (start === -1) {
|
|
114
|
+
logger.error('[PhiProcessor] Entity text not found in body, leaving it unredacted', {
|
|
115
|
+
label: entity.label, reportedStart: entity.start,
|
|
116
|
+
});
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const end = start + plaintext.length;
|
|
121
|
+
resolved.push({ start, end, plaintext: body.slice(start, end), label: entity.label });
|
|
122
|
+
claimed = { start: reported, end: reportedEnd };
|
|
123
|
+
cursor = end;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return resolved;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const TOKEN_SPLIT_REGEX = /(<<[A-Z_]+_\d+>>)/g;
|
|
130
|
+
|
|
131
|
+
const IS_TOKEN = /^<<[A-Z_]+_\d+>>$/;
|
|
132
|
+
|
|
15
133
|
class PhiProcessor {
|
|
16
134
|
constructor({ encode = false, ner, hashSecret } = {}) {
|
|
17
135
|
this._nerClient = null;
|
|
@@ -46,32 +164,34 @@ class PhiProcessor {
|
|
|
46
164
|
const entities = await this._nerClient.detectEntities(body);
|
|
47
165
|
if (!entities?.length) return body;
|
|
48
166
|
|
|
49
|
-
const
|
|
167
|
+
const spans = resolveEntitySpans(body, entities).reverse();
|
|
50
168
|
|
|
51
169
|
let encoded = body;
|
|
52
|
-
for (const
|
|
53
|
-
|
|
54
|
-
logger.debug('[PhiProcessor] Unknown label, skipping', { label: entity.label });
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const plaintext = entity.plaintext || encoded.slice(entity.start, entity.end);
|
|
59
|
-
const global = await lookupGlobal(plaintext);
|
|
170
|
+
for (const span of spans) {
|
|
171
|
+
const global = await lookupGlobal(span.plaintext);
|
|
60
172
|
const token = global
|
|
61
173
|
? global.token
|
|
62
|
-
: await tokenMapService.encode(numero, plaintext,
|
|
174
|
+
: await tokenMapService.encode(numero, span.plaintext, span.label);
|
|
175
|
+
if (!token) continue;
|
|
63
176
|
|
|
64
|
-
encoded = encoded.slice(0,
|
|
177
|
+
encoded = encoded.slice(0, span.start) + token + encoded.slice(span.end);
|
|
65
178
|
}
|
|
66
179
|
|
|
67
180
|
logger.debug('[PhiProcessor] Body encoded', { numero, entityCount: entities.length });
|
|
68
181
|
return encoded;
|
|
69
182
|
}
|
|
70
183
|
|
|
71
|
-
async
|
|
184
|
+
async encodeKnownName(name, numero) {
|
|
185
|
+
if (!this._phiEnabled) return name;
|
|
186
|
+
if (!name || !numero) return null;
|
|
187
|
+
return (await tokenMapService.encode(numero, name, 'PERSONA')) || null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async inData(messageData, saveFn, handler, { onSaved } = {}) {
|
|
72
191
|
const decodedBody = messageData.body;
|
|
73
192
|
const encodedBody = await this.encodeBody(decodedBody, messageData.code);
|
|
74
193
|
const saved = await saveFn({ ...messageData, body: encodedBody, plainBody: decodedBody });
|
|
194
|
+
if (saved?._id != null) await onSaved?.(String(saved._id));
|
|
75
195
|
return handler({ body: encodedBody, _id: saved?._id });
|
|
76
196
|
}
|
|
77
197
|
|
|
@@ -83,6 +203,17 @@ class PhiProcessor {
|
|
|
83
203
|
return handler({ body: decodedBody, _id: saved?._id });
|
|
84
204
|
}
|
|
85
205
|
|
|
206
|
+
async encodeAroundTokens(body, numero) {
|
|
207
|
+
const parts = String(body ?? '').split(TOKEN_SPLIT_REGEX);
|
|
208
|
+
if (parts.length === 1) return this.encodeBody(body, numero);
|
|
209
|
+
|
|
210
|
+
const encoded = [];
|
|
211
|
+
for (const part of parts) {
|
|
212
|
+
encoded.push(IS_TOKEN.test(part) ? part : await this.encodeBody(part, numero));
|
|
213
|
+
}
|
|
214
|
+
return encoded.join('');
|
|
215
|
+
}
|
|
216
|
+
|
|
86
217
|
async decodeBody(body, numero) {
|
|
87
218
|
if (!body || !numero) return body;
|
|
88
219
|
const tokens = body.match(TOKEN_REGEX);
|
|
@@ -102,11 +233,61 @@ class PhiProcessor {
|
|
|
102
233
|
}
|
|
103
234
|
|
|
104
235
|
async outDataFromEncoded(messageData, saveFn, handler) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
: messageData.body;
|
|
108
|
-
|
|
109
|
-
|
|
236
|
+
if (!this._phiEnabled) {
|
|
237
|
+
const saved = await saveFn({ ...messageData, plainBody: messageData.body });
|
|
238
|
+
return handler({ body: messageData.body, _id: saved?._id });
|
|
239
|
+
}
|
|
240
|
+
const plainBody = await this.decodeBody(messageData.body, messageData.code);
|
|
241
|
+
const encodedBody = await this.encodeAroundTokens(messageData.body, messageData.code);
|
|
242
|
+
const saved = await saveFn({ ...messageData, body: encodedBody, plainBody });
|
|
243
|
+
return handler({ body: plainBody, _id: saved?._id });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async repairOutbound(value, numero) {
|
|
247
|
+
if (!this._phiEnabled || !numero || value === null || value === undefined) return value;
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
const strings = collectStringsDeep(value);
|
|
251
|
+
|
|
252
|
+
const candidates = new Set();
|
|
253
|
+
for (const text of strings) {
|
|
254
|
+
for (const [match, category, index] of text.matchAll(PLACEHOLDER_REGEX)) {
|
|
255
|
+
const token = placeholderIn(match, category, index);
|
|
256
|
+
if (token) candidates.add(token);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (!candidates.size) return value;
|
|
260
|
+
|
|
261
|
+
const resolved = new Map();
|
|
262
|
+
for (const token of candidates) {
|
|
263
|
+
const plaintext = await lookupGlobalToken(token) ?? await tokenMapService.decode(numero, token);
|
|
264
|
+
if (plaintext && plaintext !== token) resolved.set(token, plaintext);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const repaired = new Set();
|
|
268
|
+
const unresolved = new Set();
|
|
269
|
+
const restore = (token, fallback) => {
|
|
270
|
+
const plaintext = resolved.get(token);
|
|
271
|
+
if (plaintext === undefined) { unresolved.add(token); return fallback; }
|
|
272
|
+
repaired.add(token);
|
|
273
|
+
return plaintext;
|
|
274
|
+
};
|
|
275
|
+
const next = mapStringsDeep(value, (text) => text.replace(PLACEHOLDER_REGEX, (match, category, index) => {
|
|
276
|
+
const token = placeholderIn(match, category, index);
|
|
277
|
+
return token ? restore(token, match) : match;
|
|
278
|
+
}));
|
|
279
|
+
|
|
280
|
+
if (repaired.size) {
|
|
281
|
+
logger.error('[PhiProcessor] PHI placeholder repaired before transport', { numero, tokens: [...repaired] });
|
|
282
|
+
}
|
|
283
|
+
if (unresolved.size) {
|
|
284
|
+
logger.error('[PhiProcessor] PHI placeholder reached transport unresolved', { numero, tokens: [...unresolved] });
|
|
285
|
+
}
|
|
286
|
+
return next;
|
|
287
|
+
} catch (e) {
|
|
288
|
+
logger.error('[PhiProcessor] repairOutbound failed, transmitting untouched', { numero, error: e?.message });
|
|
289
|
+
return value;
|
|
290
|
+
}
|
|
110
291
|
}
|
|
111
292
|
}
|
|
112
293
|
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
const { isPlainObject } = require('../utils/jsonUtils');
|
|
2
|
+
const { describeThrown } = require('../utils/errorUtils');
|
|
1
3
|
const { logger } = require('../utils/logger');
|
|
4
|
+
const { MAX_ADDITIONAL_TOOL_IDS } = require('./runtimeToolPolicy');
|
|
2
5
|
|
|
3
6
|
const VALID_HOOKS = ['preProcess', 'postProcess'];
|
|
4
7
|
|
|
@@ -31,7 +34,7 @@ class ProcessingPipeline {
|
|
|
31
34
|
return this;
|
|
32
35
|
}
|
|
33
36
|
|
|
34
|
-
async run(context, executeFn, shouldContinue = () => true) {
|
|
37
|
+
async run(context, executeFn, shouldContinue = () => true, discardResult = null) {
|
|
35
38
|
const ctx = { metadata: {}, ...context };
|
|
36
39
|
const preProcessCount = this._hooks.preProcess.length;
|
|
37
40
|
const postProcessCount = this._hooks.postProcess.length;
|
|
@@ -47,6 +50,7 @@ class ProcessingPipeline {
|
|
|
47
50
|
skip: preProcessResult.skip,
|
|
48
51
|
hasAdditionalInstructions: !!preProcessResult.additionalInstructions,
|
|
49
52
|
additionalMessagesCount: preProcessResult.additionalMessages.length,
|
|
53
|
+
additionalToolIdsCount: preProcessResult.additionalToolIds?.length || 0,
|
|
50
54
|
hasToolChoice: preProcessResult.toolChoice != null,
|
|
51
55
|
});
|
|
52
56
|
|
|
@@ -60,7 +64,21 @@ class ProcessingPipeline {
|
|
|
60
64
|
|
|
61
65
|
const result = await executeFn(preProcessResult, shouldContinue, ctx.runId);
|
|
62
66
|
|
|
63
|
-
if (!shouldContinue())
|
|
67
|
+
if (!shouldContinue()) {
|
|
68
|
+
if (result && typeof discardResult === 'function') {
|
|
69
|
+
try {
|
|
70
|
+
await discardResult(result);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
logger.warn('[ProcessingPipeline] result discard failed', {
|
|
73
|
+
chatId: ctx.chatId,
|
|
74
|
+
type: ctx.type,
|
|
75
|
+
reason: 'result_discard_failed',
|
|
76
|
+
errorType: error?.constructor?.name || typeof error,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
64
82
|
|
|
65
83
|
this._runPostProcessHooks(ctx, result, null);
|
|
66
84
|
return result;
|
|
@@ -78,13 +96,24 @@ class ProcessingPipeline {
|
|
|
78
96
|
additionalInstructions: '',
|
|
79
97
|
additionalMessages: [],
|
|
80
98
|
toolChoice: null,
|
|
99
|
+
signals: {},
|
|
81
100
|
metadata: context.metadata || {},
|
|
82
101
|
};
|
|
83
102
|
|
|
84
103
|
if (hooks.length === 0) return merged;
|
|
85
104
|
|
|
86
105
|
for (const fn of hooks) {
|
|
87
|
-
|
|
106
|
+
let result;
|
|
107
|
+
try {
|
|
108
|
+
result = await fn(context);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
logger.warn('[ProcessingPipeline] preProcess hook failed, skipping its contribution', {
|
|
111
|
+
chatId: context.chatId,
|
|
112
|
+
type: context.type,
|
|
113
|
+
error: describeThrown(error),
|
|
114
|
+
});
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
88
117
|
if (!result) continue;
|
|
89
118
|
|
|
90
119
|
if (result.skip) {
|
|
@@ -103,6 +132,18 @@ class ProcessingPipeline {
|
|
|
103
132
|
if (result.toolChoice) {
|
|
104
133
|
merged.toolChoice = result.toolChoice;
|
|
105
134
|
}
|
|
135
|
+
if (Array.isArray(result.additionalToolIds)) {
|
|
136
|
+
const existing = new Set(merged.additionalToolIds || []);
|
|
137
|
+
for (const toolId of result.additionalToolIds) {
|
|
138
|
+
if (existing.size >= MAX_ADDITIONAL_TOOL_IDS) break;
|
|
139
|
+
if (typeof toolId !== 'string' || !toolId.trim()) continue;
|
|
140
|
+
existing.add(toolId.trim());
|
|
141
|
+
}
|
|
142
|
+
if (existing.size > 0) merged.additionalToolIds = [...existing];
|
|
143
|
+
}
|
|
144
|
+
if (isPlainObject(result.signals)) {
|
|
145
|
+
Object.assign(merged.signals, result.signals);
|
|
146
|
+
}
|
|
106
147
|
if (result.metadata && typeof result.metadata === 'object') {
|
|
107
148
|
Object.assign(context.metadata, result.metadata);
|
|
108
149
|
merged.metadata = context.metadata;
|
|
@@ -117,7 +158,11 @@ class ProcessingPipeline {
|
|
|
117
158
|
if (hooks.length === 0) return;
|
|
118
159
|
|
|
119
160
|
setImmediate(() => {
|
|
120
|
-
const postContext = {
|
|
161
|
+
const postContext = {
|
|
162
|
+
chatId: context.chatId,
|
|
163
|
+
type: context.type,
|
|
164
|
+
...(Object.keys(context.metadata || {}).length > 0 && { metadata: context.metadata }),
|
|
165
|
+
};
|
|
121
166
|
if (result) postContext.result = result;
|
|
122
167
|
if (error) postContext.error = error;
|
|
123
168
|
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
|
|
3
|
+
const routes = new Map();
|
|
4
|
+
|
|
5
|
+
const normalizePayload = (value) => String(value ?? '').trim().toLowerCase();
|
|
6
|
+
|
|
7
|
+
function registerInteractiveRoute(prefix, handler) {
|
|
8
|
+
const key = normalizePayload(prefix);
|
|
9
|
+
if (!key) throw new Error('registerInteractiveRoute requires a payload prefix');
|
|
10
|
+
if (typeof handler !== 'function') throw new Error('registerInteractiveRoute requires a handler function');
|
|
11
|
+
routes.set(key, handler);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function unregisterInteractiveRoute(prefix) {
|
|
15
|
+
return routes.delete(normalizePayload(prefix));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function clearInteractiveRoutes() {
|
|
19
|
+
routes.clear();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function hasInteractiveRoutes() {
|
|
23
|
+
return routes.size > 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolveInteractiveRoute(payload) {
|
|
27
|
+
const candidate = normalizePayload(payload);
|
|
28
|
+
if (!candidate) return null;
|
|
29
|
+
for (const [prefix, handler] of routes) {
|
|
30
|
+
if (candidate.startsWith(prefix)) return handler;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function invokeInteractiveRoute(messageData) {
|
|
36
|
+
if (!routes.size) return false;
|
|
37
|
+
|
|
38
|
+
const interactive = messageData?.interactive || {};
|
|
39
|
+
const handler = resolveInteractiveRoute(interactive.payload);
|
|
40
|
+
if (!handler) return false;
|
|
41
|
+
|
|
42
|
+
try {
|
|
43
|
+
await handler({
|
|
44
|
+
code: messageData.code,
|
|
45
|
+
payload: interactive.payload ?? null,
|
|
46
|
+
title: interactive.title ?? null,
|
|
47
|
+
messageData
|
|
48
|
+
});
|
|
49
|
+
return true;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
logger.error('[InteractiveRoutes] Route handler failed', { error: error?.message || error });
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = {
|
|
57
|
+
normalizePayload,
|
|
58
|
+
registerInteractiveRoute,
|
|
59
|
+
unregisterInteractiveRoute,
|
|
60
|
+
clearInteractiveRoutes,
|
|
61
|
+
hasInteractiveRoutes,
|
|
62
|
+
resolveInteractiveRoute,
|
|
63
|
+
invokeInteractiveRoute
|
|
64
|
+
};
|
package/lib/eval/EvalProvider.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
2
|
|
|
3
|
-
const { getCurrentMexicoDateTime } = require('../utils/dateUtils');
|
|
4
3
|
const { logger } = require('../utils/logger');
|
|
5
4
|
const { Thread } = require('../models/threadModel');
|
|
6
5
|
const { getToolSchemas: getRegistrySchemas } = require('../services/toolRegistryService');
|
|
7
6
|
const { PhiProcessor } = require('../core/PhiProcessor');
|
|
7
|
+
const { buildDateAnchor } = require('../clinical/helpers/dateAnchorHelper');
|
|
8
8
|
const { DefaultMemoryManager, EnhancedMemoryManager, createLLMProvider, composePrompt, resolveTools, getAssistantById } = require('../clinical');
|
|
9
|
+
const { resolveClinicalContext } = require('../clinical/services/clinicalContextReadService');
|
|
10
|
+
const { variablesReferencedIn } = require('../clinical/services/promptComposerService');
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* Promptfoo-compatible eval provider that wraps the real Nexus pipeline.
|
|
@@ -35,7 +37,7 @@ class EvalProvider {
|
|
|
35
37
|
this.memoryManager = config.memoryManager || (
|
|
36
38
|
config.memoryStrategy === 'enhanced' ? new EnhancedMemoryManager() : new DefaultMemoryManager()
|
|
37
39
|
);
|
|
38
|
-
const variant = (config.variant || '
|
|
40
|
+
const variant = (config.variant || 'gateway').toString().toLowerCase();
|
|
39
41
|
this.provider = createLLMProvider({
|
|
40
42
|
variant,
|
|
41
43
|
defaultModels: { responseModel: this.model },
|
|
@@ -46,6 +48,11 @@ class EvalProvider {
|
|
|
46
48
|
encode: config.phi?.encode || false,
|
|
47
49
|
ner: config.phi?.ner || null,
|
|
48
50
|
});
|
|
51
|
+
this.configModelConfig = {
|
|
52
|
+
...(config.model ? { model: config.model } : {}),
|
|
53
|
+
...(config.temperature != null ? { temperature: config.temperature } : {}),
|
|
54
|
+
...(config.maxOutputTokens != null ? { max_output_tokens: config.maxOutputTokens } : {}),
|
|
55
|
+
};
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
id() {
|
|
@@ -66,14 +73,18 @@ class EvalProvider {
|
|
|
66
73
|
assistantId = thread.prompt_id || thread.assistant_id || null;
|
|
67
74
|
}
|
|
68
75
|
|
|
69
|
-
const { messages, promptVariables, lastUserMessage } = await this._buildContext(numero, beforeCheckpoint);
|
|
76
|
+
const { messages, promptVariables, lastUserMessage, contextSource } = await this._buildContext(numero, beforeCheckpoint);
|
|
70
77
|
|
|
71
|
-
const {
|
|
78
|
+
const {
|
|
79
|
+
devContent, assistant, toolSchemas, resolvedPromptId, presetModelConfig, resolvedPresetId, interpolatedVariables,
|
|
80
|
+
} = await this._resolvePrompt(prompt, assistantId, thread, promptVariables);
|
|
72
81
|
|
|
73
82
|
const request = this._buildRequest({
|
|
74
83
|
devContent, messages, promptVariables, toolSchemas, assistant,
|
|
75
84
|
assistantId: resolvedPromptId || assistantId,
|
|
76
|
-
presetId:
|
|
85
|
+
presetId: resolvedPresetId,
|
|
86
|
+
presetModelConfig,
|
|
87
|
+
interpolatedVariables,
|
|
77
88
|
});
|
|
78
89
|
|
|
79
90
|
const startTime = Date.now();
|
|
@@ -84,7 +95,7 @@ class EvalProvider {
|
|
|
84
95
|
return this._formatResult({
|
|
85
96
|
finalResponse: response, toolCallsRequested: toolCalls, allToolsExecuted: toolsExecuted,
|
|
86
97
|
accumulatedUsage: usage || { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
|
|
87
|
-
assistantId, numero, lastUserMessage, messages, promptVariables, startTime,
|
|
98
|
+
assistantId, numero, lastUserMessage, messages, promptVariables, startTime, contextSource,
|
|
88
99
|
});
|
|
89
100
|
} catch (error) {
|
|
90
101
|
logger.error('[NexusEvalProvider] callApi failed', { error: error.message, numero });
|
|
@@ -95,7 +106,7 @@ class EvalProvider {
|
|
|
95
106
|
async _buildContext(numero, beforeCheckpoint) {
|
|
96
107
|
const messages = await this.memoryManager.buildContext({
|
|
97
108
|
thread: { code: numero },
|
|
98
|
-
config: { beforeCheckpoint, beforeOperator: '$lt' },
|
|
109
|
+
config: { beforeCheckpoint, beforeOperator: '$lt', compactOlderTriage: true },
|
|
99
110
|
});
|
|
100
111
|
|
|
101
112
|
const lastUserMsg = [...messages].reverse().find(m => m.role === 'user');
|
|
@@ -107,32 +118,49 @@ class EvalProvider {
|
|
|
107
118
|
const promptVariables = {
|
|
108
119
|
clinical_context: clinicalData?.clinicalContext ?? '',
|
|
109
120
|
last_symptoms: clinicalData?.lastSymptoms ?? '',
|
|
110
|
-
|
|
121
|
+
nutrition_plan: clinicalData?.nutritionPlan ?? '',
|
|
122
|
+
current_date: buildDateAnchor(),
|
|
111
123
|
patient_memories: clinicalData?.patientMemories ?? '',
|
|
112
124
|
conversation_summaries: clinicalData?.conversationSummaries ?? '',
|
|
113
125
|
};
|
|
114
126
|
|
|
115
|
-
|
|
127
|
+
const { block, source } = await resolveClinicalContext({
|
|
128
|
+
patientId: numero,
|
|
129
|
+
legacyBlock: promptVariables.clinical_context,
|
|
130
|
+
});
|
|
131
|
+
promptVariables.clinical_context = block;
|
|
132
|
+
|
|
133
|
+
return { messages, promptVariables, lastUserMessage, contextSource: source };
|
|
116
134
|
}
|
|
117
135
|
|
|
118
136
|
async _resolvePrompt(fallbackPrompt, assistantId, thread, promptVariables) {
|
|
119
137
|
let devContent;
|
|
138
|
+
let interpolatedVariables = [];
|
|
120
139
|
let resolvedPromptId = assistantId;
|
|
121
140
|
let presetToolIds = null;
|
|
141
|
+
let presetModelConfig = null;
|
|
142
|
+
let resolvedPresetId = this.presetId || thread?.preset_id || null;
|
|
122
143
|
|
|
123
|
-
const presetId =
|
|
144
|
+
const presetId = resolvedPresetId;
|
|
124
145
|
|
|
125
146
|
if (this.promptSource === 'airtable' && (presetId || assistantId)) {
|
|
126
|
-
const {
|
|
147
|
+
const {
|
|
148
|
+
resolvedPrompt, promptId, presetToolIds: toolIds, modelConfig, presetId: composedPresetId,
|
|
149
|
+
interpolatedVariables: interpolated,
|
|
150
|
+
} = await composePrompt({
|
|
127
151
|
presetId,
|
|
128
152
|
promptId: assistantId,
|
|
129
153
|
variables: promptVariables,
|
|
130
154
|
});
|
|
131
155
|
devContent = resolvedPrompt;
|
|
156
|
+
interpolatedVariables = interpolated || [];
|
|
132
157
|
resolvedPromptId = promptId || assistantId;
|
|
133
158
|
presetToolIds = toolIds;
|
|
159
|
+
presetModelConfig = modelConfig || null;
|
|
160
|
+
resolvedPresetId = composedPresetId || resolvedPresetId;
|
|
134
161
|
} else {
|
|
135
162
|
devContent = fallbackPrompt;
|
|
163
|
+
interpolatedVariables = variablesReferencedIn(devContent);
|
|
136
164
|
devContent = devContent.replace(/\{\{(\w+)\}\}/g, (_, key) => promptVariables[key] ?? '');
|
|
137
165
|
}
|
|
138
166
|
|
|
@@ -163,15 +191,27 @@ class EvalProvider {
|
|
|
163
191
|
devContent += `\n\nYou only have access to these tools: ${activeToolSchemas.map(s => s.function?.name).join(', ')}. Do not call or reference any tools not listed here.`;
|
|
164
192
|
}
|
|
165
193
|
}
|
|
166
|
-
} catch {
|
|
167
|
-
|
|
194
|
+
} catch (error) {
|
|
195
|
+
toolSchemas = [];
|
|
196
|
+
logger.error('[NexusEvalProvider] Failed to resolve assistant — running with no tools', { assistantId, error: error.message });
|
|
168
197
|
}
|
|
169
198
|
}
|
|
170
199
|
|
|
171
|
-
return { devContent, assistant, toolSchemas, resolvedPromptId };
|
|
200
|
+
return { devContent, assistant, toolSchemas, resolvedPromptId, presetModelConfig, resolvedPresetId, interpolatedVariables };
|
|
172
201
|
}
|
|
173
202
|
|
|
174
|
-
|
|
203
|
+
_modelConfig(presetModelConfig) {
|
|
204
|
+
const base = presetModelConfig
|
|
205
|
+
|| { temperature: this.temperature, max_output_tokens: this.maxOutputTokens };
|
|
206
|
+
const merged = { model: this.model, ...base, ...this.configModelConfig };
|
|
207
|
+
if (typeof merged.model !== 'string' || !merged.model.trim()) merged.model = this.model;
|
|
208
|
+
return merged;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
_buildRequest({
|
|
212
|
+
devContent, messages, promptVariables, toolSchemas, assistant, assistantId, presetId,
|
|
213
|
+
presetModelConfig = null, interpolatedVariables = [],
|
|
214
|
+
}) {
|
|
175
215
|
const convertedMessages = this.provider._convertItemsToApiFormat(messages);
|
|
176
216
|
|
|
177
217
|
const memoryParts = [];
|
|
@@ -181,20 +221,26 @@ class EvalProvider {
|
|
|
181
221
|
? [{ role: 'developer', content: `Usa la siguiente información que conoces del paciente para personalizar tu respuesta. Adapta tu tono, contenido o recomendaciones según estas preferencias y contexto cuando sea relevante. No menciones que tienes esta información almacenada.\n\n${memoryParts.join('\n\n')}` }]
|
|
182
222
|
: [];
|
|
183
223
|
|
|
184
|
-
|
|
185
|
-
const
|
|
224
|
+
// The same runtime clinical block a live turn gets (context, symptoms, nutrition plan), unless the prompt interpolates it.
|
|
225
|
+
const clinicalMessage = typeof this.provider._buildClinicalMessage === 'function'
|
|
226
|
+
? this.provider._buildClinicalMessage(promptVariables, interpolatedVariables)
|
|
227
|
+
: [];
|
|
228
|
+
const isContextOnly = this.mode === 'context-only';
|
|
186
229
|
|
|
187
|
-
const
|
|
230
|
+
const shouldUsePromptRegistry = !presetId && this.provider.supportsPromptRegistry && !!assistantId;
|
|
231
|
+
const modelConfig = shouldUsePromptRegistry ? {} : this._modelConfig(presetModelConfig);
|
|
232
|
+
const input = this.provider._orderRuntimeMessages(
|
|
233
|
+
this.provider._sanitizeInput([...memoryMessage, ...clinicalMessage, ...convertedMessages]),
|
|
234
|
+
modelConfig,
|
|
235
|
+
);
|
|
188
236
|
|
|
189
237
|
return {
|
|
190
238
|
instructions: devContent || '',
|
|
191
239
|
input,
|
|
192
|
-
toolSchemas:
|
|
193
|
-
toolChoice:
|
|
194
|
-
modelConfig
|
|
195
|
-
|
|
196
|
-
: { model: this.model, temperature: this.temperature, max_output_tokens: this.maxOutputTokens },
|
|
197
|
-
assistant: contextOnly ? null : assistant,
|
|
240
|
+
toolSchemas: isContextOnly ? [] : toolSchemas,
|
|
241
|
+
toolChoice: isContextOnly ? 'none' : this.toolChoice,
|
|
242
|
+
modelConfig,
|
|
243
|
+
assistant: isContextOnly ? null : assistant,
|
|
198
244
|
phiProcessor: this.phiProcessor,
|
|
199
245
|
promptVariables,
|
|
200
246
|
promptVersion: this.promptVersions[assistantId],
|
|
@@ -215,7 +261,7 @@ class EvalProvider {
|
|
|
215
261
|
});
|
|
216
262
|
}
|
|
217
263
|
|
|
218
|
-
_formatResult({ finalResponse, toolCallsRequested, allToolsExecuted, accumulatedUsage, assistantId, numero, lastUserMessage, messages, promptVariables, startTime }) {
|
|
264
|
+
_formatResult({ finalResponse, toolCallsRequested, allToolsExecuted, accumulatedUsage, assistantId, numero, lastUserMessage, messages, promptVariables, startTime, contextSource }) {
|
|
219
265
|
const output = this.provider._extractMessageOutput(finalResponse);
|
|
220
266
|
const durationMs = Date.now() - startTime;
|
|
221
267
|
const toolNames = toolCallsRequested.map(t => t.name);
|
|
@@ -243,6 +289,7 @@ class EvalProvider {
|
|
|
243
289
|
memoryStrategy: this.memoryManager.constructor.name,
|
|
244
290
|
contextMessages: messages.length,
|
|
245
291
|
clinicalContext: promptVariables.clinical_context ? 'present' : 'absent',
|
|
292
|
+
contextSource,
|
|
246
293
|
durationMs,
|
|
247
294
|
toolCalls: toolCallsRequested,
|
|
248
295
|
toolsExecuted: allToolsExecuted.map(t => ({
|