@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,601 @@
|
|
|
1
|
+
const { patientMessageFromTrace } = require('../helpers/evidenceAnchorHelper');
|
|
2
|
+
const { parseGradeEstimate, projectGradeEstimate } = require('../helpers/gradeEstimateHelper');
|
|
3
|
+
const { withoutAttachedSkillBodies } = require('../helpers/skillActivationHelper');
|
|
4
|
+
const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
|
|
5
|
+
const { logger } = require('../../utils/logger');
|
|
6
|
+
|
|
7
|
+
const MONITOR_ID = 'contingency_tool_decision';
|
|
8
|
+
const MONITOR_VERSION = '5';
|
|
9
|
+
const PRESET_ID = 'llm_tool_monitor_contingency';
|
|
10
|
+
const EXTRACTION_TOOL = 'extractClinicalInfo';
|
|
11
|
+
const CONTINGENCY_TOOL = 'setContingencyPlan';
|
|
12
|
+
const MAX_EVIDENCE_CHARS = 120000;
|
|
13
|
+
const MAX_EVIDENCE_DEPTH = 12;
|
|
14
|
+
const MAX_RETAINED_CALLS = 10;
|
|
15
|
+
|
|
16
|
+
const CRITERION_BASES = {
|
|
17
|
+
open_target: ['caso_abierto', 'cluster_abierto', 'sin_objetivo_abierto', 'no_identificable'],
|
|
18
|
+
grade_ceiling: ['falta_dato_de_la_rubrica', 'rango_abierto_hacia_arriba', 'escalera_resuelta', 'pendiente_no_mueve_el_grado', 'sin_grado_ni_rubrica'],
|
|
19
|
+
assessment_open: ['evaluacion_incompleta', 'evaluado_y_escalado', 'evaluado_y_no_escalado'],
|
|
20
|
+
};
|
|
21
|
+
const CRITERION_KEYS = Object.keys(CRITERION_BASES);
|
|
22
|
+
const CRITERION_ENTRY_KEYS = ['met', 'basis', 'note'];
|
|
23
|
+
const CRITERION_MET = new Set(['yes', 'no', 'unclear']);
|
|
24
|
+
const MAX_CRITERION_NOTE_CHARS = 160;
|
|
25
|
+
|
|
26
|
+
const criterionSchema = (key) => ({
|
|
27
|
+
type: 'object',
|
|
28
|
+
additionalProperties: false,
|
|
29
|
+
required: CRITERION_ENTRY_KEYS,
|
|
30
|
+
properties: {
|
|
31
|
+
met: { type: 'string', enum: ['yes', 'no', 'unclear'] },
|
|
32
|
+
basis: { type: 'string', enum: CRITERION_BASES[key] },
|
|
33
|
+
note: { type: 'string', description: `Frase corta que nombra el dato concreto, máximo ${MAX_CRITERION_NOTE_CHARS} caracteres.` },
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const JUDGE_SCHEMA = {
|
|
38
|
+
type: 'object',
|
|
39
|
+
additionalProperties: false,
|
|
40
|
+
required: ['verdict', 'grade_ceiling', 'expected_actions', 'findings', 'rationale'],
|
|
41
|
+
properties: {
|
|
42
|
+
verdict: { type: 'string', enum: ['pass', 'findings', 'uncertain'] },
|
|
43
|
+
grade_ceiling: criterionSchema('grade_ceiling'),
|
|
44
|
+
expected_actions: {
|
|
45
|
+
type: 'array',
|
|
46
|
+
items: {
|
|
47
|
+
type: 'object',
|
|
48
|
+
additionalProperties: false,
|
|
49
|
+
required: ['action', 'target_id', 'reason'],
|
|
50
|
+
properties: {
|
|
51
|
+
action: { type: 'string', enum: ['arm', 'resolve', 'rearm'] },
|
|
52
|
+
target_id: { type: ['string', 'null'] },
|
|
53
|
+
reason: { type: 'string' },
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
findings: {
|
|
58
|
+
type: 'array',
|
|
59
|
+
items: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
additionalProperties: false,
|
|
62
|
+
required: [
|
|
63
|
+
'category', 'observed_call_index', 'expected_action', 'observed_action',
|
|
64
|
+
'target_id', 'confidence', 'uncertainty_reason', 'criteria', 'summary_es', 'evidence_es',
|
|
65
|
+
],
|
|
66
|
+
properties: {
|
|
67
|
+
criteria: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
additionalProperties: false,
|
|
70
|
+
required: CRITERION_KEYS,
|
|
71
|
+
properties: Object.fromEntries(CRITERION_KEYS.map((key) => [key, criterionSchema(key)])),
|
|
72
|
+
},
|
|
73
|
+
category: {
|
|
74
|
+
type: 'string',
|
|
75
|
+
enum: ['missing_action', 'unnecessary_action', 'wrong_action', 'unsafe_or_invalid_arguments', 'uncertain'],
|
|
76
|
+
},
|
|
77
|
+
observed_call_index: {
|
|
78
|
+
type: ['integer', 'null'],
|
|
79
|
+
description: 'Índice dentro de contingency_calls de la llamada que motiva el hallazgo. Usa null cuando el hallazgo no señala una llamada concreta — en particular siempre que category sea missing_action, porque ahí no hubo llamada.',
|
|
80
|
+
},
|
|
81
|
+
expected_action: { type: ['string', 'null'], enum: ['arm', 'resolve', 'rearm', null] },
|
|
82
|
+
observed_action: { type: ['string', 'null'], enum: ['arm', 'resolve', 'rearm', null] },
|
|
83
|
+
target_id: { type: ['string', 'null'] },
|
|
84
|
+
confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
|
|
85
|
+
uncertainty_reason: {
|
|
86
|
+
type: ['string', 'null'],
|
|
87
|
+
enum: ['prior_net_state', 'outbound_content', 'clinical_signal', 'other', null],
|
|
88
|
+
},
|
|
89
|
+
summary_es: { type: 'string' },
|
|
90
|
+
evidence_es: { type: 'string' },
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
rationale: { type: 'string' },
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const JUDGE_VERDICTS = new Set(['pass', 'findings', 'uncertain']);
|
|
99
|
+
const JUDGE_CATEGORIES = new Set([
|
|
100
|
+
'missing_action', 'unnecessary_action', 'wrong_action', 'unsafe_or_invalid_arguments', 'uncertain',
|
|
101
|
+
]);
|
|
102
|
+
const ACTIONS = new Set(['arm', 'resolve', 'rearm']);
|
|
103
|
+
const CONFIDENCES = new Set(['high', 'medium', 'low']);
|
|
104
|
+
const JUDGE_KEYS = ['verdict', 'grade_ceiling', 'expected_actions', 'findings', 'rationale'];
|
|
105
|
+
const EXPECTED_ACTION_KEYS = ['action', 'target_id', 'reason'];
|
|
106
|
+
const FINDING_KEYS = [
|
|
107
|
+
'category', 'observed_call_index', 'expected_action', 'observed_action',
|
|
108
|
+
'target_id', 'confidence', 'uncertainty_reason', 'summary_es', 'evidence_es',
|
|
109
|
+
];
|
|
110
|
+
const OPTIONAL_FINDING_KEYS = ['criteria'];
|
|
111
|
+
const UNCERTAINTY_REASONS = new Set(['prior_net_state', 'outbound_content', 'clinical_signal', 'other']);
|
|
112
|
+
const UNGROUNDED_CITATION = 'ungrounded_citation';
|
|
113
|
+
const SENSITIVE_EVIDENCE_KEYS = new Set([
|
|
114
|
+
'address', 'apellido', 'apellidos', 'bridge_text', 'calle', 'colonia', 'context',
|
|
115
|
+
'correo', 'curp', 'direccion', 'email', 'first_name', 'full_name', 'last_name', 'message',
|
|
116
|
+
'message_text', 'name', 'nombre', 'patient_code', 'patient_id', 'patient_message',
|
|
117
|
+
'patient_name', 'phone', 'phone_number', 'postal_code', 'raw_message', 'street', 'verbatim_quote',
|
|
118
|
+
'whatsapp_id', 'zip_code',
|
|
119
|
+
]);
|
|
120
|
+
|
|
121
|
+
const ESCALATION_TOOLS = new Set(['reportMedicalEscalation', 'reportCrisis']);
|
|
122
|
+
const GRADING_TOOLS = new Set(['recordClinicalImpression', 'openCondition']);
|
|
123
|
+
|
|
124
|
+
const asArray = (value) => (Array.isArray(value) ? value : []);
|
|
125
|
+
|
|
126
|
+
function bounded(value, depth = 0) {
|
|
127
|
+
if (typeof value === 'string') return value.slice(0, 8000);
|
|
128
|
+
if (value == null || typeof value !== 'object') return value;
|
|
129
|
+
if (depth >= 6) return '[contenido anidado omitido]';
|
|
130
|
+
if (Array.isArray(value)) return value.slice(0, 40).map((item) => bounded(item, depth + 1));
|
|
131
|
+
return Object.fromEntries(Object.entries(value).slice(0, 80).map(([key, item]) => [key, bounded(item, depth + 1)]));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function minimized(value, depth = 0) {
|
|
135
|
+
if (value == null || typeof value === 'number' || typeof value === 'boolean') return value;
|
|
136
|
+
if (typeof value === 'string') {
|
|
137
|
+
const trimmed = value.trim();
|
|
138
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}'))
|
|
139
|
+
|| (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
140
|
+
try {
|
|
141
|
+
return minimized(JSON.parse(trimmed), depth);
|
|
142
|
+
} catch (_error) {
|
|
143
|
+
// Keep bounded non-JSON diagnostics, but redact direct contact identifiers.
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return redactDirectIdentifiers(value).slice(0, 8000);
|
|
147
|
+
}
|
|
148
|
+
if (typeof value !== 'object') return String(value);
|
|
149
|
+
if (depth >= MAX_EVIDENCE_DEPTH) return '[contenido anidado omitido]';
|
|
150
|
+
if (Array.isArray(value)) return value.slice(0, 40).map((item) => minimized(item, depth + 1));
|
|
151
|
+
return Object.fromEntries(Object.entries(value)
|
|
152
|
+
.filter(([key]) => !SENSITIVE_EVIDENCE_KEYS.has(key.toLowerCase()))
|
|
153
|
+
.slice(0, 80)
|
|
154
|
+
.map(([key, item]) => [key, minimized(item, depth + 1)]));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function fitEvidence(evidence) {
|
|
158
|
+
if (JSON.stringify(evidence).length <= MAX_EVIDENCE_CHARS) return evidence;
|
|
159
|
+
const compact = {
|
|
160
|
+
...evidence,
|
|
161
|
+
outbound: bounded(evidence.outbound, 4),
|
|
162
|
+
extractions: evidence.extractions.slice(0, 10).map((step) => ({
|
|
163
|
+
...step,
|
|
164
|
+
arguments: bounded(step.arguments, 5),
|
|
165
|
+
output: bounded(step.output, 5),
|
|
166
|
+
})),
|
|
167
|
+
contingency_calls: evidence.contingency_calls.slice(0, MAX_RETAINED_CALLS).map((step) => ({
|
|
168
|
+
...step,
|
|
169
|
+
arguments: bounded(step.arguments, 5),
|
|
170
|
+
output: bounded(step.output, 5),
|
|
171
|
+
})),
|
|
172
|
+
relevant_steps: evidence.relevant_steps.slice(0, 10).map((step) => ({
|
|
173
|
+
tool_name: step.tool_name,
|
|
174
|
+
success: step.success,
|
|
175
|
+
iteration: step.iteration,
|
|
176
|
+
...(Number.isInteger(step.contingency_call_index) ? { contingency_call_index: step.contingency_call_index } : {}),
|
|
177
|
+
...(GRADING_TOOLS.has(step.tool_name) ? {
|
|
178
|
+
event: step.event,
|
|
179
|
+
ctcae_term: step.ctcae_term,
|
|
180
|
+
grade_estimate: step.grade_estimate,
|
|
181
|
+
missing_for_higher_grade: step.missing_for_higher_grade,
|
|
182
|
+
} : {}),
|
|
183
|
+
})),
|
|
184
|
+
evidence_truncated: true,
|
|
185
|
+
};
|
|
186
|
+
if (JSON.stringify(compact).length > MAX_EVIDENCE_CHARS) {
|
|
187
|
+
compact.signals = '[señales omitidas por tamaño]';
|
|
188
|
+
}
|
|
189
|
+
if (JSON.stringify(compact).length > MAX_EVIDENCE_CHARS) {
|
|
190
|
+
compact.outbound = bounded(evidence.outbound, 2);
|
|
191
|
+
compact.extractions = compact.extractions.map((step) => ({
|
|
192
|
+
tool_name: step.tool_name, success: step.success, iteration: step.iteration,
|
|
193
|
+
}));
|
|
194
|
+
compact.contingency_calls = compact.contingency_calls.map((step) => ({
|
|
195
|
+
index: step.index, tool_name: step.tool_name, success: step.success,
|
|
196
|
+
iteration: step.iteration, action: step.action, target_id: step.target_id,
|
|
197
|
+
already_resolved: step.already_resolved,
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
return compact;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function toolSteps(trace, name) {
|
|
204
|
+
return asArray(trace?.steps).filter((step) => step?.tool_name === name);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function observedAction(step) {
|
|
208
|
+
const args = step?.tool_arguments || step?.arguments;
|
|
209
|
+
if (!args) return null;
|
|
210
|
+
const action = (typeof args.action === 'string' ? args.action : '').trim().toLowerCase() || 'arm';
|
|
211
|
+
return ACTIONS.has(action) ? action : null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function targetId(step) {
|
|
215
|
+
const args = step?.tool_arguments || step?.arguments || {};
|
|
216
|
+
return args.plan_id || args.related_case_id || args.related_cluster_id || null;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function timelineStep(step, callIndex) {
|
|
220
|
+
return {
|
|
221
|
+
tool_name: step.tool_name,
|
|
222
|
+
success: step.success !== false,
|
|
223
|
+
iteration: step.iteration ?? null,
|
|
224
|
+
contingency_call_index: callIndex,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const MONITOR_GRADE_FIELDS = ['best_estimate', 'confidence', 'possible_range', 'functional_anchor', 'source', 'matched_grade'];
|
|
229
|
+
|
|
230
|
+
function gradedNumbers(raw) {
|
|
231
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
232
|
+
const parsed = parseGradeEstimate(raw);
|
|
233
|
+
if (parsed.error) return null;
|
|
234
|
+
const projected = projectGradeEstimate(parsed);
|
|
235
|
+
return MONITOR_GRADE_FIELDS.reduce((out, key) => Object.assign(out, { [key]: projected[key] ?? null }), {});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function gradingStep(step) {
|
|
239
|
+
const args = minimized(step.tool_arguments || null) || {};
|
|
240
|
+
const missing = typeof args.missing_for_higher_grade === 'string'
|
|
241
|
+
? args.missing_for_higher_grade.slice(0, MAX_CRITERION_NOTE_CHARS)
|
|
242
|
+
: null;
|
|
243
|
+
return {
|
|
244
|
+
tool_name: step.tool_name,
|
|
245
|
+
success: step.success !== false,
|
|
246
|
+
iteration: step.iteration ?? null,
|
|
247
|
+
case_id: args.case_id ?? null,
|
|
248
|
+
ctcae_term: args.ctcae_term ?? null,
|
|
249
|
+
event: args.event ?? null,
|
|
250
|
+
grade_estimate: gradedNumbers(args.grade_estimate),
|
|
251
|
+
trajectory_direction: args.trajectory_direction ?? null,
|
|
252
|
+
missing_for_higher_grade: missing,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function compactStep(step) {
|
|
257
|
+
return {
|
|
258
|
+
tool_name: step.tool_name,
|
|
259
|
+
arguments: minimized(step.tool_arguments || null),
|
|
260
|
+
output: minimized(withoutAttachedSkillBodies(step.tool_output) || null),
|
|
261
|
+
success: step.success !== false,
|
|
262
|
+
iteration: step.iteration ?? null,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function isEligible(trace) {
|
|
267
|
+
return trace?.status === 'completed'
|
|
268
|
+
&& trace?.shadow !== true
|
|
269
|
+
&& toolSteps(trace, EXTRACTION_TOOL).length > 0;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function buildOpsContext(trace) {
|
|
273
|
+
const patientMessage = patientMessageFromTrace(trace);
|
|
274
|
+
return patientMessage ? { patientMessage } : {};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function buildEvidence(trace) {
|
|
278
|
+
if (!trace || typeof trace !== 'object' || Array.isArray(trace)) {
|
|
279
|
+
throw new Error('contingency monitor requires a turn trace object');
|
|
280
|
+
}
|
|
281
|
+
const relevantNames = new Set([
|
|
282
|
+
EXTRACTION_TOOL,
|
|
283
|
+
'getActiveSymptomLandscape',
|
|
284
|
+
'getRouterContextBundle',
|
|
285
|
+
'getPatientRiskAssessment',
|
|
286
|
+
'submitRoutingDecision',
|
|
287
|
+
...ESCALATION_TOOLS,
|
|
288
|
+
...GRADING_TOOLS,
|
|
289
|
+
CONTINGENCY_TOOL,
|
|
290
|
+
]);
|
|
291
|
+
let callPosition = 0;
|
|
292
|
+
const relevantSteps = asArray(trace.steps)
|
|
293
|
+
.filter((step) => relevantNames.has(step?.tool_name))
|
|
294
|
+
.map((step) => {
|
|
295
|
+
if (step.tool_name === CONTINGENCY_TOOL) return timelineStep(step, callPosition++);
|
|
296
|
+
if (ESCALATION_TOOLS.has(step.tool_name)) return timelineStep(step, undefined);
|
|
297
|
+
return GRADING_TOOLS.has(step.tool_name) ? gradingStep(step) : compactStep(step);
|
|
298
|
+
});
|
|
299
|
+
const contingencyCalls = toolSteps(trace, CONTINGENCY_TOOL)
|
|
300
|
+
.map((step, index) => ({ index, ...compactStep(step) }));
|
|
301
|
+
const extractions = toolSteps(trace, EXTRACTION_TOOL).map((step) => compactStep(step));
|
|
302
|
+
const signals = trace.signals || {};
|
|
303
|
+
|
|
304
|
+
return fitEvidence({
|
|
305
|
+
turn_id: trace.turnId,
|
|
306
|
+
turn_created_at: trace.createdAt || null,
|
|
307
|
+
offered_tools: asArray(signals.offeredToolIds),
|
|
308
|
+
tool_was_offered: asArray(signals.offeredToolIds).includes(CONTINGENCY_TOOL),
|
|
309
|
+
extraction_succeeded: extractions.some((step) => step.success),
|
|
310
|
+
extractions,
|
|
311
|
+
contingency_call_count: contingencyCalls.length,
|
|
312
|
+
contingency_calls: contingencyCalls.map((step) => ({
|
|
313
|
+
...step,
|
|
314
|
+
action: observedAction(step),
|
|
315
|
+
target_id: targetId(step),
|
|
316
|
+
already_resolved: step.output?.data?.already_resolved === true,
|
|
317
|
+
})),
|
|
318
|
+
relevant_steps: relevantSteps,
|
|
319
|
+
signals: {
|
|
320
|
+
safetyFlags: signals.safetyFlags ?? null,
|
|
321
|
+
medicalEscalation: signals.medicalEscalation || null,
|
|
322
|
+
crisis: signals.crisis || null,
|
|
323
|
+
contingencyDecision: signals.contingencyDecision || null,
|
|
324
|
+
contingencySnapshot: signals.contingencyMonitorSnapshot || null,
|
|
325
|
+
contingencyPlans: signals.contingencyPlans ?? null,
|
|
326
|
+
contingencyResolutions: signals.contingencyResolutions ?? null,
|
|
327
|
+
reminderIntents: signals.reminderIntents ?? null,
|
|
328
|
+
outboundPurpose: signals.outboundPurpose || null,
|
|
329
|
+
branchTaken: signals.branchTaken || null,
|
|
330
|
+
},
|
|
331
|
+
outbound: {
|
|
332
|
+
present: typeof trace.outbound === 'string' ? trace.outbound.length > 0 : trace.outbound != null,
|
|
333
|
+
purpose: signals.outboundPurpose || null,
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function hasExactKeys(value, requiredKeys, optionalKeys = []) {
|
|
339
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
340
|
+
return Object.keys(value).every((key) => requiredKeys.includes(key) || optionalKeys.includes(key))
|
|
341
|
+
&& requiredKeys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function isNullableString(value) {
|
|
345
|
+
return value === null || typeof value === 'string';
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function isAuditableCriterionEntry(entry, key) {
|
|
349
|
+
return hasExactKeys(entry, CRITERION_ENTRY_KEYS)
|
|
350
|
+
&& CRITERION_MET.has(entry.met)
|
|
351
|
+
&& CRITERION_BASES[key].includes(entry.basis)
|
|
352
|
+
&& typeof entry.note === 'string'
|
|
353
|
+
&& entry.note.trim().length > 0;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function isAuditableCriteria(criteria) {
|
|
357
|
+
if (!hasExactKeys(criteria, CRITERION_KEYS)) return false;
|
|
358
|
+
return CRITERION_KEYS.every((key) => isAuditableCriterionEntry(criteria[key], key));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function boundedCriterionEntry(entry) {
|
|
362
|
+
return { ...entry, note: redactDirectIdentifiers(entry.note).trim().slice(0, MAX_CRITERION_NOTE_CHARS) };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function auditableCriteria(criteria) {
|
|
366
|
+
if (isAuditableCriteria(criteria)) return boundedCriteria(criteria);
|
|
367
|
+
if (criteria) {
|
|
368
|
+
logger.warn({ keys: Object.keys(criteria), expected: CRITERION_KEYS },
|
|
369
|
+
'[contingencyMonitor] judge criteria dropped — the preset is stating a checklist this version no longer reads');
|
|
370
|
+
}
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function boundedCriteria(criteria) {
|
|
375
|
+
return Object.fromEntries(CRITERION_KEYS.map((key) => {
|
|
376
|
+
const entry = criteria[key];
|
|
377
|
+
return [key, boundedCriterionEntry(entry)];
|
|
378
|
+
}));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function buildJudgeInput(evidence) {
|
|
382
|
+
return [{
|
|
383
|
+
role: 'user',
|
|
384
|
+
content: [
|
|
385
|
+
'Evalúa este turno usando únicamente la evidencia capturada durante el turno.',
|
|
386
|
+
'contingency_calls es la lista completa y autoritativa de llamadas a setContingencyPlan en el turno. relevant_steps sólo indica el orden del turno: cuando una de sus entradas es setContingencyPlan trae contingency_call_index, que apunta a esa misma llamada dentro de contingency_calls. Es la misma llamada, no una adicional.',
|
|
387
|
+
'contingency_calls NO es la lista de redes armadas: sólo recoge lo que el agente pidió con la herramienta. El sistema arma redes por su cuenta en ciertas rutas, y esas aparecen únicamente en signals.contingencyPlans, con armedBy indicando quién la armó. Un turno con contingency_calls vacío y una entrada en signals.contingencyPlans es un turno en el que la paciente SÍ quedó vigilada: no lo reportes como missing_action.',
|
|
388
|
+
'No presupongas información clínica ni estado FHIR posterior.',
|
|
389
|
+
'Resume decisiones y señales sin copiar nombres, direcciones, datos de contacto, mensajes ni fragmentos textuales del paciente.',
|
|
390
|
+
JSON.stringify(evidence),
|
|
391
|
+
].join('\n\n'),
|
|
392
|
+
}];
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function validateJudge(judge) {
|
|
396
|
+
if (!hasExactKeys(judge, JUDGE_KEYS)) throw new Error('monitor judge result is missing required fields');
|
|
397
|
+
if (!JUDGE_VERDICTS.has(judge.verdict)) throw new Error('monitor judge returned an invalid verdict');
|
|
398
|
+
if (!Array.isArray(judge.expected_actions) || !Array.isArray(judge.findings) || typeof judge.rationale !== 'string') {
|
|
399
|
+
throw new Error('monitor judge result is missing required fields');
|
|
400
|
+
}
|
|
401
|
+
for (const action of judge.expected_actions) {
|
|
402
|
+
if (!hasExactKeys(action, EXPECTED_ACTION_KEYS)
|
|
403
|
+
|| !ACTIONS.has(action.action)
|
|
404
|
+
|| !isNullableString(action.target_id)
|
|
405
|
+
|| typeof action.reason !== 'string') {
|
|
406
|
+
throw new Error('monitor judge returned an invalid expected action');
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (const finding of judge.findings) {
|
|
410
|
+
if (!hasExactKeys(finding, FINDING_KEYS, OPTIONAL_FINDING_KEYS)
|
|
411
|
+
|| !JUDGE_CATEGORIES.has(finding.category)
|
|
412
|
+
|| (finding.observed_call_index !== null && !Number.isInteger(finding.observed_call_index))
|
|
413
|
+
|| (finding.expected_action !== null && !ACTIONS.has(finding.expected_action))
|
|
414
|
+
|| (finding.observed_action !== null && !ACTIONS.has(finding.observed_action))
|
|
415
|
+
|| !isNullableString(finding.target_id)
|
|
416
|
+
|| !CONFIDENCES.has(finding.confidence)
|
|
417
|
+
|| (finding.uncertainty_reason !== null && !UNCERTAINTY_REASONS.has(finding.uncertainty_reason))
|
|
418
|
+
|| typeof finding.summary_es !== 'string'
|
|
419
|
+
|| typeof finding.evidence_es !== 'string') {
|
|
420
|
+
throw new Error('monitor judge returned an invalid finding');
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (!isAuditableCriterionEntry(judge.grade_ceiling, 'grade_ceiling')) {
|
|
424
|
+
throw new Error('monitor judge returned an unauditable grade_ceiling');
|
|
425
|
+
}
|
|
426
|
+
for (const finding of judge.findings) {
|
|
427
|
+
const inner = finding.criteria?.grade_ceiling;
|
|
428
|
+
if (isAuditableCriterionEntry(inner, 'grade_ceiling')
|
|
429
|
+
&& (inner.met !== judge.grade_ceiling.met || inner.basis !== judge.grade_ceiling.basis)) {
|
|
430
|
+
throw new Error('monitor judge contradicted its own grade ceiling');
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
judge.grade_ceiling = boundedCriterionEntry(judge.grade_ceiling);
|
|
434
|
+
if (judge.verdict === 'pass' && judge.findings.length) throw new Error('monitor judge pass verdict included findings');
|
|
435
|
+
if (judge.verdict === 'findings' && !judge.findings.length) throw new Error('monitor judge findings verdict was empty');
|
|
436
|
+
return judge;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function deterministicFinding(type, overrides = {}) {
|
|
440
|
+
return {
|
|
441
|
+
type,
|
|
442
|
+
severity: 'normal',
|
|
443
|
+
confidence: 'high',
|
|
444
|
+
opsReviewRequired: true,
|
|
445
|
+
expectedAction: null,
|
|
446
|
+
observedAction: null,
|
|
447
|
+
targetId: null,
|
|
448
|
+
observedCallIndex: null,
|
|
449
|
+
uncertaintyReason: null,
|
|
450
|
+
criteria: null,
|
|
451
|
+
summary: '',
|
|
452
|
+
evidence: '',
|
|
453
|
+
...overrides,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function sourceFailureFinding() {
|
|
458
|
+
return deterministicFinding('source_tool_failure', {
|
|
459
|
+
opsReviewRequired: false,
|
|
460
|
+
summary: 'No se pudo completar la extracción clínica del turno.',
|
|
461
|
+
evidence: 'La herramienta de extracción fue llamada, pero ninguna ejecución terminó correctamente.',
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function executionFindings(evidence) {
|
|
466
|
+
return evidence.contingency_calls
|
|
467
|
+
.filter((call) => !call.success)
|
|
468
|
+
.map((call) => deterministicFinding('execution_failure', {
|
|
469
|
+
observedAction: call.action,
|
|
470
|
+
targetId: call.target_id,
|
|
471
|
+
observedCallIndex: call.index,
|
|
472
|
+
summary: 'El agente pidió una acción sobre el plan de contingencia y no se ejecutó correctamente.',
|
|
473
|
+
evidence: `La llamada ${call.index + 1} a la herramienta terminó con error.`,
|
|
474
|
+
}));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const CATEGORY_TO_TYPE = {
|
|
478
|
+
unnecessary_action: 'false_positive',
|
|
479
|
+
wrong_action: 'wrong_action',
|
|
480
|
+
unsafe_or_invalid_arguments: 'unsafe_or_invalid_arguments',
|
|
481
|
+
uncertain: 'uncertain',
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
function changesProtection(finding, evidence) {
|
|
485
|
+
if (!['resolve', 'rearm'].includes(finding.observedAction)) return false;
|
|
486
|
+
const call = asArray(evidence?.contingency_calls).find((item) => item.index === finding.observedCallIndex);
|
|
487
|
+
return call?.already_resolved !== true;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function isIntentionalNoOp(evidence, callIndex, claimedAction) {
|
|
491
|
+
if (claimedAction && claimedAction !== 'resolve') return false;
|
|
492
|
+
const call = asArray(evidence?.contingency_calls).find((item) => item.index === callIndex);
|
|
493
|
+
return call?.action === 'resolve' && call.already_resolved === true && call.success === true;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const isMachineArmed = (plan) => typeof plan?.armedBy === 'string' && plan.armedBy && plan.armedBy !== 'agent';
|
|
497
|
+
|
|
498
|
+
function tookOverAMachineNet(evidence) {
|
|
499
|
+
const plans = asArray(evidence?.signals?.contingencyPlans);
|
|
500
|
+
if (plans.some((plan) => plan?.armedBy === 'agent' && plan?.adoptedFrom && plan.adoptedFrom !== 'agent')) return true;
|
|
501
|
+
const machine = new Set(plans.filter(isMachineArmed).map((plan) => plan.planId));
|
|
502
|
+
return machine.size > 0 && asArray(evidence?.signals?.contingencyResolutions)
|
|
503
|
+
.some((resolution) => resolution?.supersededBy && machine.has(resolution.planId));
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function isMachineNetHandover(evidence, item, callIndex) {
|
|
507
|
+
if (item.category !== 'wrong_action') return false;
|
|
508
|
+
const call = asArray(evidence?.contingency_calls).find((entry) => entry.index === callIndex);
|
|
509
|
+
const observed = call?.action || item.observed_action;
|
|
510
|
+
const pair = new Set([item.expected_action, observed]);
|
|
511
|
+
return pair.size === 2 && pair.has('arm') && pair.has('rearm') && tookOverAMachineNet(evidence);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function reviewPriority(finding, evidence) {
|
|
515
|
+
const expectedSetsProtection = ['arm', 'rearm'].includes(finding.expectedAction);
|
|
516
|
+
const observedChangesProtection = changesProtection(finding, evidence);
|
|
517
|
+
const failedToSetProtection = finding.type === 'execution_failure'
|
|
518
|
+
&& ['arm', 'rearm'].includes(finding.observedAction);
|
|
519
|
+
const missedProtection = ['false_negative', 'tool_unavailable_when_needed'].includes(finding.type)
|
|
520
|
+
&& expectedSetsProtection;
|
|
521
|
+
const incorrectProtectionChange = ['false_positive', 'wrong_action'].includes(finding.type)
|
|
522
|
+
&& (expectedSetsProtection || observedChangesProtection);
|
|
523
|
+
return missedProtection || failedToSetProtection || incorrectProtectionChange ? 'urgent' : 'normal';
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function withReviewPriorities(findings, evidence) {
|
|
527
|
+
return findings.map((finding) => ({ ...finding, severity: reviewPriority(finding, evidence) }));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function resolveCallIndex(evidence, index) {
|
|
531
|
+
if (!Number.isInteger(index)) return null;
|
|
532
|
+
const calls = asArray(evidence.contingency_calls);
|
|
533
|
+
if (calls.some((call) => call.index === index)) return index;
|
|
534
|
+
const cited = asArray(evidence.relevant_steps)[index];
|
|
535
|
+
const position = cited?.contingency_call_index;
|
|
536
|
+
return Number.isInteger(position) && calls.some((call) => call.index === position) ? position : null;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function interpret({ evidence, judge }) {
|
|
540
|
+
if (!evidence.extraction_succeeded) return withReviewPriorities([sourceFailureFinding()], evidence);
|
|
541
|
+
|
|
542
|
+
const findings = executionFindings(evidence);
|
|
543
|
+
const deterministicFindings = findings.length;
|
|
544
|
+
for (const item of asArray(judge?.findings)) {
|
|
545
|
+
let type = CATEGORY_TO_TYPE[item.category];
|
|
546
|
+
if (item.category === 'missing_action') {
|
|
547
|
+
type = evidence.tool_was_offered ? 'false_negative' : 'tool_unavailable_when_needed';
|
|
548
|
+
}
|
|
549
|
+
if (!type) continue;
|
|
550
|
+
const citesCall = item.category !== 'missing_action';
|
|
551
|
+
const observedCallIndex = citesCall ? resolveCallIndex(evidence, item.observed_call_index) : null;
|
|
552
|
+
if (item.category === 'unnecessary_action'
|
|
553
|
+
&& isIntentionalNoOp(evidence, observedCallIndex, item.observed_action)) continue;
|
|
554
|
+
if (isMachineNetHandover(evidence, item, observedCallIndex)) continue;
|
|
555
|
+
const grounded = !citesCall || item.observed_call_index == null || observedCallIndex !== null;
|
|
556
|
+
const finalType = grounded ? type : 'uncertain';
|
|
557
|
+
const uncertaintyReason = finalType !== 'uncertain' ? null
|
|
558
|
+
: (grounded ? (item.uncertainty_reason || null) : UNGROUNDED_CITATION);
|
|
559
|
+
findings.push(deterministicFinding(finalType, {
|
|
560
|
+
opsReviewRequired: type !== 'unsafe_or_invalid_arguments',
|
|
561
|
+
confidence: grounded ? (item.confidence || 'low') : 'low',
|
|
562
|
+
expectedAction: item.expected_action || null,
|
|
563
|
+
observedAction: grounded ? (item.observed_action || null) : null,
|
|
564
|
+
targetId: item.target_id || null,
|
|
565
|
+
observedCallIndex,
|
|
566
|
+
uncertaintyReason,
|
|
567
|
+
criteria: auditableCriteria(item.criteria),
|
|
568
|
+
summary: item.summary_es || 'Decisión que requiere revisión.',
|
|
569
|
+
evidence: item.evidence_es || 'El monitor no entregó evidencia resumida.',
|
|
570
|
+
}));
|
|
571
|
+
}
|
|
572
|
+
if (judge?.verdict === 'uncertain' && findings.length === deterministicFindings) {
|
|
573
|
+
findings.push(deterministicFinding('uncertain', {
|
|
574
|
+
confidence: 'low',
|
|
575
|
+
uncertaintyReason: 'other',
|
|
576
|
+
summary: 'La evidencia disponible no permite evaluar la decisión con seguridad.',
|
|
577
|
+
evidence: judge.rationale || 'Falta información suficiente en el rastro del turno.',
|
|
578
|
+
}));
|
|
579
|
+
}
|
|
580
|
+
return withReviewPriorities(findings, evidence);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
const contingencyMonitorSpec = {
|
|
584
|
+
maxRetainedCalls: MAX_RETAINED_CALLS,
|
|
585
|
+
id: MONITOR_ID,
|
|
586
|
+
version: MONITOR_VERSION,
|
|
587
|
+
presetId: PRESET_ID,
|
|
588
|
+
schema: JUDGE_SCHEMA,
|
|
589
|
+
reconcileQuery: { steps: { $elemMatch: { tool_name: EXTRACTION_TOOL } } },
|
|
590
|
+
isEligible,
|
|
591
|
+
buildOpsContext,
|
|
592
|
+
buildEvidence,
|
|
593
|
+
buildJudgeInput,
|
|
594
|
+
validateJudge,
|
|
595
|
+
interpret,
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
module.exports = {
|
|
599
|
+
CRITERION_BASES,
|
|
600
|
+
contingencyMonitorSpec,
|
|
601
|
+
};
|