@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,394 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
const { CARRIED_FORWARD, GRADE_CONFIDENCE_LEVELS, GRADE_MIN, GRADE_MAX, gradeEstimateSchema, parseGradeEstimate, projectGradeEstimate, projectGradeRead, hasGradeSignal, isCarriedForward, malformedGradeEstimate } = require('../helpers/gradeEstimateHelper');
|
|
4
|
+
const { ceilingGapError } = require('../helpers/ceilingGapHelper');
|
|
5
|
+
const { mentionProvenanceError } = require('../helpers/evidenceAnchorHelper');
|
|
6
|
+
const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
|
|
7
|
+
const { resolveCloseReason, closePatch, runCloseCascade } = require('../services/conditionCloseService');
|
|
8
|
+
const { gradeClaimError, gradeClaimNotice } = require('../services/gradeClaimService');
|
|
9
|
+
const { armOpenCeilingNet } = require('../services/contingencyDispatchService');
|
|
10
|
+
const { inputConsistency, statedReasoning } = require('../services/impressionValidationService');
|
|
11
|
+
const { isArmOnOpenCeilingLive } = require('../flags/contingencyFlags');
|
|
12
|
+
const { readSymptomCases, storeSymptomCase } = require('../../fhir');
|
|
13
|
+
const { ManagedSymptom, OPEN_STATUSES, FUNCTIONAL_ANCHORS } = require('../../shared/dtos/ManagedSymptom');
|
|
14
|
+
const { logger } = require('../../utils/logger');
|
|
15
|
+
|
|
16
|
+
const definition = {
|
|
17
|
+
name: 'recordClinicalImpression',
|
|
18
|
+
description: '**Does:** Evolves an existing symptom case by `event`. `add_evidence`: new mention on the current episode (requires `characterizing` + a grade or trajectory). `new_episode`: a new episode for the same `ctcae_term` — attaches it and returns the case to `characterizing`. `resolve_episode`: the current episode resolved — case goes to `monitoring`. `close`: terminal — status `closed`, requires `close_reason` from the closed vocabulary.\n\nAn impression is a grading act plus the reasoning behind it: `grade_estimate` carries your most likely grade with its confidence and range, and `reasoning` names, in one or two sentences, what you think is going on. `reasoning` is REQUIRED on every call and is the canonical per-case rationale — it lands on the clinical record, and the routing trace references it rather than restating it. Omitting it does not fail the write, but the impression is then a grade with no clinical reasoning behind it and the envelope says so in `input_consistency`. Grade-specific justification (the matched `grade_scale` clause) belongs inside `grade_estimate.reasoning`.\n\n**Required inputs:** `case_id` (from `openCondition` or `getActiveSymptomLandscape`), `event`, `reasoning`. Per-event: `add_evidence`/`new_episode` require `mention_id`, `missing_for_higher_grade`, plus at least one of `grade_estimate` or `trajectory_direction`; `new_episode` also requires `episode_id`; `close` requires `close_reason`, and it must be one of `resolved` | `team_resolved` | `resolved_spontaneously` | `resolved_by_intervention` (the symptom ENDED — this stamps `abatement_at`) or `escalated_to_team` | `patient_transferred` | `stale_no_activity` (stop tracking WITHOUT claiming an end — `abatement_at` stays null). Never claim a resolution nobody observed; free text is rejected.\n\n**Returns:** `case_id`, `action_taken`, `status`, `ctcae_term`, `episode_ids`, `current_episode_id`, `mention_ids`, `grade_estimate`, `temporality`, `trajectory`, `decision_posture`, `close_reason`, `abatement_at`, plus `input_consistency` when the call under-specified something, and `grade_notice` when the grade was recorded without the ADL limitation its clause mentions — advisory: the grade was stored as given. Fails hard on status guards (e.g. `add_evidence` on a non-`characterizing` case), duplicate `mention_id`, or an already-attached `episode_id`.\n\n**Side effects:** appends a FHIR `ClinicalImpression` to the case chain and repoints the head; updates the `Condition` lifecycle. `close` also retires any contingency net guarding the case (returned as `auto_resolved_contingency_plans`) — a closed case never keeps writing to the patient — and prunes the case from its active clusters, dissolving one that drops below 2 members (`pruned_clusters`, `dissolved_clusters`).',
|
|
19
|
+
strict: false,
|
|
20
|
+
parameters: {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
case_id: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'The case_id returned by openCondition (or from getActiveSymptomLandscape.active_cases[].case_id).',
|
|
26
|
+
},
|
|
27
|
+
event: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
enum: ['add_evidence', 'new_episode', 'resolve_episode', 'close'],
|
|
30
|
+
description: '`add_evidence`: more info on the current episode. `new_episode`: a new episode for the same term. `resolve_episode`: current episode resolved (case → monitoring). `close`: terminal (requires close_reason).',
|
|
31
|
+
},
|
|
32
|
+
mention_id: {
|
|
33
|
+
type: 'string',
|
|
34
|
+
description: 'The intake mention id this impression rests on. Required for add_evidence and new_episode; optional audit trace for resolve_episode. Normally a mention `extractClinicalInfo` produced this turn. When the turn extracted nothing new — a clarifying reply, or a plain \'sigue igual\' — re-cite a mention already on the case, which the landscape lists as `mention_ids`, and declare `grade_estimate.source: \'carried_forward\'`: a re-cited mention whose read has not moved is rejected as a duplicate without it. Never invent one.',
|
|
35
|
+
},
|
|
36
|
+
episode_id: {
|
|
37
|
+
type: 'string',
|
|
38
|
+
description: 'The new intake episode id. Required for new_episode.',
|
|
39
|
+
},
|
|
40
|
+
grade_estimate: gradeEstimateSchema('The graded severity read for this impression. At least one of grade_estimate or trajectory_direction is required for add_evidence and new_episode.'),
|
|
41
|
+
trajectory_direction: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
enum: ['improving', 'stable', 'worsening', 'unknown'],
|
|
44
|
+
description: 'Per-turn direction vs the prior impression.',
|
|
45
|
+
},
|
|
46
|
+
missing_for_higher_grade: {
|
|
47
|
+
type: 'string',
|
|
48
|
+
description: 'REQUIRED on add_evidence and new_episode. The one thing you would need to know to rule out a grade above your best estimate, read against this term\'s grade_scale — a value, a functional limit, whether something got worse overnight. Write it as the patient could answer it, e.g. \'si la fiebre pasó de 38.5\' or \'si puede caminar sin ayuda\'. Write \'none\' only when the ladder is already settled by what the patient told you and no further answer could move the grade up.',
|
|
49
|
+
},
|
|
50
|
+
check_in_question: {
|
|
51
|
+
type: 'string',
|
|
52
|
+
description: 'REQUIRED on add_evidence and new_episode whenever missing_for_higher_grade is not \'none\'. The same datum, rewritten as the question the patient would be asked if they go quiet — their words, their language, one question, no clinical jargon and no acronyms. \'si la fiebre pasó de 38.5\' becomes \'¿te has vuelto a tomar la temperatura? ¿pasó de 38.5?\'. This one is sent over WhatsApp, so write it for the patient, not for the record.',
|
|
53
|
+
},
|
|
54
|
+
decision_posture: {
|
|
55
|
+
type: 'string',
|
|
56
|
+
enum: ['probe_for_discriminators', 'gather_more_evidence', 'commit_to_grade'],
|
|
57
|
+
description: 'Optional. Clinical posture for this impression.',
|
|
58
|
+
},
|
|
59
|
+
close_reason: {
|
|
60
|
+
type: 'string',
|
|
61
|
+
description: 'Required for event=close. Why the case is being closed.',
|
|
62
|
+
},
|
|
63
|
+
temporality: {
|
|
64
|
+
type: 'string',
|
|
65
|
+
description: 'Optional. Pass only when temporality changed since the last impression.',
|
|
66
|
+
},
|
|
67
|
+
reasoning: {
|
|
68
|
+
type: 'string',
|
|
69
|
+
description: 'REQUIRED. 1-2 sentences of general clinical rationale for this impression, in Spanish. This is the canonical per-case rationale and it lands on the clinical record; the routing trace references it rather than restating it. Grade-specific justification (the matched grade_scale clause) belongs in grade_estimate.reasoning. '
|
|
70
|
+
+ MEDICATION_NAMING_RULE,
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
required: ['case_id', 'event', 'reasoning'],
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const EVENTS = definition.parameters.properties.event.enum;
|
|
78
|
+
const TRAJECTORIES = definition.parameters.properties.trajectory_direction.enum;
|
|
79
|
+
const POSTURES = definition.parameters.properties.decision_posture.enum;
|
|
80
|
+
|
|
81
|
+
// Only new_episode starts a fresh episode; every other event acts on the one the case holds.
|
|
82
|
+
const normalisedEvent = (args) => (typeof args?.event === 'string' ? args.event : '').trim().toLowerCase();
|
|
83
|
+
|
|
84
|
+
const uid = (prefix) => `${prefix}_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
85
|
+
|
|
86
|
+
function coerceGrade(raw, base, continuesEpisode = false) {
|
|
87
|
+
const malformed = malformedGradeEstimate(raw);
|
|
88
|
+
if (malformed) return { error: malformed };
|
|
89
|
+
if (isCarriedForward(raw)) {
|
|
90
|
+
const parsed = parseGradeEstimate(raw);
|
|
91
|
+
if (parsed?.error) return parsed;
|
|
92
|
+
return { ...base, source: CARRIED_FORWARD };
|
|
93
|
+
}
|
|
94
|
+
if (!hasGradeSignal(raw)) return base;
|
|
95
|
+
const parsed = parseGradeEstimate(raw);
|
|
96
|
+
if (parsed?.error) return parsed;
|
|
97
|
+
// The anchor records the case's functional state, not whether this turn re-asked. An unchanged
|
|
98
|
+
// grade keeps the anchor already established, so the finding survives more than one quiet turn.
|
|
99
|
+
const holdsGrade = parsed.bestEstimate === base?.bestEstimate;
|
|
100
|
+
const notReasked = parsed.functionalAnchor === null || parsed.functionalAnchor === 'not_established';
|
|
101
|
+
if (continuesEpisode && holdsGrade && notReasked && base?.functionalAnchor) {
|
|
102
|
+
parsed.functionalAnchor = base.functionalAnchor;
|
|
103
|
+
} else if (parsed.functionalAnchor === null && holdsGrade) {
|
|
104
|
+
parsed.functionalAnchor = base?.functionalAnchor ?? null;
|
|
105
|
+
}
|
|
106
|
+
return parsed;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const statesTrajectory = (args) => args?.trajectory_direction !== null && args?.trajectory_direction !== undefined;
|
|
110
|
+
|
|
111
|
+
const ONGOING_READ_EVENTS = ['add_evidence', 'new_episode'];
|
|
112
|
+
|
|
113
|
+
function buildAssessment(condition, previous, args, runtime, restatesPriorEvidence = false) {
|
|
114
|
+
const continuesEpisode = normalisedEvent(args) !== 'new_episode';
|
|
115
|
+
const grade = coerceGrade(args?.grade_estimate, previous.grade, continuesEpisode);
|
|
116
|
+
if (grade?.error) return grade;
|
|
117
|
+
if (hasGradeSignal(args?.grade_estimate)) {
|
|
118
|
+
const claimGap = gradeClaimError({
|
|
119
|
+
ctcaeTerm: condition.ctcaeTerm,
|
|
120
|
+
grade,
|
|
121
|
+
stated: parseGradeEstimate(args.grade_estimate),
|
|
122
|
+
previous: previous.grade,
|
|
123
|
+
restatesPriorEvidence,
|
|
124
|
+
recordsOngoingRead: ONGOING_READ_EVENTS.includes(normalisedEvent(args)),
|
|
125
|
+
trace: runtime?.trace || null,
|
|
126
|
+
});
|
|
127
|
+
if (claimGap) return { error: claimGap };
|
|
128
|
+
}
|
|
129
|
+
const trajectory = typeof args?.trajectory_direction === 'string' ? args.trajectory_direction : null;
|
|
130
|
+
if (statesTrajectory(args) && !TRAJECTORIES.includes(trajectory)) return { error: 'invalid_trajectory_direction' };
|
|
131
|
+
const decisionPosture = typeof args?.decision_posture === 'string' ? args.decision_posture : null;
|
|
132
|
+
if (decisionPosture !== null && !POSTURES.includes(decisionPosture)) return { error: 'invalid_decision_posture' };
|
|
133
|
+
const reasoning = statedReasoning(args);
|
|
134
|
+
return {
|
|
135
|
+
assessmentId: uid('assessment'),
|
|
136
|
+
conditionId: condition.conditionId,
|
|
137
|
+
patientId: condition.patientId,
|
|
138
|
+
performedAt: new Date().toISOString(),
|
|
139
|
+
previousId: previous.assessmentId,
|
|
140
|
+
grade,
|
|
141
|
+
trajectory,
|
|
142
|
+
decisionPosture,
|
|
143
|
+
reasoning,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function toManaged(existing, conditionPatch, newAssessment) {
|
|
148
|
+
const condition = { ...existing.condition, ...conditionPatch };
|
|
149
|
+
const priorAssessments = [existing.latestAssessment, ...existing.priorAssessments];
|
|
150
|
+
return new ManagedSymptom({
|
|
151
|
+
condition,
|
|
152
|
+
latestAssessment: newAssessment || existing.latestAssessment,
|
|
153
|
+
priorAssessments: newAssessment ? priorAssessments : existing.priorAssessments,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function fail(error, data = {}) {
|
|
158
|
+
return JSON.stringify({ success: false, error, data });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function failAssessment(error, caseId, extra = {}) {
|
|
162
|
+
const allowed = {
|
|
163
|
+
grade_out_of_range: { allowed_range: [GRADE_MIN, GRADE_MAX] },
|
|
164
|
+
invalid_grade_confidence: { allowed: GRADE_CONFIDENCE_LEVELS },
|
|
165
|
+
invalid_functional_anchor: { allowed: FUNCTIONAL_ANCHORS },
|
|
166
|
+
invalid_trajectory_direction: { allowed: TRAJECTORIES },
|
|
167
|
+
invalid_decision_posture: { allowed: POSTURES },
|
|
168
|
+
}[error] || {};
|
|
169
|
+
return fail(error, { case_id: caseId, ...allowed, ...extra });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function requireCeilingGap(args, event) {
|
|
173
|
+
const error = ceilingGapError(args, event);
|
|
174
|
+
return error ? fail(error) : null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function sameGradeAndAnchor(a, b) {
|
|
178
|
+
return !!a && !!b && a.bestEstimate === b.bestEstimate && a.functionalAnchor === b.functionalAnchor;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function sameGrade(a, b) {
|
|
182
|
+
return JSON.stringify(projectGradeRead(a)) === JSON.stringify(projectGradeRead(b));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function movesTheRead(previous, next) {
|
|
186
|
+
if (!sameGrade(previous?.grade, next.grade)) return true;
|
|
187
|
+
if (next.trajectory !== null && next.trajectory !== (previous?.trajectory ?? null)) return true;
|
|
188
|
+
return next.decisionPosture !== null && next.decisionPosture !== (previous?.decisionPosture ?? null);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function applyAddEvidence(existing, args, runtime) {
|
|
192
|
+
if (existing.condition.clinicalStatus !== 'characterizing') {
|
|
193
|
+
return fail('add_evidence requires status=characterizing. If status=monitoring, call new_episode; if closed, open a new case.', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus });
|
|
194
|
+
}
|
|
195
|
+
const ceilingGap = requireCeilingGap(args, 'add_evidence');
|
|
196
|
+
if (ceilingGap) return ceilingGap;
|
|
197
|
+
const mentionId = (typeof args?.mention_id === 'string' ? args.mention_id : '').trim();
|
|
198
|
+
if (!mentionId) return fail('mention_id is required for add_evidence');
|
|
199
|
+
const alreadyOnCase = existing.condition.evidenceMentionIds.includes(mentionId);
|
|
200
|
+
const provenance = mentionProvenanceError(mentionId, { trace: runtime?.trace || null, knownMentionIds: existing.condition.evidenceMentionIds });
|
|
201
|
+
if (provenance) return fail(provenance, { case_id: existing.condition.conditionId, mention_id: mentionId });
|
|
202
|
+
const duplicate = () => fail('mention_already_recorded_on_case', { case_id: existing.condition.conditionId, mention_id: mentionId });
|
|
203
|
+
const carriesForward = isCarriedForward(args?.grade_estimate);
|
|
204
|
+
if (!hasGradeSignal(args?.grade_estimate) && !args?.trajectory_direction && !carriesForward) {
|
|
205
|
+
if (alreadyOnCase) return duplicate();
|
|
206
|
+
return fail('add_evidence requires at least one of `grade_estimate` or `trajectory_direction`.', { case_id: existing.condition.conditionId });
|
|
207
|
+
}
|
|
208
|
+
const assessment = buildAssessment(existing.condition, existing.latestAssessment, args, runtime, alreadyOnCase);
|
|
209
|
+
if (assessment.error) return failAssessment(assessment.error, existing.condition.conditionId);
|
|
210
|
+
if (alreadyOnCase && !carriesForward && !movesTheRead(existing.latestAssessment, assessment)) return duplicate();
|
|
211
|
+
const patch = alreadyOnCase ? {} : { evidenceMentionIds: [...existing.condition.evidenceMentionIds, mentionId] };
|
|
212
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
213
|
+
return toManaged(existing, patch, assessment);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function applyNewEpisode(existing, args, runtime) {
|
|
217
|
+
if (!OPEN_STATUSES.includes(existing.condition.clinicalStatus)) {
|
|
218
|
+
return fail('new_episode requires an open case (characterizing or monitoring).', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus });
|
|
219
|
+
}
|
|
220
|
+
const ceilingGap = requireCeilingGap(args, 'new_episode');
|
|
221
|
+
if (ceilingGap) return ceilingGap;
|
|
222
|
+
const episodeId = (typeof args?.episode_id === 'string' ? args.episode_id : '').trim();
|
|
223
|
+
const mentionId = (typeof args?.mention_id === 'string' ? args.mention_id : '').trim();
|
|
224
|
+
if (!episodeId || !mentionId) return fail('new_episode requires both episode_id and mention_id');
|
|
225
|
+
const provenance = mentionProvenanceError(mentionId, { trace: runtime?.trace || null, knownMentionIds: existing.condition.evidenceMentionIds });
|
|
226
|
+
if (provenance) return fail(provenance, { case_id: existing.condition.conditionId, mention_id: mentionId });
|
|
227
|
+
if (existing.condition.evidenceEpisodeIds.includes(episodeId)) {
|
|
228
|
+
return fail('episode_already_attached_to_case', { case_id: existing.condition.conditionId, episode_id: episodeId, current_episode_id: existing.condition.currentEpisodeId });
|
|
229
|
+
}
|
|
230
|
+
if (!hasGradeSignal(args?.grade_estimate) && !args?.trajectory_direction) {
|
|
231
|
+
return fail('new_episode requires at least one of `grade_estimate` or `trajectory_direction`.', { case_id: existing.condition.conditionId, episode_id: episodeId });
|
|
232
|
+
}
|
|
233
|
+
const assessment = buildAssessment(existing.condition, existing.latestAssessment, args, runtime);
|
|
234
|
+
if (assessment.error) return failAssessment(assessment.error, existing.condition.conditionId, { episode_id: episodeId });
|
|
235
|
+
const mentions = [...existing.condition.evidenceMentionIds];
|
|
236
|
+
if (!mentions.includes(mentionId)) mentions.push(mentionId);
|
|
237
|
+
const patch = {
|
|
238
|
+
evidenceEpisodeIds: [...existing.condition.evidenceEpisodeIds, episodeId],
|
|
239
|
+
currentEpisodeId: episodeId,
|
|
240
|
+
evidenceMentionIds: mentions,
|
|
241
|
+
clinicalStatus: 'characterizing',
|
|
242
|
+
};
|
|
243
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
244
|
+
return toManaged(existing, patch, assessment);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function closingAssessment(existing, args, runtime, restatesPriorEvidence) {
|
|
248
|
+
const malformed = malformedGradeEstimate(args?.grade_estimate);
|
|
249
|
+
if (malformed) return { error: malformed };
|
|
250
|
+
if (!hasGradeSignal(args?.grade_estimate) && !statesTrajectory(args)) return null;
|
|
251
|
+
return buildAssessment(existing.condition, existing.latestAssessment, args, runtime, restatesPriorEvidence);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function applyResolveEpisode(existing, args, runtime) {
|
|
255
|
+
if (existing.condition.clinicalStatus !== 'characterizing') {
|
|
256
|
+
return fail('resolve_episode requires status=characterizing (there must be an active episode to resolve).', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus });
|
|
257
|
+
}
|
|
258
|
+
const patch = { clinicalStatus: 'monitoring', currentEpisodeId: null };
|
|
259
|
+
const mentionId = (typeof args?.mention_id === 'string' ? args.mention_id : '').trim();
|
|
260
|
+
const restatesPriorEvidence = !mentionId || existing.condition.evidenceMentionIds.includes(mentionId);
|
|
261
|
+
if (mentionId && !existing.condition.evidenceMentionIds.includes(mentionId)) {
|
|
262
|
+
const provenance = mentionProvenanceError(mentionId, {
|
|
263
|
+
trace: runtime?.trace || null, knownMentionIds: existing.condition.evidenceMentionIds,
|
|
264
|
+
});
|
|
265
|
+
if (provenance) return fail(provenance, { case_id: existing.condition.conditionId, mention_id: mentionId });
|
|
266
|
+
patch.evidenceMentionIds = [...existing.condition.evidenceMentionIds, mentionId];
|
|
267
|
+
}
|
|
268
|
+
if (typeof args?.temporality === 'string') patch.temporality = args.temporality;
|
|
269
|
+
const reasoning = (typeof args?.reasoning === 'string' ? args.reasoning : '').trim();
|
|
270
|
+
if (reasoning) patch.lastTransitionReason = reasoning;
|
|
271
|
+
const assessment = closingAssessment(existing, args, runtime, restatesPriorEvidence);
|
|
272
|
+
if (assessment?.error) return failAssessment(assessment.error, existing.condition.conditionId);
|
|
273
|
+
return toManaged(existing, patch, assessment);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function applyClose(existing, args, runtime) {
|
|
277
|
+
if (!OPEN_STATUSES.includes(existing.condition.clinicalStatus)) {
|
|
278
|
+
return fail('case_already_terminal', { case_id: existing.condition.conditionId, status: existing.condition.clinicalStatus, abatement_at: existing.condition.abatementAt, close_reason: existing.condition.closeReason });
|
|
279
|
+
}
|
|
280
|
+
const close = resolveCloseReason(args?.close_reason, { caseId: existing.condition.conditionId });
|
|
281
|
+
if (close.error) return fail(close.error.error, close.error.data);
|
|
282
|
+
const reasoning = (typeof args?.reasoning === 'string' ? args.reasoning : '').trim();
|
|
283
|
+
const patch = closePatch({ closeReason: close.closeReason, resolving: close.resolving, reasoning });
|
|
284
|
+
const assessment = closingAssessment(existing, args, runtime, true);
|
|
285
|
+
if (assessment?.error) return failAssessment(assessment.error, existing.condition.conditionId);
|
|
286
|
+
return toManaged(existing, patch, assessment);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const HANDLERS = {
|
|
290
|
+
add_evidence: applyAddEvidence,
|
|
291
|
+
new_episode: applyNewEpisode,
|
|
292
|
+
resolve_episode: applyResolveEpisode,
|
|
293
|
+
close: applyClose,
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
async function handler(args = {}, context = {}) {
|
|
297
|
+
try {
|
|
298
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
299
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
300
|
+
return JSON.stringify({ success: false, error: 'recordClinicalImpression requires an active turn context (turnId, patientCode).', data: {} });
|
|
301
|
+
}
|
|
302
|
+
const caseId = (typeof args?.case_id === 'string' ? args.case_id : '').trim();
|
|
303
|
+
const event = normalisedEvent(args);
|
|
304
|
+
if (!caseId) return fail('case_id is required');
|
|
305
|
+
if (!EVENTS.includes(event)) {
|
|
306
|
+
return fail(`unknown event: '${event}'. Must be one of ${EVENTS.join(' | ')}.`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const patientId = runtime.patientCode;
|
|
310
|
+
const cases = await readSymptomCases({ patientId });
|
|
311
|
+
const existing = cases.find((symptomCase) => symptomCase.condition.conditionId === caseId);
|
|
312
|
+
if (!existing) return fail('case_not_found_or_wrong_patient', { case_id: caseId });
|
|
313
|
+
|
|
314
|
+
const result = HANDLERS[event](existing, args, runtime);
|
|
315
|
+
if (typeof result === 'string') return result;
|
|
316
|
+
|
|
317
|
+
await storeSymptomCase({ patientId, managedSymptom: result });
|
|
318
|
+
|
|
319
|
+
const autoResolvedPlans = [];
|
|
320
|
+
const prunedClusters = [];
|
|
321
|
+
const dissolvedClusters = [];
|
|
322
|
+
if (event === 'close') {
|
|
323
|
+
try {
|
|
324
|
+
const cascade = await runCloseCascade(patientId, caseId, runtime.turnId, runtime.trace || null, 'recordClinicalImpression', {
|
|
325
|
+
closeReason: result.condition.closeReason,
|
|
326
|
+
});
|
|
327
|
+
autoResolvedPlans.push(...cascade.autoResolvedPlans);
|
|
328
|
+
prunedClusters.push(...cascade.prunedClusters);
|
|
329
|
+
dissolvedClusters.push(...cascade.dissolvedClusters);
|
|
330
|
+
for (const failure of cascade.cascadeErrors) {
|
|
331
|
+
logger.warn('[recordClinicalImpression] close cascade incomplete', { caseId, error: failure });
|
|
332
|
+
}
|
|
333
|
+
} catch (error) {
|
|
334
|
+
// The close already succeeded, so failing the tool here would only invite a useless retry.
|
|
335
|
+
logger.warn('[recordClinicalImpression] contingency cascade failed on close', { caseId, error: error?.message });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (['add_evidence', 'new_episode'].includes(event) && isArmOnOpenCeilingLive() && OPEN_STATUSES.includes(result.condition.clinicalStatus)) {
|
|
340
|
+
try {
|
|
341
|
+
const net = await armOpenCeilingNet({
|
|
342
|
+
patientCode: patientId,
|
|
343
|
+
caseId: result.condition.conditionId,
|
|
344
|
+
symptom: result.condition.ctcaeTerm,
|
|
345
|
+
missing: args?.missing_for_higher_grade,
|
|
346
|
+
checkIn: args?.check_in_question,
|
|
347
|
+
grade: result.latestAssessment?.grade?.bestEstimate ?? null,
|
|
348
|
+
trace: runtime.trace || null,
|
|
349
|
+
isLive: runtime.isLive?.bind(runtime),
|
|
350
|
+
});
|
|
351
|
+
logger.info('[recordClinicalImpression] open-ceiling net', { turnId: runtime.turnId, caseId, ...net });
|
|
352
|
+
} catch (netErr) {
|
|
353
|
+
logger.error('[recordClinicalImpression] open-ceiling net not armed', { turnId: runtime.turnId, caseId, error: netErr?.message });
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const { condition, latestAssessment } = result;
|
|
358
|
+
const consistency = inputConsistency(args);
|
|
359
|
+
// A hold of the same grade on the same anchor was already advised; repeating it re-asks the patient every turn.
|
|
360
|
+
const heldAsAdvised = event === 'add_evidence' && sameGradeAndAnchor(existing.latestAssessment?.grade, latestAssessment.grade);
|
|
361
|
+
const freshRead = ONGOING_READ_EVENTS.includes(event) && hasGradeSignal(args?.grade_estimate) && !isCarriedForward(args.grade_estimate) && !heldAsAdvised;
|
|
362
|
+
const gradeNotice = freshRead ? gradeClaimNotice({ ctcaeTerm: condition.ctcaeTerm, grade: latestAssessment.grade }) : null;
|
|
363
|
+
return JSON.stringify({
|
|
364
|
+
success: true,
|
|
365
|
+
data: {
|
|
366
|
+
case_id: condition.conditionId,
|
|
367
|
+
...(autoResolvedPlans.length ? { auto_resolved_contingency_plans: autoResolvedPlans } : {}),
|
|
368
|
+
...(prunedClusters.length ? { pruned_clusters: prunedClusters } : {}),
|
|
369
|
+
...(dissolvedClusters.length ? { dissolved_clusters: dissolvedClusters } : {}),
|
|
370
|
+
action_taken: event,
|
|
371
|
+
status: condition.clinicalStatus,
|
|
372
|
+
ctcae_term: condition.ctcaeTerm,
|
|
373
|
+
episode_ids: [...condition.evidenceEpisodeIds],
|
|
374
|
+
current_episode_id: condition.currentEpisodeId,
|
|
375
|
+
mention_ids: [...condition.evidenceMentionIds],
|
|
376
|
+
grade_estimate: projectGradeEstimate(latestAssessment.grade),
|
|
377
|
+
temporality: condition.temporality,
|
|
378
|
+
trajectory: { direction: latestAssessment.trajectory || 'unknown' },
|
|
379
|
+
decision_posture: latestAssessment.decisionPosture,
|
|
380
|
+
close_reason: condition.closeReason,
|
|
381
|
+
abatement_at: condition.abatementAt,
|
|
382
|
+
...(consistency.length ? { input_consistency: consistency } : {}),
|
|
383
|
+
...(gradeNotice ? { grade_notice: gradeNotice } : {}),
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
} catch (err) {
|
|
387
|
+
return JSON.stringify({ success: false, error: err?.message || 'recordClinicalImpression failed', data: {} });
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
module.exports = {
|
|
392
|
+
definition,
|
|
393
|
+
handler,
|
|
394
|
+
};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
const { readSymptomCases, readInterventions, storeIntervention } = require('../../fhir');
|
|
4
|
+
const { Intervention, KINDS, OUTCOMES } = require('../../shared/dtos/Intervention');
|
|
5
|
+
const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
6
|
+
|
|
7
|
+
const ACTIONS = ['create', 'record_outcome'];
|
|
8
|
+
|
|
9
|
+
const definition = {
|
|
10
|
+
name: 'recordIntervention',
|
|
11
|
+
description: '**Does:** Records an agent-delivered intervention against an open symptom case (`action:\'create\'`) or patches the outcome of one already recorded (`action:\'record_outcome\'`). One intervention = one clinical action (OTC advice, self-care, education, a team escalation task, or a follow-up check).\n\n**Create inputs:** `case_id` (an OPEN case from `openCondition`/`getActiveSymptomLandscape`), `intervention_label`, `intervention_kind` (`otc` | `self_care` | `other` | `education` | `team_escalation` | `follow_up_check`); optional `rationale`. Fails hard with `case_not_found_or_wrong_patient` or `case_is_dormant` (recover via `updateConditionStatus(transition=\'reactivate\')`), or `invalid intervention_kind`.\n\n**Outcome inputs (`action:\'record_outcome\'`):** `intervention_id` (the handle create returned), `outcome` (`pending` | `improved` | `no_relief` | `side_effects` | `worsened` | `unknown`); optional `outcome_notes`. Single-write: fails with `outcome_already_recorded` if the outcome is already non-pending.\n\n**Record vs actuate — this tool only WRITES A RECORD.** `intervention_kind=\'team_escalation\'` dispatches nothing: escalate with `reportMedicalEscalation` FIRST, then record it here. `intervention_kind=\'follow_up_check\'` schedules nothing: schedule with `schedulePatientReminder` FIRST, then record it here. **Recording an escalation is not escalating** — a `success` here never means anyone was notified.\n\n**When to call:** create when you deliver an intervention; record_outcome once the patient reports how it went.\n\n**Returns:** create → `{intervention_id, delivered_at}`; record_outcome → `{intervention_id, outcome}`.\n\n**Side effects:** writes a FHIR Procedure/Communication/Task/CommunicationRequest (per kind) + Provenance.',
|
|
12
|
+
strict: false,
|
|
13
|
+
parameters: {
|
|
14
|
+
type: 'object',
|
|
15
|
+
properties: {
|
|
16
|
+
action: {
|
|
17
|
+
type: 'string',
|
|
18
|
+
enum: ACTIONS,
|
|
19
|
+
description: '`create` (default) records a new intervention; `record_outcome` patches an existing one\'s outcome. When omitted, presence of `intervention_id` implies `record_outcome`.',
|
|
20
|
+
},
|
|
21
|
+
case_id: {
|
|
22
|
+
type: 'string',
|
|
23
|
+
description: 'create: the OPEN case_id this intervention attaches to.',
|
|
24
|
+
},
|
|
25
|
+
intervention_label: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'create: short human label for the intervention.',
|
|
28
|
+
},
|
|
29
|
+
intervention_kind: {
|
|
30
|
+
type: 'string',
|
|
31
|
+
enum: KINDS,
|
|
32
|
+
description: 'create: `otc`, `self_care`, `other`, `education`, `team_escalation`, or `follow_up_check`.',
|
|
33
|
+
},
|
|
34
|
+
rationale: {
|
|
35
|
+
type: 'string',
|
|
36
|
+
description: 'create: optional clinical rationale for the intervention.',
|
|
37
|
+
},
|
|
38
|
+
intervention_id: {
|
|
39
|
+
type: 'string',
|
|
40
|
+
description: 'record_outcome: the handle returned when the intervention was created.',
|
|
41
|
+
},
|
|
42
|
+
outcome: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
enum: OUTCOMES,
|
|
45
|
+
description: 'record_outcome: `pending`, `improved`, `no_relief`, `side_effects`, `worsened`, or `unknown`.',
|
|
46
|
+
},
|
|
47
|
+
outcome_notes: {
|
|
48
|
+
type: 'string',
|
|
49
|
+
description: 'record_outcome: optional free-text notes on the outcome.',
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
required: [],
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function fail(error, data = {}) {
|
|
57
|
+
return JSON.stringify({ success: false, error, data });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function recordOutcome(patientId, interventionId, args) {
|
|
61
|
+
const outcome = (typeof args?.outcome === 'string' ? args.outcome : '').trim().toLowerCase();
|
|
62
|
+
if (!OUTCOMES.includes(outcome)) {
|
|
63
|
+
return fail(`invalid outcome: '${outcome}'. Must be one of ${OUTCOMES.join(' | ')}.`, { outcome });
|
|
64
|
+
}
|
|
65
|
+
const existing = (await readInterventions({ patientId })).find((i) => i.interventionId === interventionId);
|
|
66
|
+
if (!existing) return fail('intervention_not_found_or_wrong_patient', { intervention_id: interventionId });
|
|
67
|
+
if (existing.outcome && existing.outcome !== 'pending') {
|
|
68
|
+
return fail('outcome_already_recorded', { intervention_id: interventionId, outcome: existing.outcome });
|
|
69
|
+
}
|
|
70
|
+
const outcomeNotes = typeof args?.outcome_notes === 'string' ? (args.outcome_notes.trim() || null) : null;
|
|
71
|
+
const patched = new Intervention({ ...existing, outcome, outcomeNotes });
|
|
72
|
+
await storeIntervention({ patientId, intervention: patched });
|
|
73
|
+
return JSON.stringify({ success: true, data: { intervention_id: patched.interventionId, outcome: patched.outcome } });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function create(patientId, args) {
|
|
77
|
+
const caseId = (typeof args?.case_id === 'string' ? args.case_id : '').trim();
|
|
78
|
+
const label = (typeof args?.intervention_label === 'string' ? args.intervention_label : '').trim();
|
|
79
|
+
const kind = (typeof args?.intervention_kind === 'string' ? args.intervention_kind : '').trim().toLowerCase();
|
|
80
|
+
const rationale = typeof args?.rationale === 'string' ? (args.rationale.trim() || null) : null;
|
|
81
|
+
|
|
82
|
+
const missing = [['case_id', caseId], ['intervention_label', label], ['intervention_kind', kind]]
|
|
83
|
+
.filter(([, v]) => !v).map(([n]) => n);
|
|
84
|
+
if (missing.length) return fail(`missing required field(s): ${missing.join(', ')}`);
|
|
85
|
+
if (!KINDS.includes(kind)) return fail(`invalid intervention_kind: '${kind}'. Must be one of ${KINDS.join(' | ')}.`, { intervention_kind: kind });
|
|
86
|
+
|
|
87
|
+
const targetCase = (await readSymptomCases({ patientId })).find((c) => c.condition.conditionId === caseId);
|
|
88
|
+
if (!targetCase) return fail('case_not_found_or_wrong_patient', { case_id: caseId });
|
|
89
|
+
if (!OPEN_STATUSES.includes(targetCase.condition.clinicalStatus)) {
|
|
90
|
+
return fail('case_is_dormant — interventions attach to open cases; if the symptom recurred, reactivate the case with updateConditionStatus(transition=\'reactivate\') first.', { case_id: caseId, status: targetCase.condition.clinicalStatus });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const deliveredAt = new Date().toISOString();
|
|
94
|
+
const intervention = new Intervention({
|
|
95
|
+
kind,
|
|
96
|
+
interventionId: `intv_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`,
|
|
97
|
+
patientId,
|
|
98
|
+
caseId,
|
|
99
|
+
interventionLabel: label,
|
|
100
|
+
rationale,
|
|
101
|
+
deliveredAt,
|
|
102
|
+
});
|
|
103
|
+
await storeIntervention({ patientId, intervention });
|
|
104
|
+
return JSON.stringify({ success: true, data: { intervention_id: intervention.interventionId, delivered_at: deliveredAt } });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function handler(args = {}, context = {}) {
|
|
108
|
+
try {
|
|
109
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
110
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
111
|
+
return fail('recordIntervention requires an active turn context (turnId, patientCode).');
|
|
112
|
+
}
|
|
113
|
+
const patientId = runtime.patientCode;
|
|
114
|
+
const interventionId = (typeof args?.intervention_id === 'string' ? args.intervention_id : '').trim();
|
|
115
|
+
const action = (typeof args?.action === 'string' ? args.action : '').trim().toLowerCase();
|
|
116
|
+
if (action && !ACTIONS.includes(action)) {
|
|
117
|
+
return fail(`invalid action: '${action}'. Must be one of ${ACTIONS.join(' | ')}.`);
|
|
118
|
+
}
|
|
119
|
+
if (action === 'record_outcome' && !interventionId) {
|
|
120
|
+
return fail('action=record_outcome requires `intervention_id`.');
|
|
121
|
+
}
|
|
122
|
+
if (action === 'create' && interventionId) {
|
|
123
|
+
return fail('action=create must NOT carry `intervention_id` — use action=record_outcome to patch an outcome.', { intervention_id: interventionId });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (action === 'record_outcome' || (!action && interventionId)) {
|
|
127
|
+
return await recordOutcome(patientId, interventionId, args);
|
|
128
|
+
}
|
|
129
|
+
return await create(patientId, args);
|
|
130
|
+
} catch (err) {
|
|
131
|
+
return fail(err?.message || 'recordIntervention failed');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
module.exports = {
|
|
136
|
+
definition,
|
|
137
|
+
handler,
|
|
138
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const { recordRecommendationOutcome } = require('../../fhir');
|
|
2
|
+
|
|
3
|
+
const NO_MATCH_HINT = 'No active recommendation matched — there may be no current care plan, or none targeting that symptom. Handle the symptom normally (open a case / route).';
|
|
4
|
+
|
|
5
|
+
const definition = {
|
|
6
|
+
name: 'recordRecommendationOutcome',
|
|
7
|
+
description: '**Does:** Records how a symptom-management recommendation went for the patient — appended to the recommendation\'s history so the next plan can adapt. Feeds the SAME outcome loop as the weekly-triage feedback form.\n\n**Required inputs:** one of `recommendation_id` (preferred — from getActiveRecommendations) or `ctcae_term` (fallback; resolves the active recommendation for that symptom), plus at least one of `outcome` (`improved`|`partial`|`no_relief`|`worsened`|`not_tried`|`unknown`) or `adherence` (`full`|`partial`|`none`) — an adherence-only report defaults `outcome` to `unknown`. Optional `notes`.\n\n**Returns:** `recorded` (bool). When true: `recommendation_id`, `outcome`, optional `adherence`. When false: `hint` (no active recommendation matched).',
|
|
8
|
+
strict: false,
|
|
9
|
+
parameters: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
recommendation_id: {
|
|
13
|
+
type: 'string',
|
|
14
|
+
description: 'The recommendation to attach the outcome to (from getActiveRecommendations). Preferred over ctcae_term.',
|
|
15
|
+
},
|
|
16
|
+
ctcae_term: {
|
|
17
|
+
type: 'string',
|
|
18
|
+
description: 'Fallback when recommendation_id is unknown: the PRO-CTCAE symptom whose active recommendation the outcome is about.',
|
|
19
|
+
},
|
|
20
|
+
outcome: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: ['improved', 'partial', 'no_relief', 'worsened', 'not_tried', 'unknown'],
|
|
23
|
+
description: 'How the recommendation went.',
|
|
24
|
+
},
|
|
25
|
+
adherence: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
enum: ['full', 'partial', 'none'],
|
|
28
|
+
description: 'Whether the patient followed it (distinct axis from outcome).',
|
|
29
|
+
},
|
|
30
|
+
notes: { type: 'string', description: 'Optional free-text detail from the patient.' },
|
|
31
|
+
},
|
|
32
|
+
required: [],
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
async function handler(args = {}, context = {}) {
|
|
37
|
+
try {
|
|
38
|
+
const runtime = context?.toolRuntimeContext || null;
|
|
39
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
40
|
+
return JSON.stringify({ success: false, error: 'recordRecommendationOutcome requires an active turn context (turnId, patientCode).', data: {} });
|
|
41
|
+
}
|
|
42
|
+
const recommendationId = typeof args?.recommendation_id === 'string' ? args.recommendation_id.trim() || null : null;
|
|
43
|
+
const ctcaeTerm = typeof args?.ctcae_term === 'string' ? args.ctcae_term.trim() || null : null;
|
|
44
|
+
if (!recommendationId && !ctcaeTerm) {
|
|
45
|
+
return JSON.stringify({ success: false, error: 'provide recommendation_id or ctcae_term.', data: {} });
|
|
46
|
+
}
|
|
47
|
+
const outcome = typeof args?.outcome === 'string' ? args.outcome.trim().toLowerCase() || null : null;
|
|
48
|
+
const adherence = typeof args?.adherence === 'string' ? args.adherence.trim().toLowerCase() || null : null;
|
|
49
|
+
if (!outcome && !adherence) {
|
|
50
|
+
return JSON.stringify({ success: false, error: 'provide outcome or adherence — nothing to record.', data: {} });
|
|
51
|
+
}
|
|
52
|
+
const result = await recordRecommendationOutcome({
|
|
53
|
+
patientId: runtime.patientCode,
|
|
54
|
+
recommendationId,
|
|
55
|
+
ctcaeTerm,
|
|
56
|
+
outcome,
|
|
57
|
+
adherence,
|
|
58
|
+
notes: typeof args?.notes === 'string' ? args.notes.trim() || null : null,
|
|
59
|
+
});
|
|
60
|
+
if (!result.recorded) {
|
|
61
|
+
return JSON.stringify({ success: true, data: { recorded: false, hint: NO_MATCH_HINT } });
|
|
62
|
+
}
|
|
63
|
+
return JSON.stringify({ success: true, data: result });
|
|
64
|
+
} catch (err) {
|
|
65
|
+
return JSON.stringify({ success: false, error: err?.message || 'recordRecommendationOutcome failed', data: {} });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
definition,
|
|
71
|
+
handler,
|
|
72
|
+
};
|