@peopl-health/nexus 6.0.0-dev.718 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
const {
|
|
2
|
+
SAFETY_NET_SOURCE,
|
|
3
|
+
getActivityQuietMs,
|
|
4
|
+
getHumanQuietMs,
|
|
5
|
+
getOfferWindowMs,
|
|
6
|
+
getPauseQuietMs,
|
|
7
|
+
getSafetyNetContentSid,
|
|
8
|
+
getSafetyNetLabel,
|
|
9
|
+
getSafetyNetPhone,
|
|
10
|
+
getSafetyNetUnassignedContentSid,
|
|
11
|
+
getTapWindowMs,
|
|
12
|
+
staffSendFilter
|
|
13
|
+
} = require('../config/safetyNetConfig');
|
|
14
|
+
const { logger } = require('../../utils/logger');
|
|
15
|
+
const { phoneDigits } = require('../../helpers/whatsappHelper');
|
|
16
|
+
const { isStaffSend } = require('../../helpers/staffSendHelper');
|
|
17
|
+
|
|
18
|
+
const { patientIsDeceased, pausedSince } = require('../../helpers/pausedThreadHelper');
|
|
19
|
+
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../../helpers/sendClaimHelper');
|
|
20
|
+
|
|
21
|
+
const { normalizePayload: normalize, registerInteractiveRoute, unregisterInteractiveRoute } = require('../../core/interactiveRouteService');
|
|
22
|
+
const { getMessages } = require('../../services/messageService');
|
|
23
|
+
|
|
24
|
+
const { WriteClaimStore } = require('./writeClaimStore');
|
|
25
|
+
const { OPS_ALERTS, cancelPendingFollowUps, recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
26
|
+
const { anyoneRepliedSince, humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
|
|
27
|
+
|
|
28
|
+
const getMessaging = () => require('../../core/NexusMessaging');
|
|
29
|
+
|
|
30
|
+
const SOURCE = SAFETY_NET_SOURCE;
|
|
31
|
+
const PAYLOAD_PREFIX = 'peopl_safetynet_';
|
|
32
|
+
const CHOICES = ['callback'];
|
|
33
|
+
const PAUSED = 'paused';
|
|
34
|
+
const UNASSIGNED = 'unassigned';
|
|
35
|
+
const REQUEST_CATEGORY = 'contact_team_member';
|
|
36
|
+
const COURTESY_ONLY = 'courtesy_only';
|
|
37
|
+
const UNANSWERED_LOOKBACK = 20;
|
|
38
|
+
const COURTESY_ANCHORS = new Set(['hola', 'gracias', 'agradezco', 'agradecida', 'agradecido', 'saludos', 'buen', 'buenas', 'buenos', 'bendiciones']);
|
|
39
|
+
const COURTESY_MODIFIERS = new Set(['muchas', 'mil', 'tardes', 'dias', 'días', 'noches', 'su', 'tu', 'la', 'informacion', 'información', 'igualmente']);
|
|
40
|
+
const COURTESY_EMOJI = /(?:😊|🙂|🙏|❤|👍)\uFE0F?[\u{1F3FB}-\u{1F3FF}]?/gu;
|
|
41
|
+
const COURTESY_CHARACTERS = /^[\p{L}\s.,!¡]*$/u;
|
|
42
|
+
|
|
43
|
+
const REQUEST_COPY = {
|
|
44
|
+
callback: {
|
|
45
|
+
question: 'El paciente pidió que el equipo lo contacte',
|
|
46
|
+
details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y pidió que lo contacten. Se le prometió contacto; revisar la conversación.`
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
let offerClaimStore = null;
|
|
51
|
+
let tapClaimStore = null;
|
|
52
|
+
let phoneCheckedFor = null;
|
|
53
|
+
|
|
54
|
+
const offerClaims = () => {
|
|
55
|
+
if (!offerClaimStore) offerClaimStore = new WriteClaimStore({ namespace: 'paused-safety-net', ttlMs: getOfferWindowMs() });
|
|
56
|
+
return offerClaimStore;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const tapClaims = () => {
|
|
60
|
+
if (!tapClaimStore) tapClaimStore = new WriteClaimStore({ namespace: 'safety-net-choice', ttlMs: getTapWindowMs() });
|
|
61
|
+
return tapClaimStore;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const disarmSafetyNet = () => {
|
|
65
|
+
unregisterInteractiveRoute(PAYLOAD_PREFIX);
|
|
66
|
+
stopSafetyNetSweep();
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const _resetSafetyNetState = () => {
|
|
70
|
+
offerClaimStore = null;
|
|
71
|
+
tapClaimStore = null;
|
|
72
|
+
phoneCheckedFor = null;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
function matchSafetyNetChoice(payload, title) {
|
|
76
|
+
const candidate = normalize(payload);
|
|
77
|
+
if (candidate.startsWith(PAYLOAD_PREFIX)) {
|
|
78
|
+
const suffix = candidate.slice(PAYLOAD_PREFIX.length);
|
|
79
|
+
return CHOICES.find((choice) => choice === suffix) || null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const label = normalize(title) || candidate;
|
|
83
|
+
if (!label) return null;
|
|
84
|
+
return CHOICES.find((choice) => {
|
|
85
|
+
const configured = normalize(getSafetyNetLabel(choice));
|
|
86
|
+
return configured && configured === label;
|
|
87
|
+
}) || null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const dialledNumbers = (template) => Object.values(template?.types ?? {})
|
|
91
|
+
.flatMap((type) => type?.actions ?? [])
|
|
92
|
+
.filter((action) => action?.type === 'PHONE_NUMBER')
|
|
93
|
+
.map((action) => action?.phone);
|
|
94
|
+
|
|
95
|
+
async function warnIfPhoneDiffersFromTemplate(contentSid) {
|
|
96
|
+
const phone = getSafetyNetPhone();
|
|
97
|
+
if (!phone || phoneCheckedFor === contentSid) return;
|
|
98
|
+
phoneCheckedFor = contentSid;
|
|
99
|
+
try {
|
|
100
|
+
const provider = getMessaging().requireProvider();
|
|
101
|
+
const wanted = phoneDigits(phone);
|
|
102
|
+
|
|
103
|
+
if (dialledNumbers(await provider.getTemplate(contentSid)).map(phoneDigits).includes(wanted)) return;
|
|
104
|
+
|
|
105
|
+
const body = await provider.renderTemplate(contentSid);
|
|
106
|
+
if (body && !phoneDigits(body).includes(wanted)) {
|
|
107
|
+
logger.error('[PausedSafetyNet] The configured phone number is absent from the template', { contentSid });
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
phoneCheckedFor = null;
|
|
111
|
+
logger.warn('[PausedSafetyNet] Could not read the template to check the phone number', { contentSid, error: error.message });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function templateFor(reason) {
|
|
116
|
+
if (reason !== UNASSIGNED) return getSafetyNetContentSid();
|
|
117
|
+
return getSafetyNetUnassignedContentSid() || getSafetyNetContentSid();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const writtenText = (message) => String(message?.plainBody || message?.body || '').trim();
|
|
121
|
+
|
|
122
|
+
function isCourtesyText(text) {
|
|
123
|
+
const plain = text.normalize('NFC').replace(COURTESY_EMOJI, ' ');
|
|
124
|
+
if (!COURTESY_CHARACTERS.test(plain)) return false;
|
|
125
|
+
const words = plain.toLowerCase().split(/[^\p{L}]+/u).filter(Boolean);
|
|
126
|
+
return words.some((word) => COURTESY_ANCHORS.has(word))
|
|
127
|
+
&& words.every((word) => COURTESY_ANCHORS.has(word) || COURTESY_MODIFIERS.has(word));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const isCourtesy = (message) => !message.media?.mediaType && !message.media?.key && !message.interactive_type
|
|
131
|
+
&& isCourtesyText(writtenText(message));
|
|
132
|
+
|
|
133
|
+
async function hasOnlyCourtesyUnanswered(code) {
|
|
134
|
+
try {
|
|
135
|
+
const unanswered = await getMessages(
|
|
136
|
+
{ numero: code, from_me: false, createdAt: { $gt: new Date(Date.now() - getOfferWindowMs()) } },
|
|
137
|
+
{ sort: { createdAt: -1 }, limit: UNANSWERED_LOOKBACK, select: { body: 1, plainBody: 1, media: 1, interactive_type: 1 } }
|
|
138
|
+
);
|
|
139
|
+
return unanswered.length > 0 && unanswered.length < UNANSWERED_LOOKBACK && unanswered.every(isCourtesy);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
logger.warn('[PausedSafetyNet] Could not read the unanswered messages; offering the net', { code, error: error.message });
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
147
|
+
try {
|
|
148
|
+
if (!code || !getSafetyNetContentSid() || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
|
|
149
|
+
if (await patientIsDeceased(code)) return { sent: false, reason: 'deceased' };
|
|
150
|
+
if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
|
|
151
|
+
if (await pausedSince(code, new Date(Date.now() - getPauseQuietMs()))) return { sent: false, reason: 'just_paused' };
|
|
152
|
+
if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
|
|
153
|
+
if (await anyoneRepliedSince(code, new Date(Date.now() - getActivityQuietMs()))) return { sent: false, reason: 'conversation_active' };
|
|
154
|
+
if (await hasOnlyCourtesyUnanswered(code)) return { sent: false, reason: COURTESY_ONLY };
|
|
155
|
+
|
|
156
|
+
const contentSid = templateFor(reason);
|
|
157
|
+
await warnIfPhoneDiffersFromTemplate(contentSid);
|
|
158
|
+
|
|
159
|
+
const result = await getMessaging().sendMessage({ code, contentSid, triggeredBy: SOURCE });
|
|
160
|
+
const sent = result?.success === true || result?.completed === true;
|
|
161
|
+
if (!sent) return { sent: false, reason: result?.status || 'send_failed' };
|
|
162
|
+
|
|
163
|
+
await offerClaims().set(code, true);
|
|
164
|
+
return { sent: true, reason: null };
|
|
165
|
+
} catch (error) {
|
|
166
|
+
logger.error('[PausedSafetyNet] Could not offer the safety net', { code, error: error.message });
|
|
167
|
+
return { sent: false, reason: 'error' };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const offerContentSids = () => [getSafetyNetContentSid(), getSafetyNetUnassignedContentSid()].filter(Boolean);
|
|
172
|
+
|
|
173
|
+
async function offerIsLive(code) {
|
|
174
|
+
try {
|
|
175
|
+
const since = new Date(Date.now() - getOfferWindowMs());
|
|
176
|
+
const [sent] = await getMessages(
|
|
177
|
+
{ numero: code, from_me: true, content_sid: { $in: offerContentSids() }, createdAt: { $gt: since } },
|
|
178
|
+
{ sort: { createdAt: -1 }, limit: 1 }
|
|
179
|
+
);
|
|
180
|
+
return Boolean(sent);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
logger.error('[PausedSafetyNet] Could not read the offer history; honouring the tap', { code, error: error.message });
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function unansweredText(code) {
|
|
188
|
+
const [written] = await getMessages(
|
|
189
|
+
{ numero: code, from_me: false, interactive_type: null },
|
|
190
|
+
{ sort: { createdAt: -1 }, limit: 1 }
|
|
191
|
+
);
|
|
192
|
+
return written ? writtenText(written) : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function staffSenderSince(code, since) {
|
|
196
|
+
try {
|
|
197
|
+
const [sent] = await getMessages(staffSendFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
|
|
198
|
+
return isStaffSend(sent?.triggeredBy) ? sent.triggeredBy : null;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
logger.warn('[PausedSafetyNet] Could not read who last wrote to the patient', { code, error: error.message });
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function opsAlertFor(code, reason) {
|
|
206
|
+
const alert = OPS_ALERTS[reason] || OPS_ALERTS.paused;
|
|
207
|
+
const staff = await staffSenderSince(code, new Date(Date.now() - getHumanQuietMs()));
|
|
208
|
+
return staff ? { ...alert, summary: `escribió después de un mensaje de ${staff}` } : alert;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const assistantNamedOn = (thread) => Boolean(thread?.getAssistantId?.() || thread?.assistant_id);
|
|
212
|
+
|
|
213
|
+
async function coverIfUnassigned({ code, thread }) {
|
|
214
|
+
if (!code || assistantNamedOn(thread)) return;
|
|
215
|
+
try {
|
|
216
|
+
await coverUnansweredPatient({ code, reason: UNASSIGNED });
|
|
217
|
+
} catch (error) {
|
|
218
|
+
logger.warn('[PausedSafetyNet] Could not cover an unassigned patient', { code, error: error.message });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function coverUnansweredPatient({ code, reason = PAUSED }) {
|
|
223
|
+
if (!code) return;
|
|
224
|
+
|
|
225
|
+
const claim = await acquireSendClaim({ idempotencyKey: `safetynet-cover:${code}` });
|
|
226
|
+
if (!claim.acquired) return;
|
|
227
|
+
|
|
228
|
+
const results = await Promise.allSettled([
|
|
229
|
+
Promise.all([unansweredText(code), opsAlertFor(code, reason)])
|
|
230
|
+
.then(([text, alert]) => recordPausedThreadMessage({ code, text, alert })),
|
|
231
|
+
offerSafetyNet({ code, reason }),
|
|
232
|
+
]);
|
|
233
|
+
|
|
234
|
+
const covered = results.every((r) => r.status === 'fulfilled') && results[1].value?.reason !== COURTESY_ONLY;
|
|
235
|
+
if (covered) await completeSendClaim(claim.claimId);
|
|
236
|
+
else await releaseSendClaim(claim.claimId);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const trimmed = (value) => (typeof value === 'string' ? value.trim().replace(/[.\s]+$/, '') : '');
|
|
240
|
+
|
|
241
|
+
function claimedAlert(alert) {
|
|
242
|
+
if (alert === true) return OPS_ALERTS.unassigned;
|
|
243
|
+
const label = trimmed(alert?.label);
|
|
244
|
+
const summary = trimmed(alert?.summary);
|
|
245
|
+
return label && summary ? { label, summary } : null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function alertOpsForClaimedMessage({ code, alert, text = null }) {
|
|
249
|
+
const opsAlert = claimedAlert(alert);
|
|
250
|
+
if (!code || !opsAlert) return false;
|
|
251
|
+
try {
|
|
252
|
+
return await recordPausedThreadMessage({ code, text, alert: opsAlert });
|
|
253
|
+
} catch (error) {
|
|
254
|
+
logger.error('[PausedSafetyNet] Could not alert ops about a message the consumer answered', { code, error: error.message });
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function fileUrgentRequest(code, choice) {
|
|
260
|
+
const copy = REQUEST_COPY[choice];
|
|
261
|
+
return recordUnresolvedRequest({
|
|
262
|
+
code,
|
|
263
|
+
trace: null,
|
|
264
|
+
question: copy.question,
|
|
265
|
+
details: copy.details(code),
|
|
266
|
+
category: REQUEST_CATEGORY,
|
|
267
|
+
urgency: 'urgent'
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function applyChoice(code, choice) {
|
|
272
|
+
const queued = await fileUrgentRequest(code, choice);
|
|
273
|
+
if (!queued) return { queued, pledge: null };
|
|
274
|
+
|
|
275
|
+
if (!(await cancelPendingFollowUps({ code, reason: 'safety_net_request' }))) {
|
|
276
|
+
logger.error('[PausedSafetyNet] Pending follow-ups were not stood down', { code });
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
return { queued, pledge: await openPledge({ code }) };
|
|
281
|
+
} catch (error) {
|
|
282
|
+
logger.error('[PausedSafetyNet] The request was filed but no pledge was opened', { code, error: error.message });
|
|
283
|
+
return { queued, pledge: null };
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const withPhone = (text, closing) => {
|
|
288
|
+
const phone = getSafetyNetPhone();
|
|
289
|
+
return phone ? `${text} ${closing.replace('{phone}', phone)}` : text;
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
function ackFor(choice, outcome) {
|
|
293
|
+
if (outcome.stale) {
|
|
294
|
+
return withPhone('Recibimos tu respuesta y el equipo va a revisar tu conversación.', 'Si necesitas ayuda ahora, llámanos al {phone}.');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (!outcome.queued) {
|
|
298
|
+
return withPhone('No pudimos registrar tu solicitud.', 'Por favor llámanos al {phone} para que te atendamos.');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (!outcome.pledge) {
|
|
302
|
+
return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return withPhone(
|
|
306
|
+
'Listo. Un miembro del equipo te va a contactar a la brevedad.',
|
|
307
|
+
'Si te sientes peor antes, llámanos al {phone}.'
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function sendAck(code, choice, outcome) {
|
|
312
|
+
try {
|
|
313
|
+
await getMessaging().sendMessage({ code, body: ackFor(choice, outcome), triggeredBy: SOURCE });
|
|
314
|
+
return true;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
logger.error('[PausedSafetyNet] Could not acknowledge the tap', { code, choice, error: error.message });
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function handleSafetyNetTap({ code, payload, title }) {
|
|
322
|
+
const choice = matchSafetyNetChoice(payload, title);
|
|
323
|
+
if (!choice || !code) return { handled: false };
|
|
324
|
+
|
|
325
|
+
const claim = await acquireSendClaim({ idempotencyKey: `safetynet:${code}:${choice}` });
|
|
326
|
+
if (!claim.acquired) return { handled: true, choice, reason: 'concurrent_tap' };
|
|
327
|
+
|
|
328
|
+
let acknowledged = false;
|
|
329
|
+
let filed = true;
|
|
330
|
+
try {
|
|
331
|
+
if (!await offerIsLive(code)) {
|
|
332
|
+
acknowledged = await sendAck(code, choice, { queued: true, pledge: null, repeated: false, stale: true });
|
|
333
|
+
return { handled: true, choice, queued: false, stale: true };
|
|
334
|
+
}
|
|
335
|
+
await offerClaims().set(code, true);
|
|
336
|
+
|
|
337
|
+
const chosen = await tapClaims().get(code);
|
|
338
|
+
const repeated = Boolean(chosen);
|
|
339
|
+
const effective = repeated ? chosen : choice;
|
|
340
|
+
|
|
341
|
+
let outcome = { queued: true, pledge: null, repeated };
|
|
342
|
+
if (!repeated) {
|
|
343
|
+
try {
|
|
344
|
+
outcome = { ...await applyChoice(code, choice), repeated: false };
|
|
345
|
+
if (outcome.queued) await tapClaims().set(code, choice);
|
|
346
|
+
} catch (error) {
|
|
347
|
+
logger.error('[PausedSafetyNet] Could not record the tap', { code, choice, error: error.message });
|
|
348
|
+
outcome = { queued: false, pledge: null, repeated: false };
|
|
349
|
+
}
|
|
350
|
+
filed = outcome.queued;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
acknowledged = await sendAck(code, effective, outcome);
|
|
354
|
+
return { handled: true, choice: effective, ...outcome };
|
|
355
|
+
} finally {
|
|
356
|
+
if (acknowledged && filed) await completeSendClaim(claim.claimId);
|
|
357
|
+
else await releaseSendClaim(claim.claimId);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function registerSafetyNetRoutes() {
|
|
362
|
+
const armed = Boolean(getSafetyNetContentSid()) && Boolean(getSafetyNetPhone());
|
|
363
|
+
if (!armed) {
|
|
364
|
+
if (getSafetyNetContentSid()) logger.error('[PausedSafetyNet] A template is configured without a phone number; the safety net stays disarmed');
|
|
365
|
+
disarmSafetyNet();
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
registerInteractiveRoute(PAYLOAD_PREFIX, handleSafetyNetTap);
|
|
370
|
+
return true;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
module.exports = {
|
|
374
|
+
alertOpsForClaimedMessage,
|
|
375
|
+
coverUnansweredPatient,
|
|
376
|
+
coverIfUnassigned,
|
|
377
|
+
disarmSafetyNet,
|
|
378
|
+
offerSafetyNet,
|
|
379
|
+
PAUSED,
|
|
380
|
+
UNASSIGNED,
|
|
381
|
+
handleSafetyNetTap,
|
|
382
|
+
matchSafetyNetChoice,
|
|
383
|
+
registerSafetyNetRoutes,
|
|
384
|
+
_resetSafetyNetState,
|
|
385
|
+
PAYLOAD_PREFIX,
|
|
386
|
+
CHOICES
|
|
387
|
+
};
|
|
@@ -2,7 +2,7 @@ const { Config_ID } = require('../../config/airtableConfig');
|
|
|
2
2
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
3
3
|
|
|
4
4
|
const { logger } = require('../../utils/logger');
|
|
5
|
-
const MapCache = require('../../utils/MapCache');
|
|
5
|
+
const { MapCache } = require('../../utils/MapCache');
|
|
6
6
|
|
|
7
7
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
8
8
|
const { hasTool, getRegisteredToolNames } = require('../../services/toolRegistryService');
|
|
@@ -15,6 +15,15 @@ const snippetCache = new MapCache({ maxSize: 200, ttl: CACHE_TTL });
|
|
|
15
15
|
const toolCache = new MapCache({ maxSize: 50, ttl: CACHE_TTL });
|
|
16
16
|
const presetCache = new MapCache({ maxSize: 50, ttl: CACHE_TTL });
|
|
17
17
|
|
|
18
|
+
async function fetchConfigRecords(table, filter) {
|
|
19
|
+
const records = await getRecordByFilter(Config_ID, table, filter);
|
|
20
|
+
if (!records) {
|
|
21
|
+
logger.error('[promptComposer] Airtable read failed — refusing to widen the toolset', { table, filter });
|
|
22
|
+
throw new Error(`[promptComposer] Airtable read failed for ${table}`);
|
|
23
|
+
}
|
|
24
|
+
return records;
|
|
25
|
+
}
|
|
26
|
+
|
|
18
27
|
async function fetchPreset(presetId, version = null) {
|
|
19
28
|
const cacheKey = version ? `preset:${presetId}:v${version}` : `preset:${presetId}:active`;
|
|
20
29
|
const cached = presetCache.get(cacheKey);
|
|
@@ -24,8 +33,13 @@ async function fetchPreset(presetId, version = null) {
|
|
|
24
33
|
? `AND({preset_id} = "${presetId}", {version} = ${version})`
|
|
25
34
|
: `AND({preset_id} = "${presetId}", {is_active} = 1)`;
|
|
26
35
|
|
|
27
|
-
const records = await
|
|
28
|
-
|
|
36
|
+
const records = await fetchConfigRecords('presets', filter);
|
|
37
|
+
if (records.length > 1) {
|
|
38
|
+
logger.error('[promptComposer] Ambiguous preset — several records match; using the first', {
|
|
39
|
+
presetId, version, matched: records.length,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const record = records[0] || null;
|
|
29
43
|
if (record) presetCache.set(cacheKey, record);
|
|
30
44
|
return record;
|
|
31
45
|
}
|
|
@@ -54,6 +68,10 @@ function applyVariables(text, variables) {
|
|
|
54
68
|
return text.replace(/\{\{(\w+)\}\}/g, (_, key) => variables[key] ?? '');
|
|
55
69
|
}
|
|
56
70
|
|
|
71
|
+
function variablesReferencedIn(text) {
|
|
72
|
+
return [...new Set([...(text || '').matchAll(/\{\{(\w+)\}\}/g)].map(m => m[1]))];
|
|
73
|
+
}
|
|
74
|
+
|
|
57
75
|
async function fetchSnippetsByRecordIds(recordIds) {
|
|
58
76
|
if (!recordIds?.length) return [];
|
|
59
77
|
|
|
@@ -68,8 +86,8 @@ async function fetchSnippetsByRecordIds(recordIds) {
|
|
|
68
86
|
snippetCache.set(cacheKey, snippets);
|
|
69
87
|
return snippets;
|
|
70
88
|
} catch (error) {
|
|
71
|
-
logger.error('[promptComposer] Failed to fetch preset snippets', { error: error.message });
|
|
72
|
-
|
|
89
|
+
logger.error('[promptComposer] Failed to fetch preset snippets — refusing to narrow the prompt', { error: error.message });
|
|
90
|
+
throw error;
|
|
73
91
|
}
|
|
74
92
|
}
|
|
75
93
|
|
|
@@ -77,6 +95,7 @@ async function composePrompt({ presetId = null, presetVersion = null, promptId =
|
|
|
77
95
|
let resolvedPromptId = promptId;
|
|
78
96
|
let presetSnippetIds = null;
|
|
79
97
|
let presetToolIds = null;
|
|
98
|
+
let presetSkillIds = null;
|
|
80
99
|
let resolvedPresetVersion = null;
|
|
81
100
|
let modelConfig = null;
|
|
82
101
|
|
|
@@ -84,10 +103,12 @@ async function composePrompt({ presetId = null, presetVersion = null, promptId =
|
|
|
84
103
|
const preset = await fetchPreset(id, version);
|
|
85
104
|
if (!preset) {
|
|
86
105
|
logger.error('[promptComposer] Preset not found in Airtable', { presetId: id, presetVersion: version });
|
|
106
|
+
presetToolIds = [];
|
|
87
107
|
return;
|
|
88
108
|
}
|
|
89
109
|
presetSnippetIds = preset.snippets || [];
|
|
90
110
|
presetToolIds = preset.tools || [];
|
|
111
|
+
presetSkillIds = preset.skills || [];
|
|
91
112
|
resolvedPresetVersion = preset.version ? String(preset.version) : null;
|
|
92
113
|
|
|
93
114
|
if (preset.model_config) {
|
|
@@ -132,6 +153,7 @@ async function composePrompt({ presetId = null, presetVersion = null, promptId =
|
|
|
132
153
|
baseContent = [...sorted.map(s => s.content), baseContent].join('\n\n');
|
|
133
154
|
}
|
|
134
155
|
|
|
156
|
+
const interpolatedVariables = variablesReferencedIn(baseContent);
|
|
135
157
|
const resolvedPrompt = applyVariables(baseContent, variables);
|
|
136
158
|
|
|
137
159
|
logger.debug('[promptComposer] Prompt composed', {
|
|
@@ -145,9 +167,11 @@ async function composePrompt({ presetId = null, presetVersion = null, promptId =
|
|
|
145
167
|
|
|
146
168
|
return {
|
|
147
169
|
resolvedPrompt,
|
|
170
|
+
interpolatedVariables,
|
|
148
171
|
snippetIds,
|
|
149
172
|
promptId: resolvedPromptId,
|
|
150
173
|
presetToolIds,
|
|
174
|
+
presetSkillIds,
|
|
151
175
|
presetId: presetId || null,
|
|
152
176
|
presetVersion: resolvedPresetVersion,
|
|
153
177
|
modelConfig,
|
|
@@ -161,16 +185,25 @@ async function fetchToolsByRecordIds(recordIds) {
|
|
|
161
185
|
const cached = toolCache.get(cacheKey);
|
|
162
186
|
if (cached) return cached;
|
|
163
187
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
188
|
+
const formula = `OR(${recordIds.map(id => `RECORD_ID()="${id}"`).join(',')})`;
|
|
189
|
+
const tools = await fetchConfigRecords('tools', formula);
|
|
190
|
+
toolCache.set(cacheKey, tools);
|
|
191
|
+
return tools;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const BLANK_TOOL_ID = '(blank tool_id)';
|
|
195
|
+
const warnedUnlinked = new Set();
|
|
196
|
+
|
|
197
|
+
function warnUnlinkedRegisteredTools(linkedToolIds, promptId) {
|
|
198
|
+
const linked = new Set(linkedToolIds);
|
|
199
|
+
const unlinked = getRegisteredToolNames().filter(name => !linked.has(name)).sort();
|
|
200
|
+
if (!unlinked.length) return;
|
|
201
|
+
const signature = `${promptId || '(no prompt)'}|${unlinked.join(',')}`;
|
|
202
|
+
if (warnedUnlinked.has(signature)) return;
|
|
203
|
+
warnedUnlinked.add(signature);
|
|
204
|
+
logger.warn('[promptComposer] Registered in code but not linked to the preset — never offered to the model', {
|
|
205
|
+
promptId, unlinked,
|
|
206
|
+
});
|
|
174
207
|
}
|
|
175
208
|
|
|
176
209
|
async function resolveTools({ promptId, assistant, presetToolIds = null, status = runtimeConfig.getServerMode() }) {
|
|
@@ -179,30 +212,50 @@ async function resolveTools({ promptId, assistant, presetToolIds = null, status
|
|
|
179
212
|
|
|
180
213
|
if (!hasRegistryTools && !hasAssistantTools) return { toolIds: [], filtered: false, descriptions: {} };
|
|
181
214
|
if (presetToolIds == null) return { toolIds: [], filtered: false, descriptions: {} };
|
|
182
|
-
if (presetToolIds.length === 0)
|
|
215
|
+
if (presetToolIds.length === 0) {
|
|
216
|
+
warnUnlinkedRegisteredTools([], promptId);
|
|
217
|
+
return { toolIds: [], filtered: true, descriptions: {} };
|
|
218
|
+
}
|
|
183
219
|
|
|
184
220
|
const mappedTools = await fetchToolsByRecordIds(presetToolIds);
|
|
185
|
-
if (!mappedTools.length)
|
|
221
|
+
if (!mappedTools.length) {
|
|
222
|
+
logger.error('[promptComposer] Preset tool ids resolved to no records — running with no tools', {
|
|
223
|
+
promptId, linked: presetToolIds.length,
|
|
224
|
+
});
|
|
225
|
+
return { toolIds: [], filtered: true, descriptions: {} };
|
|
226
|
+
}
|
|
186
227
|
|
|
187
228
|
const isProd = status === 'prod';
|
|
188
229
|
const activeTools = mappedTools.filter(t => !t.status || t.status === 'prod' || (!isProd && t.status === 'dev'));
|
|
189
230
|
|
|
190
231
|
const validToolIds = [];
|
|
232
|
+
const unregisteredToolIds = [];
|
|
191
233
|
const descriptions = {};
|
|
192
234
|
|
|
193
235
|
for (const tool of activeTools) {
|
|
194
236
|
const id = tool.tool_id;
|
|
195
237
|
if (hasTool(id) || assistant?.tools?.has(id)) {
|
|
196
238
|
validToolIds.push(id);
|
|
197
|
-
|
|
239
|
+
// An Airtable column retyped away from long text would otherwise reach the model as [object Object].
|
|
240
|
+
if (typeof tool.description === 'string' && tool.description) descriptions[id] = tool.description;
|
|
198
241
|
} else {
|
|
199
|
-
|
|
242
|
+
unregisteredToolIds.push(id || BLANK_TOOL_ID);
|
|
243
|
+
logger.error('[promptComposer] Tool mapped in Airtable but not registered in code', { toolId: id, promptId });
|
|
200
244
|
}
|
|
201
245
|
}
|
|
202
246
|
|
|
247
|
+
if (validToolIds.length === 0) {
|
|
248
|
+
logger.error('[promptComposer] Preset links tools but none resolved — the agent will run with NO tools', {
|
|
249
|
+
promptId, status, linked: presetToolIds.length,
|
|
250
|
+
dropped: mappedTools.map(t => `${t.tool_id}:${t.status || 'prod'}`),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
warnUnlinkedRegisteredTools(mappedTools.map(t => t.tool_id).filter(Boolean), promptId);
|
|
255
|
+
|
|
203
256
|
logger.debug('[promptComposer] Tools resolved', { promptId, mapped: activeTools.length, valid: validToolIds.length, filtered: true });
|
|
204
257
|
|
|
205
|
-
return { toolIds: validToolIds, filtered: true, descriptions };
|
|
258
|
+
return { toolIds: validToolIds, filtered: true, descriptions, unregisteredToolIds };
|
|
206
259
|
}
|
|
207
260
|
|
|
208
261
|
function clearCache() {
|
|
@@ -212,4 +265,4 @@ function clearCache() {
|
|
|
212
265
|
presetCache.clear();
|
|
213
266
|
}
|
|
214
267
|
|
|
215
|
-
module.exports = { composePrompt, resolveTools, clearCache, _test: { applyVariables, sortSnippets } };
|
|
268
|
+
module.exports = { composePrompt, resolveTools, clearCache, variablesReferencedIn, _test: { applyVariables, sortSnippets, resetUnlinkedWarnings: () => warnedUnlinked.clear() } };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const { rtContextBlockLive } = require('../flags/clinicalContextFlags');
|
|
2
|
+
const { Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
|
|
3
|
+
const { escapeFormulaValue, fieldEquals } = require('../../helpers/airtableFormulaHelper');
|
|
4
|
+
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
|
+
const { logger } = require('../../utils/logger');
|
|
6
|
+
const { withTimeout } = require('../../utils/timeoutUtils');
|
|
7
|
+
const { latestCourse, renderRadiotherapyBlock } = require('./radiotherapyPhaseService');
|
|
8
|
+
|
|
9
|
+
const ZONE_FIELDS = ['rt_zona', 'rt_zona_confirmada'];
|
|
10
|
+
const FACT_FIELDS = ['value_text', 'normalized_value', 'report_date'];
|
|
11
|
+
const READ_TIMEOUT_MS = 2000;
|
|
12
|
+
|
|
13
|
+
const courseFacts = (code) => getRecordByFilter(
|
|
14
|
+
Estado_General_ID,
|
|
15
|
+
'facts',
|
|
16
|
+
`AND({variable}='radiotherapy_summary', ARRAYJOIN({whatsapp_id (from patient)})='${escapeFormulaValue(code)}')`,
|
|
17
|
+
null,
|
|
18
|
+
FACT_FIELDS,
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
async function radiotherapyBlockFor(code, now) {
|
|
22
|
+
try {
|
|
23
|
+
if (!rtContextBlockLive() || !code) return '';
|
|
24
|
+
const [zones, facts] = await withTimeout(Promise.all([
|
|
25
|
+
getRecordByFilter(Symptoms_ID, 'estado_general', fieldEquals('whatsapp_id', code), 'Grid view', ZONE_FIELDS),
|
|
26
|
+
courseFacts(code),
|
|
27
|
+
]), READ_TIMEOUT_MS, 'radiotherapy context read');
|
|
28
|
+
const row = zones?.[0] || {};
|
|
29
|
+
return renderRadiotherapyBlock({
|
|
30
|
+
zona: row.rt_zona || null, confirmada: Boolean(row.rt_zona_confirmada), curso: latestCourse(facts), now,
|
|
31
|
+
});
|
|
32
|
+
} catch (error) {
|
|
33
|
+
logger.warn('[radiotherapyContext] block left out', { error: error?.message });
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const withRadiotherapyBlock = (block, rtBlock) => (rtBlock ? [block, rtBlock].filter(Boolean).join('\n\n') : block);
|
|
39
|
+
|
|
40
|
+
module.exports = { radiotherapyBlockFor, withRadiotherapyBlock };
|