@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,332 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
const { isShadowRun } = require('../helpers/shadowHelper');
|
|
4
|
+
const { armContingency, computeExpiresAt, stampContingencyPlan, resolveContingency, quietHoursShiftMinutes } = require('../services/contingencyDispatchService');
|
|
5
|
+
const { readSymptomCases, readClusters, readContingencies, storeContingency } = require('../../fhir');
|
|
6
|
+
const { ContingencySafetyNet, ESCALATION_PRIORITIES, RESOLVED_REASONS, RESOLVES_ON, isAgentArmed, isNetActive, isExpired } = require('../../shared/dtos/ContingencySafetyNet');
|
|
7
|
+
const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
8
|
+
const { logger } = require('../../utils/logger');
|
|
9
|
+
|
|
10
|
+
const STEP_SHAPE = '{message, fires_after_silence_minutes, window_reasoning}';
|
|
11
|
+
const MAX_PATIENT_SILENCE_MIN = 1380;
|
|
12
|
+
|
|
13
|
+
const definition = {
|
|
14
|
+
name: 'setContingencyPlan',
|
|
15
|
+
description: `**Does:** Manages the contingency safety net guarding an open case or cluster, selected via \`action\`. A net is a single promise: if the patient goes quiet, you write to them again.\n- \`arm\` (default): arms a new net — a CarePlan anchor plus the follow-up check-in that goes out to the patient after true silence.\n- \`resolve\`: stands an active net down because this turn's conversation addressed the guarded concern, or it is no longer clinically relevant. Requires \`plan_id\` + \`resolution_reasoning\`.\n- \`rearm\`: replaces the target's active net with this new definition (fresh silence window anchored now) — same required fields as \`arm\`. Use when new information changes the concern, window, or message.\n\n**Required inputs:** \`arm\`/\`rearm\`: \`concern\`, \`awaiting_characterization\`; at least one of \`related_case_id\` / \`related_cluster_id\`; \`patient_followup_reminder\` \`${STEP_SHAPE}\` (message + a positive \`fires_after_silence_minutes\` <= ${MAX_PATIENT_SILENCE_MIN}, plus \`window_reasoning\`: one sentence on why that wait). \`resolve\`: \`plan_id\` + \`resolution_reasoning\`.\n\n**When to call:** \`arm\` when, read against the symptom's CTCAE grade scale, a datum is still missing that could put the case at a grade above your current read. If everything needed to settle the severity is already known, do not arm. The rubric is the test, not how alarming the symptom sounds.\n- Missing information could move it from G1 to G2/G3 → arm, and wait for exactly that datum.\n- Everything needed to rule out the higher grades is already known → do not arm.\n- Serious AND fully assessed → escalate. A finished assessment needs a person, not a check-in.\n\nFind the gap in the \`grade_scale\` you graded against: which clause of the next grade up can you neither confirm nor rule out? Name that datum in \`awaiting_characterization\`, concrete enough that the next turn can tell whether their message addressed it. It is an answer the patient still owes about the symptom as it stands now — what qualifies it is that it moves the grade, not the form it takes. A pending detail that cannot change the grade (an administrative confirmation, a name, an appointment) is not a reason to arm. Neither is a watch that starts after the patient already gave that datum — whether the symptom comes back, crosses a threshold you named, or eases with what you recommended: that is continuity, not uncertainty, so schedule a \`seguimiento\` with \`schedulePatientReminder\` instead, and do not re-arm a net you just resolved to cover it. Set \`resolves_on\` to match: \`reply\` for an answer they owe, \`observation\` for an event their next message may not carry.\n\nWaiting on the care team does NOT satisfy this test — a non-routine escalation normally arms its own net, so team follow-up is not this tool's job. A \`routine\` escalation does not — it routes to the team's ticket lane and leaves no net, so on those turns the ceiling test decides on its own merits. Do not condition it on predicting whether the patient will go quiet: that cannot be known, and each message they send pushes the check-in back, but it still goes out once they fall silent unless you resolve the net — so resolve it as soon as they give what it waits for. \`resolve\` when the patient's message answered what the net was waiting to observe; \`rearm\` when the net's definition went stale. Resolve a net only when its awaited datum arrived or the concern it guards was addressed. A care-team indication to book or do a visit or test does not by itself address it: if the net still awaits a grade-changing observation, keep the net as it is and also schedule the seguimiento about the visit or test — an open net does not hold it back. When a net is resolved and the team gave an indication, what remains open is the indication: schedule a \`seguimiento\` with \`schedulePatientReminder\` (\`utility_basis: agreed_action\`) at 24–48 h instead of treating the topic as closed — for a medication or measure, to learn whether it works; for a visit or test, to learn whether it was booked or done and when (ask about the result later, once it has happened).\n\n**When NOT to call:** \`arm\` on a target that already has an active plan (fails hard — use \`resolve\` or \`rearm\`) or whose case/cluster is closed/dissolved; \`resolve\` while the concern is still unobserved (closing the case retires its net automatically). This tool does NOT notify the care team — to reach a human, use the escalation tools.\n\n**Returns:** \`arm\`/\`rearm\` → \`{plan_id}\` (\`rearm\` adds \`superseded_plan_ids\` when it replaced a net). \`resolve\` → \`{plan_id}\`, with \`already_resolved: true\` when the net was retired earlier — an idempotent success, not an error. Fails hard with \`case_not_found_or_wrong_patient\` / \`cluster_not_found_or_wrong_patient\`, \`target_not_open\`, \`active_plan_already_exists_for_case\` / \`_for_cluster\` (arm only), \`plan_not_found_or_wrong_patient\`, \`store_failed_retry_next_turn\`, or \`stand_down_failed_retry_next_turn\`.\n\n**Side effects:** records the action on the turn trace; writes the FHIR CarePlan + patient CommunicationRequest + Provenance; arms or deactivates the dispatch row — the check-in goes out over WhatsApp only if the patient stayed silent through its window, and is pushed back each time they write. Nets also stand down when their case closes or cluster dissolves, and expire on their own after a bounded multiple of the check-in window.`,
|
|
16
|
+
strict: false,
|
|
17
|
+
parameters: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
action: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: ['arm', 'resolve', 'rearm'],
|
|
23
|
+
description: '\'arm\' (default) = new net. \'resolve\' = stand an active net down (requires plan_id + resolution_reasoning). \'rearm\' = replace the target\'s active net with this new definition.',
|
|
24
|
+
},
|
|
25
|
+
plan_id: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'For \'resolve\': the plan to stand down, from getActiveSymptomLandscape.active_contingencies[] or a prior arm.',
|
|
28
|
+
},
|
|
29
|
+
resolution_reasoning: {
|
|
30
|
+
type: 'string',
|
|
31
|
+
description: 'For \'resolve\': one sentence — what in this turn addressed the concern or made the net irrelevant (audit trail).',
|
|
32
|
+
},
|
|
33
|
+
resolution_kind: {
|
|
34
|
+
type: 'string',
|
|
35
|
+
enum: ['concern_addressed', 'no_longer_relevant'],
|
|
36
|
+
description: 'For \'resolve\': \'concern_addressed\' (default) = the awaited answer arrived; \'no_longer_relevant\' = context made the net moot without answering it.',
|
|
37
|
+
},
|
|
38
|
+
concern: {
|
|
39
|
+
type: 'string',
|
|
40
|
+
description: 'The feared trajectory this plan guards against.',
|
|
41
|
+
},
|
|
42
|
+
awaiting_characterization: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
description: 'The datum from the term\'s grade_scale that would rule out a grade above your current read, concrete enough that the next turn can tell whether the patient\'s message addressed it — an answer they still owe about the current presentation (\'temperature reading\', \'whether liquids also get stuck\'). It must be able to move the grade: an administrative confirmation, a name or an appointment does not qualify, and neither does a process confirmation about the care team or a restatement of the concern. A later recurrence, threshold or response to treatment once that datum is known is a seguimiento (schedulePatientReminder), not a net.',
|
|
45
|
+
},
|
|
46
|
+
resolves_on: {
|
|
47
|
+
type: 'string',
|
|
48
|
+
enum: Object.values(RESOLVES_ON),
|
|
49
|
+
description: 'How the net stands down. \'reply\' (default): what you await is an answer they owe — resolve the net when they give it; their other messages only push the check-in back. \'observation\': the net keeps waiting through messages that do not carry it, and stands down only when you `resolve` it, its target closes, or it expires — use it when what you await is an event their next message may not contain, such as the result of something you asked them to do, or a threshold you named.',
|
|
50
|
+
},
|
|
51
|
+
related_case_id: {
|
|
52
|
+
type: 'string',
|
|
53
|
+
description: 'The open case this plan guards. At least one of related_case_id / related_cluster_id is required.',
|
|
54
|
+
},
|
|
55
|
+
related_cluster_id: {
|
|
56
|
+
type: 'string',
|
|
57
|
+
description: 'The non-dissolved cluster this plan guards. At least one of related_case_id / related_cluster_id is required.',
|
|
58
|
+
},
|
|
59
|
+
patient_followup_reminder: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, addressed directly to whoever is in the conversation, in second person and in their language — tú or usted, as in the conversation; never about the reader in third person — about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
required: ['action'],
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
69
|
+
|
|
70
|
+
function fail(error, data = {}) {
|
|
71
|
+
return JSON.stringify({ success: false, error, data });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function recordResolution(runtime, entry) {
|
|
75
|
+
const trace = runtime.trace || null;
|
|
76
|
+
const existing = Array.isArray(trace?.signals?.contingencyResolutions) ? trace.signals.contingencyResolutions : [];
|
|
77
|
+
trace?.setSignals?.({ contingencyResolutions: [...existing, entry] });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function resolveNet(args, runtime) {
|
|
81
|
+
const planId = str(args?.plan_id).trim();
|
|
82
|
+
const reasoning = str(args?.resolution_reasoning).trim();
|
|
83
|
+
const kind = str(args?.resolution_kind).trim() || RESOLVED_REASONS.CONCERN_ADDRESSED;
|
|
84
|
+
if (!planId) return fail('plan_id is required for resolve');
|
|
85
|
+
if (!reasoning) return fail('resolution_reasoning is required for resolve — one short sentence on what addressed the concern.');
|
|
86
|
+
if (![RESOLVED_REASONS.CONCERN_ADDRESSED, RESOLVED_REASONS.NO_LONGER_RELEVANT].includes(kind)) {
|
|
87
|
+
return fail(`unknown resolution_kind: '${kind}'. Must be concern_addressed | no_longer_relevant.`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const patientId = runtime.patientCode;
|
|
91
|
+
const nets = await readContingencies({ patientId });
|
|
92
|
+
const net = nets.find((n) => n.carePlan.planId === planId);
|
|
93
|
+
if (!net) {
|
|
94
|
+
if (isShadowRun()) {
|
|
95
|
+
recordResolution(runtime, { planId, action: 'resolve', reasoning, skipped: 'shadow' });
|
|
96
|
+
logger.info('[setContingencyPlan] resolve on a plan never persisted — shadow run', { turnId: runtime.turnId, planId });
|
|
97
|
+
return JSON.stringify({ success: true, data: { plan_id: planId } });
|
|
98
|
+
}
|
|
99
|
+
return fail('plan_not_found_or_wrong_patient', { plan_id: planId });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (!isNetActive(net)) {
|
|
103
|
+
recordResolution(runtime, { planId, action: 'resolve', reasoning });
|
|
104
|
+
return JSON.stringify({ success: true, data: { plan_id: planId, already_resolved: true } });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const isLive = runtime.isLive?.bind(runtime);
|
|
108
|
+
const skipped = isShadowRun() ? 'shadow' : (isLive && !isLive() ? 'superseded' : null);
|
|
109
|
+
recordResolution(runtime, { planId, action: 'resolve', reasoning, ...(skipped ? { skipped } : {}) });
|
|
110
|
+
if (skipped) {
|
|
111
|
+
logger.info(`[setContingencyPlan] resolve not stored — ${skipped === 'shadow' ? 'shadow run' : 'turn superseded'}`, { turnId: runtime.turnId, planId });
|
|
112
|
+
return JSON.stringify({ success: true, data: { plan_id: planId } });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const ok = await resolveContingency({
|
|
116
|
+
patientCode: patientId, net, resolvedReason: kind, resolutionNote: reasoning, trace: runtime.trace || null,
|
|
117
|
+
});
|
|
118
|
+
if (!ok) return fail('stand_down_failed_retry_next_turn', { plan_id: planId });
|
|
119
|
+
return JSON.stringify({ success: true, data: { plan_id: planId } });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function buildStep(raw, label, armedAt = new Date()) {
|
|
123
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
124
|
+
return { error: `${label} is required and must be a non-empty object ${STEP_SHAPE}` };
|
|
125
|
+
}
|
|
126
|
+
const silence = raw.fires_after_silence_minutes;
|
|
127
|
+
if (typeof silence !== 'number' || !Number.isInteger(silence) || silence <= 0) {
|
|
128
|
+
return { error: `${label}.fires_after_silence_minutes is required and must be a positive integer` };
|
|
129
|
+
}
|
|
130
|
+
if (silence > MAX_PATIENT_SILENCE_MIN) {
|
|
131
|
+
return { error: `${label}.fires_after_silence_minutes must be <= ${MAX_PATIENT_SILENCE_MIN} — a check-in beyond ~23h of silence lands outside the WhatsApp session and cannot be delivered as a normal message` };
|
|
132
|
+
}
|
|
133
|
+
// The quiet-hours hold counts too: a window that ends overnight is sent at the morning start, which must still fall inside the session.
|
|
134
|
+
const held = quietHoursShiftMinutes(armedAt, silence);
|
|
135
|
+
if (silence + held > MAX_PATIENT_SILENCE_MIN) {
|
|
136
|
+
return { error: `${label}.fires_after_silence_minutes of ${silence} ends in the hours when check-ins are held, so it would go out ~${Math.round((silence + held) / 60)}h from now, outside the WhatsApp session — choose a window that ends before 21:00 today or no later than ${MAX_PATIENT_SILENCE_MIN} minutes including that hold` };
|
|
137
|
+
}
|
|
138
|
+
const message = (typeof raw.message === 'string' ? raw.message : '').trim();
|
|
139
|
+
if (!message) return { error: `${label}.message is required` };
|
|
140
|
+
const step = {
|
|
141
|
+
recipient: 'patient',
|
|
142
|
+
message,
|
|
143
|
+
firesAfterSilenceMinutes: silence,
|
|
144
|
+
};
|
|
145
|
+
if (typeof raw.priority === 'string' && raw.priority.trim()) {
|
|
146
|
+
const priority = raw.priority.trim();
|
|
147
|
+
if (!ESCALATION_PRIORITIES.includes(priority)) {
|
|
148
|
+
return { error: 'invalid_priority', data: { priority, allowed: ESCALATION_PRIORITIES } };
|
|
149
|
+
}
|
|
150
|
+
step.priority = priority;
|
|
151
|
+
}
|
|
152
|
+
if (typeof raw.action_requested === 'string' && raw.action_requested.trim()) {
|
|
153
|
+
step.actionRequested = raw.action_requested.trim();
|
|
154
|
+
}
|
|
155
|
+
// Audit-only: a missing rationale must never cost the patient her net, so it is recorded, not required.
|
|
156
|
+
const why = (typeof raw.window_reasoning === 'string' ? raw.window_reasoning : '').trim();
|
|
157
|
+
if (why) step.windowReasoning = why;
|
|
158
|
+
return { step };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function isAdoptable(net, relatedCaseId, relatedClusterId) {
|
|
162
|
+
const plan = net?.carePlan;
|
|
163
|
+
if (!plan || isAgentArmed(net) || plan.status !== 'armed') return false;
|
|
164
|
+
if (relatedCaseId && plan.relatedCaseId === relatedCaseId) return true;
|
|
165
|
+
return Boolean(relatedClusterId && plan.relatedClusterId === relatedClusterId);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function handler(args = {}, context = {}) {
|
|
169
|
+
try {
|
|
170
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
171
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
172
|
+
return fail('setContingencyPlan requires an active turn context (turnId, patientCode).');
|
|
173
|
+
}
|
|
174
|
+
const action = str(args?.action).trim().toLowerCase() || 'arm';
|
|
175
|
+
if (!['arm', 'resolve', 'rearm'].includes(action)) {
|
|
176
|
+
return fail(`unknown action: '${action}'. Must be arm | resolve | rearm.`);
|
|
177
|
+
}
|
|
178
|
+
if (action === 'resolve') return await resolveNet(args, runtime);
|
|
179
|
+
|
|
180
|
+
const concern = str(args?.concern).trim();
|
|
181
|
+
const awaiting = str(args?.awaiting_characterization).trim();
|
|
182
|
+
const requestedResolvesOn = args?.resolves_on ?? RESOLVES_ON.REPLY;
|
|
183
|
+
const resolvesOn = typeof requestedResolvesOn === 'string'
|
|
184
|
+
? requestedResolvesOn.trim().toLowerCase() || RESOLVES_ON.REPLY
|
|
185
|
+
: requestedResolvesOn;
|
|
186
|
+
if (!Object.values(RESOLVES_ON).includes(resolvesOn)) {
|
|
187
|
+
return fail(`unknown resolves_on: ${JSON.stringify(args?.resolves_on)}. Must be ${Object.values(RESOLVES_ON).join(' | ')}.`);
|
|
188
|
+
}
|
|
189
|
+
const relatedCaseId = str(args?.related_case_id).trim() || null;
|
|
190
|
+
const relatedClusterId = str(args?.related_cluster_id).trim() || null;
|
|
191
|
+
|
|
192
|
+
const missing = [['concern', concern], ['awaiting_characterization', awaiting]]
|
|
193
|
+
.filter(([, v]) => !v).map(([n]) => n);
|
|
194
|
+
if (missing.length) return fail(`missing required field(s): ${missing.join(', ')}`);
|
|
195
|
+
if (!relatedCaseId && !relatedClusterId) {
|
|
196
|
+
return fail('at least one of related_case_id or related_cluster_id is required — a plan must link to a target');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const patientId = runtime.patientCode;
|
|
200
|
+
if (relatedCaseId) {
|
|
201
|
+
const targetCase = (await readSymptomCases({ patientId })).find((c) => c.condition.conditionId === relatedCaseId);
|
|
202
|
+
if (!targetCase) return fail('case_not_found_or_wrong_patient', { related_case_id: relatedCaseId });
|
|
203
|
+
if (!OPEN_STATUSES.includes(targetCase.condition.clinicalStatus)) {
|
|
204
|
+
return fail('target_not_open — contingency plans require an active case', { related_case_id: relatedCaseId, current_status: targetCase.condition.clinicalStatus });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (relatedClusterId) {
|
|
208
|
+
const targetCluster = (await readClusters({ patientId })).find((c) => c.clusterId === relatedClusterId);
|
|
209
|
+
if (!targetCluster) return fail('cluster_not_found_or_wrong_patient', { related_cluster_id: relatedClusterId });
|
|
210
|
+
if (targetCluster.status === 'dissolved') {
|
|
211
|
+
return fail('target_not_open — contingency plans require a non-dissolved cluster', { related_cluster_id: relatedClusterId, current_status: targetCluster.status });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const expiredNets = new Map();
|
|
216
|
+
const supersededNets = new Map();
|
|
217
|
+
const held = await readContingencies({ patientId });
|
|
218
|
+
const activeNets = held.filter((n) => isNetActive(n));
|
|
219
|
+
if (action === 'arm' && activeNets.some((n) => isAgentArmed(n))) {
|
|
220
|
+
const blocking = activeNets.find((n) => isAgentArmed(n));
|
|
221
|
+
const onCluster = blocking.carePlan.relatedCaseId == null && blocking.carePlan.relatedClusterId != null;
|
|
222
|
+
return fail(onCluster ? 'active_plan_already_exists_for_cluster' : 'active_plan_already_exists_for_case', {
|
|
223
|
+
existing_plan_id: blocking.carePlan.planId,
|
|
224
|
+
existing_status: blocking.carePlan.status,
|
|
225
|
+
existing_related_case_id: blocking.carePlan.relatedCaseId,
|
|
226
|
+
existing_related_cluster_id: blocking.carePlan.relatedClusterId,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
const adopted = activeNets.length === 1 && isAdoptable(activeNets[0], relatedCaseId, relatedClusterId)
|
|
230
|
+
? activeNets[0]
|
|
231
|
+
: null;
|
|
232
|
+
for (const n of activeNets) {
|
|
233
|
+
if (n !== adopted) supersededNets.set(n.carePlan.planId, n);
|
|
234
|
+
}
|
|
235
|
+
for (const n of held.filter((n) => isExpired(n))) expiredNets.set(n.carePlan.planId, n);
|
|
236
|
+
|
|
237
|
+
// Taken after the reads, so a slow read cannot eat into the silence; validation and createdAt share it.
|
|
238
|
+
const armedAt = new Date();
|
|
239
|
+
const built = buildStep(args?.patient_followup_reminder, 'patient_followup_reminder', armedAt);
|
|
240
|
+
if (built.error) return fail(built.error, built.data);
|
|
241
|
+
const reminder = built.step;
|
|
242
|
+
|
|
243
|
+
const now = armedAt.toISOString();
|
|
244
|
+
const planId = adopted ? adopted.carePlan.planId : `plan_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
245
|
+
const contingency = new ContingencySafetyNet({
|
|
246
|
+
carePlan: {
|
|
247
|
+
planId,
|
|
248
|
+
patientId,
|
|
249
|
+
relatedCaseId,
|
|
250
|
+
relatedClusterId,
|
|
251
|
+
concern,
|
|
252
|
+
awaitingCharacterization: awaiting,
|
|
253
|
+
resolvesOn,
|
|
254
|
+
createdAt: now,
|
|
255
|
+
expiresAt: computeExpiresAt(now, reminder.firesAfterSilenceMinutes),
|
|
256
|
+
},
|
|
257
|
+
patientReminder: reminder,
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const trace = runtime.trace || null;
|
|
261
|
+
stampContingencyPlan({
|
|
262
|
+
trace,
|
|
263
|
+
planId,
|
|
264
|
+
relatedCaseId,
|
|
265
|
+
relatedClusterId,
|
|
266
|
+
concern,
|
|
267
|
+
awaitingCharacterization: awaiting,
|
|
268
|
+
resolvesOn,
|
|
269
|
+
createdAt: now,
|
|
270
|
+
firesAfterSilenceMinutes: reminder.firesAfterSilenceMinutes,
|
|
271
|
+
windowReasoning: reminder.windowReasoning || null,
|
|
272
|
+
extra: { armedBy: 'agent', ...(adopted ? { adoptedFrom: adopted.carePlan.armedBy } : {}) },
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
const isLive = runtime.isLive?.bind(runtime);
|
|
276
|
+
if (isShadowRun()) {
|
|
277
|
+
logger.info('[setContingencyPlan] plan not stored — shadow run', { turnId: runtime.turnId, planId });
|
|
278
|
+
} else if (isLive && !isLive()) {
|
|
279
|
+
logger.info('[setContingencyPlan] plan not stored — turn superseded', { turnId: runtime.turnId, planId });
|
|
280
|
+
} else {
|
|
281
|
+
for (const expired of expiredNets.values()) {
|
|
282
|
+
await resolveContingency({ patientCode: patientId, net: expired, status: 'auto_resolved', resolvedReason: RESOLVED_REASONS.EXPIRED, trace, requireRowsDown: false });
|
|
283
|
+
}
|
|
284
|
+
if (adopted) {
|
|
285
|
+
if (!await armContingency({ contingency, patientCode: patientId, trace, isLive, actionType: 'update' })) {
|
|
286
|
+
return fail('dispatch_not_armed_retry_next_turn', { plan_id: planId });
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
await storeContingency({ patientId, contingency });
|
|
290
|
+
} catch (err) {
|
|
291
|
+
await armContingency({ contingency: adopted, patientCode: patientId, trace, isLive, actionType: 'update' });
|
|
292
|
+
logger.warn('[setContingencyPlan] adoption rolled back; the machine net keeps its row', { turnId: runtime.turnId, planId, error: err?.message });
|
|
293
|
+
return fail('store_failed_retry_next_turn', { plan_id: planId });
|
|
294
|
+
}
|
|
295
|
+
return JSON.stringify({ success: true, data: { plan_id: planId, adopted_from: adopted.carePlan.armedBy } });
|
|
296
|
+
}
|
|
297
|
+
await storeContingency({ patientId, contingency });
|
|
298
|
+
let armed = false;
|
|
299
|
+
try {
|
|
300
|
+
armed = await armContingency({ contingency, patientCode: patientId, trace, isLive });
|
|
301
|
+
} catch (err) {
|
|
302
|
+
logger.warn('[setContingencyPlan] dispatch rows not armed; the plan is stored', { turnId: runtime.turnId, planId, error: err?.message });
|
|
303
|
+
}
|
|
304
|
+
const rollBack = () => resolveContingency({ patientCode: patientId, net: contingency, status: 'auto_resolved', resolvedReason: RESOLVED_REASONS.NO_LONGER_RELEVANT, trace, requireRowsDown: armed });
|
|
305
|
+
if (!armed && supersededNets.size) {
|
|
306
|
+
await rollBack();
|
|
307
|
+
return fail('dispatch_not_armed_retry_next_turn', { plan_id: planId });
|
|
308
|
+
}
|
|
309
|
+
for (const superseded of supersededNets.values()) {
|
|
310
|
+
if (!await resolveContingency({ patientCode: patientId, net: superseded, resolvedReason: RESOLVED_REASONS.SUPERSEDED_BY_AGENT, trace })) {
|
|
311
|
+
await rollBack();
|
|
312
|
+
return fail('stand_down_failed_retry_next_turn', { plan_id: superseded.carePlan.planId });
|
|
313
|
+
}
|
|
314
|
+
recordResolution(runtime, {
|
|
315
|
+
planId: superseded.carePlan.planId,
|
|
316
|
+
action: 'rearm',
|
|
317
|
+
supersededBy: planId,
|
|
318
|
+
reasoning: `superseded — the replacement net guards: ${concern}`,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
const supersededIds = [...supersededNets.keys()];
|
|
323
|
+
return JSON.stringify({ success: true, data: { plan_id: planId, ...(supersededIds.length ? { superseded_plan_ids: supersededIds } : {}) } });
|
|
324
|
+
} catch (err) {
|
|
325
|
+
return fail(err?.message || 'setContingencyPlan failed');
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
module.exports = {
|
|
330
|
+
definition,
|
|
331
|
+
handler,
|
|
332
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
|
|
2
|
+
const { markSkillActivated } = require('../helpers/skillActivationHelper');
|
|
3
|
+
const { loadSkillBody } = require('../services/skillService');
|
|
4
|
+
|
|
5
|
+
const definition = {
|
|
6
|
+
name: 'Skill',
|
|
7
|
+
description: '**Does:** Activates an enabled skill by name and returns its `SKILL.md` body inline; the body then governs the rest of the turn.\n\n**Required inputs:** `skill` (enabled skill name, no leading slash, e.g. `emergency`), `args` (context string the skill body can interpret — pass `null` when there is no additional context).\n\n**When to call:** the turn matches a protocol the operator has enabled for this run (e.g. an emergency/red-flag turn) and you need its full body to proceed correctly.\n\n**When NOT to call:** the skill is not enabled for this run; a plain reply covers the turn without a protocol.\n\n**Returns:** `activated_skills[]` — `{name, version, body}`; read `body` and follow it verbatim. A skill already returned this turn (by `Skill` or inside another tool\'s `activated_skills`) returns `already_active` instead of the body again. A skill not enabled for this run returns the enabled skill names, and an unknown name returns the available skill names, in the error payload for self-correction. Read-only.',
|
|
8
|
+
strict: true,
|
|
9
|
+
replayScope: 'turn',
|
|
10
|
+
parameters: {
|
|
11
|
+
type: 'object',
|
|
12
|
+
properties: {
|
|
13
|
+
skill: {
|
|
14
|
+
type: 'string',
|
|
15
|
+
description: 'Name of the skill protocol to activate.',
|
|
16
|
+
},
|
|
17
|
+
args: {
|
|
18
|
+
type: ['string', 'null'],
|
|
19
|
+
description: 'Context string the skill body can interpret; `null` when there is no additional context. '
|
|
20
|
+
+ MEDICATION_NAMING_RULE,
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
required: ['skill', 'args'],
|
|
24
|
+
additionalProperties: false,
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
async function handler(args, context) {
|
|
29
|
+
try {
|
|
30
|
+
const name = typeof args?.skill === 'string' ? args.skill.trim() : '';
|
|
31
|
+
if (!name) {
|
|
32
|
+
return JSON.stringify({
|
|
33
|
+
success: false,
|
|
34
|
+
error: 'Skill requires `skill` (name of the skill to activate).',
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const enabledSkills = context?.toolRuntimeContext?.enabledSkills;
|
|
39
|
+
if (!Array.isArray(enabledSkills) || !enabledSkills.includes(name)) {
|
|
40
|
+
return JSON.stringify({
|
|
41
|
+
success: false,
|
|
42
|
+
error: `Skill '${name}' is not enabled for this run.`,
|
|
43
|
+
data: {
|
|
44
|
+
requested_skill: name,
|
|
45
|
+
enabled_skills: Array.isArray(enabledSkills) ? [...enabledSkills].sort() : [],
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const runtime = context?.toolRuntimeContext;
|
|
51
|
+
if (runtime?.activatedSkills?.has(name)) {
|
|
52
|
+
return JSON.stringify({
|
|
53
|
+
success: true,
|
|
54
|
+
data: { already_active: name, note: `The ${name} body was already returned to you in this turn; follow it from there.` },
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const { skill, availableSkills } = await loadSkillBody(name);
|
|
59
|
+
if (!skill) {
|
|
60
|
+
return JSON.stringify({
|
|
61
|
+
success: false,
|
|
62
|
+
error: `Skill '${name}' is not registered.`,
|
|
63
|
+
data: { requested_skill: name, available_skills: availableSkills },
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const fragment = { name: skill.name, version: skill.version, body: skill.body };
|
|
68
|
+
if (args?.args) fragment.args_received = args.args;
|
|
69
|
+
|
|
70
|
+
markSkillActivated(runtime, skill.name);
|
|
71
|
+
|
|
72
|
+
return JSON.stringify({ success: true, data: { activated_skills: [fragment] } });
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return JSON.stringify({ success: false, error: err?.message || 'Skill failed' });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = {
|
|
79
|
+
definition,
|
|
80
|
+
handler,
|
|
81
|
+
};
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
NutritionSafetyDecision,
|
|
5
|
+
FINDING_CODES,
|
|
6
|
+
FINDING_VALUES,
|
|
7
|
+
QUESTION_CODES,
|
|
8
|
+
EVIDENCE_SOURCE_TYPES,
|
|
9
|
+
DISPOSITIONS,
|
|
10
|
+
} = require('../../shared/dtos/NutritionSafetyDecision');
|
|
11
|
+
|
|
12
|
+
const definition = {
|
|
13
|
+
name: 'submitNutritionSafetyDecision',
|
|
14
|
+
description: '**Does:** Commits the typed warning-sign decision for the current nutrition-intake clarification turn. The active patient, trace, inbound message identity, submission revision, and screen revision are validated by Nexus and revalidated by the consumer repository. Call exactly once when this runtime tool is offered and forced.\n\n**Required inputs:** the reviewed submission and screen revisions; all four findings as yes/no/unknown; every unresolved question code; and a clear, clarify, escalate, or review_required disposition.\n\n**Side effects:** synchronously invokes the configured canonical nutrition-safety repository. It never writes consumer state directly.',
|
|
15
|
+
strict: true,
|
|
16
|
+
replayScope: 'turn',
|
|
17
|
+
parameters: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
additionalProperties: false,
|
|
20
|
+
properties: {
|
|
21
|
+
submission_revision: { type: 'integer', minimum: 1 },
|
|
22
|
+
screen_revision: { type: 'integer', minimum: 0 },
|
|
23
|
+
findings: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
additionalProperties: false,
|
|
26
|
+
properties: Object.fromEntries(FINDING_CODES.map(code => [code, { type: 'string', enum: FINDING_VALUES }])),
|
|
27
|
+
required: FINDING_CODES,
|
|
28
|
+
},
|
|
29
|
+
evidence_refs: {
|
|
30
|
+
type: 'array',
|
|
31
|
+
minItems: FINDING_CODES.length,
|
|
32
|
+
items: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
properties: {
|
|
36
|
+
finding: { type: 'string', enum: FINDING_CODES },
|
|
37
|
+
source_type: { type: 'string', enum: EVIDENCE_SOURCE_TYPES },
|
|
38
|
+
source_id: { type: 'string', minLength: 1 },
|
|
39
|
+
observed_at: { type: 'string', format: 'date-time' },
|
|
40
|
+
},
|
|
41
|
+
required: ['finding', 'source_type', 'source_id', 'observed_at'],
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
questions_needed: {
|
|
45
|
+
type: 'array',
|
|
46
|
+
maxItems: QUESTION_CODES.length,
|
|
47
|
+
uniqueItems: true,
|
|
48
|
+
items: { type: 'string', enum: QUESTION_CODES },
|
|
49
|
+
},
|
|
50
|
+
disposition: { type: 'string', enum: DISPOSITIONS },
|
|
51
|
+
},
|
|
52
|
+
required: ['submission_revision', 'screen_revision', 'findings', 'evidence_refs', 'questions_needed', 'disposition'],
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function fail(error, data = {}) {
|
|
57
|
+
return JSON.stringify({ success: false, error, data });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function activeIdentity(runtime) {
|
|
61
|
+
const trace = runtime?.trace;
|
|
62
|
+
const traceId = trace?._id ? String(trace._id) : null;
|
|
63
|
+
const sourceId = runtime?.patientInput?.sourceId;
|
|
64
|
+
const observedAt = runtime?.patientInput?.observedAt;
|
|
65
|
+
if (!runtime?.turnId || !runtime?.patientCode || runtime?.turnKind !== 'patient' || !traceId
|
|
66
|
+
|| String(trace.turnId) !== String(runtime.turnId)
|
|
67
|
+
|| String(trace.patientCode) !== String(runtime.patientCode)
|
|
68
|
+
|| typeof sourceId !== 'string' || !sourceId
|
|
69
|
+
|| typeof observedAt !== 'string' || Number.isNaN(new Date(observedAt).getTime())) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
patientCode: runtime.patientCode,
|
|
74
|
+
turnId: runtime.turnId,
|
|
75
|
+
traceId,
|
|
76
|
+
sourceId,
|
|
77
|
+
observedAt,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function safeCommitResult(result) {
|
|
82
|
+
const outcome = typeof result?.outcome === 'string' ? result.outcome : null;
|
|
83
|
+
const status = typeof result?.screen?.status === 'string'
|
|
84
|
+
? result.screen.status
|
|
85
|
+
: (typeof result?.status === 'string' ? result.status : null);
|
|
86
|
+
const requested = result?.questionsNeeded ?? result?.questions_needed ?? [];
|
|
87
|
+
const questionsNeeded = Array.isArray(requested)
|
|
88
|
+
? [...new Set(requested.filter(code => QUESTION_CODES.includes(code)))]
|
|
89
|
+
: [];
|
|
90
|
+
if (!outcome || !status) return null;
|
|
91
|
+
return { outcome, status, questions_needed: questionsNeeded };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sameInstant(first, second) {
|
|
95
|
+
return new Date(first).getTime() === new Date(second).getTime();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function validateEvidence(decision, runtime, identity) {
|
|
99
|
+
const trustedContext = runtime?.consumerMetadata?.nutritionSafety?.evidenceRefs;
|
|
100
|
+
const trustedReferences = Array.isArray(trustedContext) ? trustedContext : [];
|
|
101
|
+
|
|
102
|
+
const validated = decision.evidenceRefs.map((reference) => {
|
|
103
|
+
if (reference.sourceType === 'chat') {
|
|
104
|
+
if (reference.sourceId !== identity.sourceId
|
|
105
|
+
|| !sameInstant(reference.observedAt, identity.observedAt)) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return { ...reference, observedAt: identity.observedAt, traceId: identity.traceId };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const trusted = trustedReferences.find(candidate => (
|
|
112
|
+
candidate?.finding === reference.finding
|
|
113
|
+
&& candidate?.sourceType === reference.sourceType
|
|
114
|
+
&& candidate?.sourceId === reference.sourceId
|
|
115
|
+
&& typeof candidate?.observedAt === 'string'
|
|
116
|
+
&& (reference.sourceType === 'flow'
|
|
117
|
+
? candidate.observedAt === reference.observedAt
|
|
118
|
+
: sameInstant(candidate.observedAt, reference.observedAt))
|
|
119
|
+
));
|
|
120
|
+
if (!trusted) return null;
|
|
121
|
+
return {
|
|
122
|
+
...reference,
|
|
123
|
+
observedAt: trusted.observedAt,
|
|
124
|
+
...(typeof trusted.traceId === 'string' && trusted.traceId ? { traceId: trusted.traceId } : {}),
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
if (validated.some(reference => reference === null)) return null;
|
|
129
|
+
return validated;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function isRuntimeLive(runtime) {
|
|
133
|
+
if (typeof runtime?.isLive !== 'function') return false;
|
|
134
|
+
try {
|
|
135
|
+
return runtime.isLive() === true;
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function handler(args = {}, context = {}) {
|
|
142
|
+
const runtime = context?.toolRuntimeContext;
|
|
143
|
+
const identity = activeIdentity(runtime);
|
|
144
|
+
const commitDecision = runtime?.repos?.nutritionSafety?.commitDecision;
|
|
145
|
+
if (!identity || typeof commitDecision !== 'function') {
|
|
146
|
+
return fail('nutrition_safety_active_context_required');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let decision;
|
|
150
|
+
try {
|
|
151
|
+
decision = new NutritionSafetyDecision(args);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error instanceof ZodError) {
|
|
154
|
+
return fail('nutrition_safety_decision_invalid', {
|
|
155
|
+
issues: error.issues.slice(0, 20).map(issue => ({
|
|
156
|
+
path: issue.path.join('.'),
|
|
157
|
+
problem: issue.message,
|
|
158
|
+
})),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return fail('nutrition_safety_decision_invalid');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const evidenceRefs = validateEvidence(decision, runtime, identity);
|
|
165
|
+
if (!evidenceRefs) return fail('nutrition_safety_evidence_invalid');
|
|
166
|
+
decision.evidenceRefs = evidenceRefs;
|
|
167
|
+
|
|
168
|
+
if (!isRuntimeLive(runtime)) {
|
|
169
|
+
return fail('nutrition_safety_turn_inactive');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
const result = await commitDecision({ decision, ...identity });
|
|
174
|
+
const safeResult = safeCommitResult(result);
|
|
175
|
+
if (!safeResult) return fail('nutrition_safety_commit_result_invalid');
|
|
176
|
+
if (result?.deliveryDirective) {
|
|
177
|
+
if (typeof runtime?.setDeliveryDirective !== 'function') {
|
|
178
|
+
return fail('nutrition_safety_delivery_directive_unavailable');
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
runtime.setDeliveryDirective(result.deliveryDirective);
|
|
182
|
+
} catch {
|
|
183
|
+
return fail('nutrition_safety_delivery_directive_invalid');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
runtime.trace?.setSignals?.({
|
|
187
|
+
nutritionSafety: {
|
|
188
|
+
submissionRevision: decision.submissionRevision,
|
|
189
|
+
screenRevision: decision.screenRevision,
|
|
190
|
+
disposition: decision.disposition,
|
|
191
|
+
status: safeResult.status,
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
return JSON.stringify({ success: true, data: safeResult });
|
|
195
|
+
} catch {
|
|
196
|
+
return fail('nutrition_safety_commit_failed');
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
module.exports = { definition, handler };
|