@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.
Files changed (438) hide show
  1. package/README.md +104 -0
  2. package/lib/adapters/BaileysProvider.js +8 -37
  3. package/lib/adapters/MessageAdapter.js +3 -1
  4. package/lib/adapters/MessageProvider.js +0 -11
  5. package/lib/adapters/TwilioProvider.js +44 -77
  6. package/lib/clinical/AssistantProcessor.js +414 -19
  7. package/lib/clinical/assistants/BaseAssistant.js +0 -15
  8. package/lib/clinical/config/checkInConfig.js +3 -0
  9. package/lib/clinical/config/cohortConfig.js +3 -3
  10. package/lib/clinical/config/composerConfig.js +42 -0
  11. package/lib/clinical/config/divergenceConfig.js +80 -50
  12. package/lib/clinical/config/llmConfig.js +11 -2
  13. package/lib/clinical/config/safetyNetConfig.js +108 -0
  14. package/lib/clinical/config/subAgentsConfig.js +61 -2
  15. package/lib/clinical/context/ToolRuntimeContext.js +121 -6
  16. package/lib/clinical/context/turnContext.js +50 -0
  17. package/lib/clinical/flags/bridgeConfig.js +31 -0
  18. package/lib/clinical/flags/clinicalContextFlags.js +46 -0
  19. package/lib/clinical/flags/composerFlags.js +14 -0
  20. package/lib/clinical/flags/contingencyFlags.js +19 -0
  21. package/lib/clinical/flags/escalationFlags.js +43 -0
  22. package/lib/clinical/flags/flagSnapshot.js +58 -0
  23. package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
  24. package/lib/clinical/flags/llmAuditConfig.js +7 -0
  25. package/lib/clinical/flags/llmMonitorConfig.js +18 -0
  26. package/lib/clinical/flags/patternConsultFlags.js +10 -0
  27. package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
  28. package/lib/clinical/flags/supportLightFlags.js +7 -0
  29. package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
  30. package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
  31. package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
  32. package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
  33. package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
  34. package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
  35. package/lib/clinical/helpers/chemoContextHelper.js +217 -0
  36. package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
  37. package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
  38. package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
  39. package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
  40. package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
  41. package/lib/clinical/helpers/cohortHelper.js +3 -1
  42. package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
  43. package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
  44. package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
  45. package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
  46. package/lib/clinical/helpers/encodedPairHelper.js +12 -0
  47. package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
  48. package/lib/clinical/helpers/factAssertionHelper.js +300 -0
  49. package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
  50. package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
  51. package/lib/clinical/helpers/legacyContextHelper.js +122 -0
  52. package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
  53. package/lib/clinical/helpers/llmsHelper.js +170 -87
  54. package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
  55. package/lib/clinical/helpers/medicationNamingRule.js +5 -0
  56. package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
  57. package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
  58. package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
  59. package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
  60. package/lib/clinical/helpers/resultsHelper.js +56 -0
  61. package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
  62. package/lib/clinical/helpers/shadowHelper.js +1 -13
  63. package/lib/clinical/helpers/skillActivationHelper.js +53 -0
  64. package/lib/clinical/helpers/structuredTextHelper.js +13 -0
  65. package/lib/clinical/helpers/toolResultHelper.js +35 -0
  66. package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
  67. package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
  68. package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
  69. package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
  70. package/lib/clinical/index.js +4 -0
  71. package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
  72. package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
  73. package/lib/clinical/models/llmCallModel.js +19 -0
  74. package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
  75. package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
  76. package/lib/clinical/models/patternConsultModel.js +37 -0
  77. package/lib/clinical/models/riskWarmupEventModel.js +23 -0
  78. package/lib/clinical/models/supportCandidateModel.js +90 -0
  79. package/lib/clinical/models/supportLightModel.js +95 -0
  80. package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
  81. package/lib/clinical/models/turnTraceModel.js +24 -7
  82. package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
  83. package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
  84. package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
  85. package/lib/clinical/promptPlacement.js +5 -0
  86. package/lib/clinical/protocols/treatmentFormulary.js +387 -0
  87. package/lib/clinical/providers/AnthropicProvider.js +459 -31
  88. package/lib/clinical/providers/BaseLLMProvider.js +689 -52
  89. package/lib/clinical/providers/GatewayProvider.js +14 -4
  90. package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
  91. package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
  92. package/lib/clinical/providers/OpenRouterProvider.js +9 -2
  93. package/lib/clinical/services/assistantService.js +51 -7
  94. package/lib/clinical/services/bridgeService.js +93 -0
  95. package/lib/clinical/services/checkInDueService.js +134 -0
  96. package/lib/clinical/services/clinicalAirtableService.js +752 -0
  97. package/lib/clinical/services/clinicalContextReadService.js +47 -0
  98. package/lib/clinical/services/clinicalExtractionService.js +156 -23
  99. package/lib/clinical/services/composerService.js +78 -0
  100. package/lib/clinical/services/conceptVerifierService.js +127 -0
  101. package/lib/clinical/services/conditionCloseService.js +138 -0
  102. package/lib/clinical/services/contextCleanupService.js +85 -0
  103. package/lib/clinical/services/contextMirrorService.js +72 -0
  104. package/lib/clinical/services/contextSyncRunner.js +20 -0
  105. package/lib/clinical/services/contextSyncService.js +258 -0
  106. package/lib/clinical/services/contingencyDispatchService.js +496 -0
  107. package/lib/clinical/services/ctcaeLadderService.js +70 -0
  108. package/lib/clinical/services/ctcaeTermService.js +44 -0
  109. package/lib/clinical/services/currentRegimenService.js +60 -0
  110. package/lib/clinical/services/deliverySettlementService.js +39 -0
  111. package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
  112. package/lib/clinical/services/dispatcherService.js +142 -0
  113. package/lib/clinical/services/escalationDraftService.js +229 -0
  114. package/lib/clinical/services/escalationNoteFactsService.js +131 -0
  115. package/lib/clinical/services/escalationQuestionsService.js +131 -0
  116. package/lib/clinical/services/gradeAnchorService.js +85 -0
  117. package/lib/clinical/services/gradeClaimService.js +73 -0
  118. package/lib/clinical/services/gradeSourceService.js +138 -0
  119. package/lib/clinical/services/impressionValidationService.js +19 -0
  120. package/lib/clinical/services/legacyContextSyncService.js +255 -0
  121. package/lib/clinical/services/llmAuditService.js +23 -0
  122. package/lib/clinical/services/nutritionPlanService.js +97 -0
  123. package/lib/clinical/services/outreachCarrierService.js +88 -0
  124. package/lib/clinical/services/outreachSweepRunner.js +8 -0
  125. package/lib/clinical/services/outreachSweepService.js +644 -0
  126. package/lib/clinical/services/patientHistoryService.js +203 -0
  127. package/lib/clinical/services/patientIdentityService.js +43 -0
  128. package/lib/clinical/services/patientProfileService.js +145 -0
  129. package/lib/clinical/services/patternConsultService.js +127 -0
  130. package/lib/clinical/services/pausedSafetyNetService.js +387 -0
  131. package/lib/clinical/services/promptComposerService.js +74 -21
  132. package/lib/clinical/services/radiotherapyContextService.js +40 -0
  133. package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
  134. package/lib/clinical/services/recommendationRankService.js +180 -0
  135. package/lib/clinical/services/recommendationRecoveryService.js +241 -0
  136. package/lib/clinical/services/recommendationValidationService.js +206 -0
  137. package/lib/clinical/services/regimenCloserService.js +205 -0
  138. package/lib/clinical/services/reminderDispatchService.js +36 -0
  139. package/lib/clinical/services/riskAssessmentService.js +469 -0
  140. package/lib/clinical/services/riskHeadlineService.js +56 -0
  141. package/lib/clinical/services/safetyNetPledgeService.js +231 -0
  142. package/lib/clinical/services/shadowMessageService.js +30 -12
  143. package/lib/clinical/services/shadowService.js +8 -4
  144. package/lib/clinical/services/skillService.js +117 -0
  145. package/lib/clinical/services/supportActionService.js +122 -0
  146. package/lib/clinical/services/supportCandidateService.js +607 -0
  147. package/lib/clinical/services/supportInvitability.js +86 -0
  148. package/lib/clinical/services/supportLightEvaluationService.js +231 -0
  149. package/lib/clinical/services/supportLightService.js +277 -0
  150. package/lib/clinical/services/supportRoutingAgentService.js +118 -0
  151. package/lib/clinical/services/symptomLandscapeService.js +153 -0
  152. package/lib/clinical/services/treatmentProposalService.js +136 -0
  153. package/lib/clinical/services/triageRecommendationService.js +1226 -0
  154. package/lib/clinical/services/turnRiskBriefService.js +217 -0
  155. package/lib/clinical/services/writeClaimStore.js +126 -0
  156. package/lib/clinical/stores/CtcaeCatalog.js +21 -0
  157. package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
  158. package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
  159. package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
  160. package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
  161. package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
  162. package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
  163. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
  164. package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
  165. package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
  166. package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
  167. package/lib/clinical/tools/openConditionTool.js +198 -0
  168. package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
  169. package/lib/clinical/tools/recordInterventionTool.js +138 -0
  170. package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
  171. package/lib/clinical/tools/registerClinicalTools.js +51 -6
  172. package/lib/clinical/tools/reportCrisisTool.js +193 -0
  173. package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
  174. package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
  175. package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
  176. package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
  177. package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
  178. package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
  179. package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
  180. package/lib/clinical/tools/skillTool.js +81 -0
  181. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
  182. package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
  183. package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
  184. package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
  185. package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
  186. package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
  187. package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
  188. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
  189. package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
  190. package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
  191. package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
  192. package/lib/config/airtableArchiveConfig.js +177 -0
  193. package/lib/config/airtableConfig.js +24 -1
  194. package/lib/config/instructionConfig.js +5 -0
  195. package/lib/config/lifecycle.js +36 -1
  196. package/lib/config/programConfig.js +20 -0
  197. package/lib/controllers/assistantController.js +67 -11
  198. package/lib/controllers/contextSyncController.js +30 -0
  199. package/lib/controllers/contingencyController.js +28 -0
  200. package/lib/controllers/conversationController.js +7 -7
  201. package/lib/controllers/dashboardController.js +7 -4
  202. package/lib/controllers/escalationReviewController.js +299 -0
  203. package/lib/controllers/healthController.js +16 -0
  204. package/lib/controllers/interactionController.js +1 -1
  205. package/lib/controllers/messageController.js +67 -19
  206. package/lib/controllers/officeAssistantController.js +57 -0
  207. package/lib/controllers/patientController.js +216 -48
  208. package/lib/controllers/prescriptionController.js +10 -3
  209. package/lib/controllers/templateController.js +8 -17
  210. package/lib/controllers/traceController.js +26 -0
  211. package/lib/controllers/triageRecommendationController.js +41 -0
  212. package/lib/controllers/uploadController.js +2 -2
  213. package/lib/core/BatchingManager.js +146 -11
  214. package/lib/core/DeferredWorkRunner.js +257 -0
  215. package/lib/core/MessageParser.js +2 -2
  216. package/lib/core/NexusMessaging.js +948 -146
  217. package/lib/core/PhiProcessor.js +198 -17
  218. package/lib/core/ProcessingPipeline.js +49 -4
  219. package/lib/core/interactiveRouteService.js +64 -0
  220. package/lib/core/runtimeToolPolicy.js +3 -0
  221. package/lib/eval/EvalProvider.js +72 -25
  222. package/lib/fhir/config/catalogConfig.js +9 -14
  223. package/lib/fhir/config/fhirConfig.js +16 -12
  224. package/lib/fhir/constants/escalationCaseStatus.js +31 -0
  225. package/lib/fhir/constants/extensionSlugs.js +195 -0
  226. package/lib/fhir/constants/gradeMethods.js +12 -0
  227. package/lib/fhir/constants/projectionSlugs.js +69 -1
  228. package/lib/fhir/constants/severityPriority.js +8 -0
  229. package/lib/fhir/constants/variableRegistry.js +60 -0
  230. package/lib/fhir/helpers/compositeHelper.js +65 -12
  231. package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
  232. package/lib/fhir/helpers/elementHelper.js +39 -0
  233. package/lib/fhir/helpers/fhirHelper.js +4 -1
  234. package/lib/fhir/helpers/fhirReadHelper.js +62 -0
  235. package/lib/fhir/helpers/recommendationIds.js +44 -0
  236. package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
  237. package/lib/fhir/helpers/resourceHelper.js +46 -0
  238. package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
  239. package/lib/fhir/helpers/termMatchHelper.js +42 -0
  240. package/lib/fhir/helpers/terminologyHelper.js +92 -5
  241. package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
  242. package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
  243. package/lib/fhir/index.js +75 -0
  244. package/lib/fhir/models/envelopeModel.js +22 -0
  245. package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
  246. package/lib/fhir/projections/clusterProjection.js +124 -0
  247. package/lib/fhir/projections/contextFactProjection.js +380 -0
  248. package/lib/fhir/projections/contingencyProjection.js +224 -0
  249. package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
  250. package/lib/fhir/projections/interventionProjection.js +245 -0
  251. package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
  252. package/lib/fhir/projections/palliativeProjection.js +175 -0
  253. package/lib/fhir/projections/proctcaeProjection.js +62 -15
  254. package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
  255. package/lib/fhir/projections/registerProjectors.js +10 -2
  256. package/lib/fhir/projections/reminderProjection.js +20 -0
  257. package/lib/fhir/projections/riskProjection.js +16 -0
  258. package/lib/fhir/projections/routingProjection.js +285 -0
  259. package/lib/fhir/projections/safetyGateProjection.js +42 -0
  260. package/lib/fhir/projections/symptomCaseProjection.js +324 -0
  261. package/lib/fhir/resources/CommunicationRequest.js +91 -0
  262. package/lib/fhir/resources/Condition.js +2 -24
  263. package/lib/fhir/resources/Encounter.js +30 -0
  264. package/lib/fhir/resources/Observation.js +22 -69
  265. package/lib/fhir/resources/Patient.js +57 -6
  266. package/lib/fhir/resources/Provenance.js +48 -12
  267. package/lib/fhir/resources/RiskAssessment.js +184 -0
  268. package/lib/fhir/resources/Task.js +102 -0
  269. package/lib/fhir/services/clinicalContextService.js +161 -0
  270. package/lib/fhir/services/clinicalMentionService.js +3 -5
  271. package/lib/fhir/services/clusterService.js +30 -0
  272. package/lib/fhir/services/contingencyService.js +47 -0
  273. package/lib/fhir/services/encounterService.js +16 -0
  274. package/lib/fhir/services/escalationService.js +85 -0
  275. package/lib/fhir/services/fhirService.js +20 -0
  276. package/lib/fhir/services/interventionService.js +50 -0
  277. package/lib/fhir/services/palliativeService.js +74 -0
  278. package/lib/fhir/services/patientService.js +41 -0
  279. package/lib/fhir/services/recommendationService.js +336 -0
  280. package/lib/fhir/services/resultObservationService.js +53 -0
  281. package/lib/fhir/services/riskService.js +202 -0
  282. package/lib/fhir/services/routingService.js +86 -0
  283. package/lib/fhir/services/snapshotService.js +18 -3
  284. package/lib/fhir/services/symptomCaseService.js +33 -0
  285. package/lib/fhir/services/terminologyService.js +16 -21
  286. package/lib/fhir/services/triageService.js +8 -4
  287. package/lib/fhir/stores/fhirStore.js +42 -19
  288. package/lib/fhir/utils/normalizeUtils.js +12 -0
  289. package/lib/helpers/airtableArchiveHelper.js +51 -0
  290. package/lib/helpers/airtableFormulaHelper.js +25 -0
  291. package/lib/helpers/caregiverHelper.js +136 -0
  292. package/lib/helpers/channelErrorHelper.js +31 -0
  293. package/lib/helpers/channelRetryHelper.js +156 -0
  294. package/lib/helpers/conversationWindowHelper.js +2 -2
  295. package/lib/helpers/deliveryAttemptHelper.js +14 -2
  296. package/lib/helpers/filesHelper.js +3 -3
  297. package/lib/helpers/healthHelper.js +40 -0
  298. package/lib/helpers/messageHelper.js +16 -6
  299. package/lib/helpers/messageStatusHelper.js +16 -22
  300. package/lib/helpers/metaSignatureHelper.js +6 -6
  301. package/lib/helpers/nerHelper.js +24 -0
  302. package/lib/helpers/outboundAllowlistHelper.js +51 -0
  303. package/lib/helpers/patientInformationHelper.js +20 -16
  304. package/lib/helpers/patientMessageHelper.js +79 -0
  305. package/lib/helpers/patientTaskRulesHelper.js +57 -0
  306. package/lib/helpers/pausedThreadHelper.js +37 -0
  307. package/lib/helpers/processHelper.js +47 -16
  308. package/lib/helpers/sendClaimHelper.js +126 -0
  309. package/lib/helpers/staffSendHelper.js +4 -0
  310. package/lib/helpers/templateFlowControllerHelper.js +1 -1
  311. package/lib/helpers/templateRecoveryHelper.js +66 -8
  312. package/lib/helpers/triageRecordHelper.js +124 -0
  313. package/lib/helpers/twilioHelper.js +7 -79
  314. package/lib/helpers/twilioMediaHelper.js +1 -1
  315. package/lib/helpers/whatsappHelper.js +3 -1
  316. package/lib/index.d.ts +844 -34
  317. package/lib/index.js +169 -11
  318. package/lib/jobs/ScheduledMessageJob.js +44 -0
  319. package/lib/jobs/TemplateApprovalJob.js +200 -33
  320. package/lib/models/agendaMessageModel.js +5 -0
  321. package/lib/models/airtableArchiveModel.js +225 -0
  322. package/lib/models/contactGateDecisionModel.js +27 -0
  323. package/lib/models/contextSyncStateModel.js +26 -0
  324. package/lib/models/deferredWorkModel.js +24 -0
  325. package/lib/models/deliveryAttemptModel.js +5 -1
  326. package/lib/models/escalationReviewModel.js +341 -0
  327. package/lib/models/flowRoutingModel.js +1 -1
  328. package/lib/models/messageModel.js +21 -1
  329. package/lib/models/patientProfileModel.js +24 -0
  330. package/lib/models/safetyNetPledgeModel.js +31 -0
  331. package/lib/models/sendClaimModel.js +18 -0
  332. package/lib/models/templateModel.js +1 -2
  333. package/lib/models/threadModel.js +7 -0
  334. package/lib/models/tokenMapModel.js +2 -1
  335. package/lib/models/writeClaimModel.js +14 -0
  336. package/lib/observability/telemetry.js +7 -7
  337. package/lib/providers/NerClient.js +2 -2
  338. package/lib/queue/QueueAdapter.js +1 -0
  339. package/lib/queue/RedisQueueAdapter.js +104 -7
  340. package/lib/routes/index.js +132 -2
  341. package/lib/services/airtableArchivePlanService.js +197 -0
  342. package/lib/services/airtableArchiveReadService.js +48 -0
  343. package/lib/services/airtableArchiveService.js +561 -0
  344. package/lib/services/airtableMirrorService.js +223 -0
  345. package/lib/services/airtableService.js +198 -18
  346. package/lib/services/assistantMessageService.js +140 -0
  347. package/lib/services/carePlanHistoryService.js +610 -0
  348. package/lib/services/characterizationOutcomeService.js +294 -0
  349. package/lib/services/contactGateService.js +178 -0
  350. package/lib/services/conversationService.js +66 -20
  351. package/lib/services/dashboard-provider-registry.js +38 -0
  352. package/lib/services/dashboardService.js +31 -4
  353. package/lib/services/escalationCaseTaskService.js +134 -0
  354. package/lib/services/escalationContextService.js +92 -0
  355. package/lib/services/escalationReviewService.js +2214 -0
  356. package/lib/services/flowDataExchangeService.js +1 -1
  357. package/lib/services/globalEntityService.js +1 -1
  358. package/lib/services/gravePendingService.js +41 -0
  359. package/lib/services/healthService.js +252 -0
  360. package/lib/services/heldMessageService.js +141 -0
  361. package/lib/services/inboundRecoveryService.js +354 -0
  362. package/lib/services/instructionInFlightService.js +17 -0
  363. package/lib/services/officeAssistantService.js +217 -0
  364. package/lib/services/orbisService.js +44 -0
  365. package/lib/services/patientClinicalStatusService.js +189 -0
  366. package/lib/services/patientResourceService.js +24 -0
  367. package/lib/services/patientService.js +28 -16
  368. package/lib/services/patientTaskService.js +221 -0
  369. package/lib/services/patientTaskSummaryService.js +93 -0
  370. package/lib/services/physicianService.js +31 -0
  371. package/lib/services/preprocessingService.js +18 -6
  372. package/lib/services/queueReconciliationService.js +161 -0
  373. package/lib/services/recommendationCarouselService.js +398 -0
  374. package/lib/services/reviewAlertSweepService.js +99 -0
  375. package/lib/services/reviewBoardService.js +75 -0
  376. package/lib/services/reviewDeadlineService.js +116 -0
  377. package/lib/services/reviewDraftSweepService.js +85 -0
  378. package/lib/services/teamAlertService.js +140 -0
  379. package/lib/services/templateService.js +1 -2
  380. package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
  381. package/lib/services/tokenMapService.js +119 -22
  382. package/lib/services/toolRegistryService.js +43 -2
  383. package/lib/services/triageHistoryService.js +128 -0
  384. package/lib/services/twilioMediaService.js +79 -0
  385. package/lib/services/undeliverableService.js +36 -0
  386. package/lib/services/untakenAlertService.js +210 -0
  387. package/lib/shared/dtos/ClinicalAssertion.js +21 -0
  388. package/lib/shared/dtos/ClinicalMention.js +4 -0
  389. package/lib/shared/dtos/ClusterImpression.js +16 -5
  390. package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
  391. package/lib/shared/dtos/DispatchedEscalation.js +4 -8
  392. package/lib/shared/dtos/GradedSymptom.js +2 -0
  393. package/lib/shared/dtos/Intervention.js +10 -3
  394. package/lib/shared/dtos/ManagedSymptom.js +40 -11
  395. package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
  396. package/lib/shared/dtos/PalliativeAssessment.js +62 -0
  397. package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
  398. package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
  399. package/lib/shared/dtos/RecommendationPlan.js +102 -0
  400. package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
  401. package/lib/shared/dtos/Reminder.js +2 -2
  402. package/lib/shared/dtos/RoutingDecision.js +2 -1
  403. package/lib/shared/dtos/SupportAction.js +28 -0
  404. package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
  405. package/lib/shared/dtos/TriageCompletion.js +50 -0
  406. package/lib/shared/dtos/TriageResponse.js +7 -1
  407. package/lib/storage/MongoStorage.js +10 -1
  408. package/lib/templates/predefinedTemplates.js +1 -1
  409. package/lib/templates/templateStructure.js +15 -2
  410. package/lib/utils/MapCache.js +1 -1
  411. package/lib/utils/coercionUtils.js +11 -0
  412. package/lib/utils/concurrencyUtils.js +13 -0
  413. package/lib/utils/dateUtils.js +114 -6
  414. package/lib/utils/errorUtils.js +26 -1
  415. package/lib/utils/formatUtils.js +43 -37
  416. package/lib/utils/httpErrorUtils.js +9 -0
  417. package/lib/utils/intervalSweeper.js +75 -0
  418. package/lib/utils/jsonUtils.js +51 -0
  419. package/lib/utils/logger.js +8 -6
  420. package/lib/utils/paginationUtils.js +30 -0
  421. package/lib/utils/retryUtils.js +9 -1
  422. package/lib/utils/sanitizerUtils.js +87 -1
  423. package/lib/utils/scheduleUtils.js +70 -1
  424. package/lib/utils/shadowScope.js +13 -0
  425. package/lib/utils/statsUtils.js +21 -0
  426. package/lib/utils/textMatchUtils.js +76 -0
  427. package/lib/utils/timeoutUtils.js +16 -0
  428. package/lib/utils/tokenMapUtils.js +3 -3
  429. package/package.json +11 -11
  430. package/lib/clinical/helpers/divergenceHelper.js +0 -100
  431. package/lib/clinical/models/divergenceModel.js +0 -41
  432. package/lib/clinical/services/clinicalAgentService.js +0 -18
  433. package/lib/clinical/services/divergenceService.js +0 -90
  434. package/lib/core/workflowRunner.js +0 -35
  435. package/lib/fhir/resources/Appointment.js +0 -28
  436. package/lib/fhir/resources/MedicationStatement.js +0 -42
  437. package/lib/fhir/resources/Procedure.js +0 -30
  438. package/lib/services/twilioService.js +0 -13
@@ -0,0 +1,466 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ const { clinicalIntakeRequiresRisk, hasAlternateTerminalCommit, validateRoutingPrerequisites } = require('../helpers/clinicalWorkflowGuard');
4
+ const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
5
+ const { attachRequiredSkill } = require('../helpers/skillActivationHelper');
6
+ const { isResolutionReason } = require('../services/conditionCloseService');
7
+ const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
8
+ const { CLOSED_STATUSES } = require('../../shared/dtos/ManagedSymptom');
9
+ const { RoutingDecision } = require('../../shared/dtos/RoutingDecision');
10
+ const { foldAccents } = require('../../utils/formatUtils');
11
+ const { logger } = require('../../utils/logger');
12
+
13
+ const _ROUTING_ACTIONS = [
14
+ 'emergency_escalation', 'team_escalation', 'palliative_referral',
15
+ 'symptom_recommendation', 'symptom_probe',
16
+ 'acknowledge_improvement_on_case',
17
+ 'follow_up_on_open_case', 'revisit_neglected_case',
18
+ 'educate_about_symptom', 'educate_about_treatment', 'preparation_guidance',
19
+ 'emotional_support', 'acknowledge_only',
20
+ 'request_clarification',
21
+ 'weekly_triage_recommendations',
22
+ 'generate_recommendations',
23
+ ];
24
+
25
+ const _COMPOSE_AS_VALUES = [
26
+ 'opener', 'woven_into_primary', 'closer',
27
+ 'brief_checkin', 'separate_if_space',
28
+ ];
29
+
30
+ const _ACTION_SYNONYMS = {
31
+ acknowledge: 'acknowledge_only',
32
+ clarify: 'request_clarification',
33
+ clarification: 'request_clarification',
34
+ probe: 'symptom_probe',
35
+ recommend: 'symptom_recommendation',
36
+ recommendation: 'symptom_recommendation',
37
+ referral: 'palliative_referral',
38
+ escalate: 'team_escalation',
39
+ emergency: 'emergency_escalation',
40
+ };
41
+
42
+ const _COMPOSE_SYNONYMS = {
43
+ open: 'opener',
44
+ opening: 'opener',
45
+ close: 'closer',
46
+ closing: 'closer',
47
+ weave: 'woven_into_primary',
48
+ woven: 'woven_into_primary',
49
+ checkin: 'brief_checkin',
50
+ check_in: 'brief_checkin',
51
+ separate: 'separate_if_space',
52
+ };
53
+
54
+ // The case is already closed (often earlier this same turn): its disposition is born closed, as the cascade
55
+ // would have left it.
56
+ async function closeDispositionForClosedCase({ patientId, turnId, caseId, cases }) {
57
+ const condition = caseId ? cases.find((c) => c.condition.conditionId === caseId)?.condition : null;
58
+ if (!CLOSED_STATUSES.includes(condition?.clinicalStatus) || !condition.closeReason) return;
59
+ try {
60
+ await closeRoutingDispositions({
61
+ patientId, caseId, closeReason: condition.closeReason, resolving: isResolutionReason(condition.closeReason),
62
+ });
63
+ } catch (error) {
64
+ logger.warn('[submitRoutingDecision] could not close the disposition of an already-closed case', { patientId, turnId, caseId, error: error?.message });
65
+ }
66
+ }
67
+
68
+ const _ACTION_TO_DISPOSITION_KIND = {
69
+ emergency_escalation: 'task',
70
+ team_escalation: 'task',
71
+ palliative_referral: 'task',
72
+ symptom_recommendation: 'care_plan',
73
+ follow_up_on_open_case: 'care_plan',
74
+ revisit_neglected_case: 'care_plan',
75
+ preparation_guidance: 'care_plan',
76
+ weekly_triage_recommendations: 'care_plan',
77
+ generate_recommendations: 'care_plan',
78
+ symptom_probe: 'communication_request',
79
+ acknowledge_improvement_on_case: 'communication',
80
+ emotional_support: 'communication',
81
+ educate_about_symptom: 'communication',
82
+ educate_about_treatment: 'communication',
83
+ acknowledge_only: 'communication',
84
+ request_clarification: 'communication',
85
+ };
86
+
87
+ const _DOWNSTREAM_SKILL = {
88
+ emergency_escalation: 'emergency',
89
+ palliative_referral: 'accompaniment',
90
+ symptom_recommendation: 'symptom_management',
91
+ follow_up_on_open_case: 'symptom_management',
92
+ revisit_neglected_case: 'symptom_management',
93
+ preparation_guidance: 'accompaniment',
94
+ emotional_support: 'accompaniment',
95
+ educate_about_symptom: 'patient_education',
96
+ educate_about_treatment: 'patient_education',
97
+ weekly_triage_recommendations: 'symptom_management',
98
+ generate_recommendations: 'symptom_management',
99
+ };
100
+
101
+ const _CASE_IMPLYING_ACTIONS = new Set([
102
+ 'emergency_escalation', 'team_escalation',
103
+ 'symptom_recommendation', 'symptom_probe',
104
+ 'acknowledge_improvement_on_case',
105
+ 'follow_up_on_open_case', 'revisit_neglected_case',
106
+ 'educate_about_symptom',
107
+ 'weekly_triage_recommendations', 'generate_recommendations',
108
+ ]);
109
+
110
+ const definition = {
111
+ name: 'submitRoutingDecision',
112
+ description: '**Does:** The terminal routing checkpoint — call ONCE per turn to commit the turn plan. Decomposes `trace` (the per-mention evaluation record) and `turn_plan` (the primary action + optional secondary/deferred) into a persisted RoutingDecision (assessment + disposition + provenance), sets the turn\'s outbound signals, and returns the body of the skill that governs the reply.\n\n**Required inputs:** `trace.mentions_evaluated[]` — one entry per clinical mention: `clinical_reasoning`, `decision.action`, `case_id_opened_or_updated` — REQUIRED whenever `decision.action` acts on a symptom (`emergency_escalation`, `team_escalation`, `symptom_recommendation`, `symptom_probe`, `acknowledge_improvement_on_case`, `follow_up_on_open_case`, `revisit_neglected_case`, `educate_about_symptom`, `weekly_triage_recommendations`, `generate_recommendations`), null only for a genuinely caseless mention (a medication, an appointment, a mood), plus `safety_flag_disposition` (string or object) when `safety_flags_received` is non-empty. `turn_plan.primary` — exactly one `{action, reason, case_id?}`; `turn_plan.secondary[]` — up to 2 `{action, compose_as}`; `turn_plan.deferred[]` — optional `{item?, defer_reason}`.\n\n**Routing-skill prerequisite:** when `clinical_routing` is among your enabled skills and `Skill` is offered to you this turn, this checkpoint fails until that body has been read in an EARLIER iteration. Presets without either proceed straight to routing. `extractClinicalInfo` returns that body in its `activated_skills` when it extracts clinical mentions: read it there and commit here in a LATER response, not in the same one as the intake. If no body was returned, call `Skill` with `skill=clinical_routing` first.\n\n**Risk prerequisite:** after a clinical intake with extracted mentions, this checkpoint fails until the turn trace records a successful, processed risk read with status `final`, `no_signal`, or `not_generated`. Normally call `getRouterContextBundle` first and use its `risk.turn_focus`; if `sections_returned` lacks `risk` or reports `_diagnostics.risk_error`, call `getPatientRiskAssessment`, then retry this checkpoint.\n\n**Enum coercion:** primary/secondary `action` and secondary `compose_as` are folded (case/accent/separator) and synonym-mapped to canonical values; each repair is disclosed via `auto_repairs`. A genuinely unknown action is rejected.\n\n**Returns:** `decision_id`, `downstream_skill_to_invoke` (emergency | accompaniment | symptom_management | patient_education | null, derived from `primary.action`), `activated_skills` (that skill\'s body, when it is enabled and not yet loaded this turn — read it and compose the reply from it; no `Skill` call needed), and `auto_repairs` (only when non-empty). Fails hard with `risk_assessment_required_before_routing` when clinical intake ran without a processed risk disposition, with `decision_already_committed_for_turn` if called twice in one turn, when a symptom-acting mention carries no `case_id_opened_or_updated`, and when a named `case_id` does not exist for this patient. A clinical `DeliverPatientMessage` remains blocked until this commit succeeds.\n\n**Side effects:** persists the RoutingDecision; sets `branch_taken=ai_agent` on the turn trace.',
113
+ strict: false,
114
+ parameters: {
115
+ type: 'object',
116
+ properties: {
117
+ trace: {
118
+ type: 'object',
119
+ properties: {
120
+ mentions_evaluated: {
121
+ type: 'array',
122
+ description: 'One entry per clinical mention evaluated this turn.',
123
+ items: {
124
+ type: 'object',
125
+ properties: {
126
+ case_id_opened_or_updated: {
127
+ type: ['string', 'null'],
128
+ description: 'The case this mention opened or updated. REQUIRED whenever `decision.action` acts on a symptom; null ONLY for a genuinely caseless mention (a medication, an appointment, a mood).',
129
+ },
130
+ clinical_reasoning: { type: 'string', pattern: '\\S', description: 'Why this mention was dispositioned this way. Trimmed and rejected when empty.' },
131
+ decision: {
132
+ type: 'object',
133
+ properties: { action: { type: 'string', enum: [..._ROUTING_ACTIONS], description: 'The action taken on this mention.' } },
134
+ required: ['action'],
135
+ },
136
+ safety_flags_received: { type: 'array', items: { type: 'string' }, description: 'Safety flags carried by this mention.' },
137
+ safety_flag_disposition: {
138
+ anyOf: [{ type: 'string', minLength: 1 }, { type: 'object' }],
139
+ description: 'Required whenever `safety_flags_received` is non-empty. A short string (e.g. `acknowledged`, `escalated`) or an object. Arrays, numbers and null are rejected.',
140
+ },
141
+ },
142
+ required: ['clinical_reasoning', 'decision'],
143
+ },
144
+ },
145
+ },
146
+ description: 'Per-mention evaluation record. `mentions_evaluated[]`: each `{case_id_opened_or_updated?, clinical_reasoning, decision:{action}, safety_flags_received?, safety_flag_disposition?}`. `case_id_opened_or_updated` is null/omitted ONLY when the mention opened or updated no case (e.g. a medication, appointment, allergy or emotion mention); any action that acts on a symptom must name its case, and the id must be one this patient actually has. `safety_flag_disposition` is required for any mention with a non-empty `safety_flags_received`, and may be a short string (e.g. `acknowledged`, `escalated`) or an object. '
147
+ + MEDICATION_NAMING_RULE,
148
+ },
149
+ turn_plan: {
150
+ type: 'object',
151
+ description: 'The routing plan. `primary` (required): `{action, reason, case_id?}`. `secondary` (0-2): `[{action, compose_as}]`. `deferred` (optional): `[{item?, defer_reason}]`.',
152
+ properties: {
153
+ primary: {
154
+ type: 'object',
155
+ description: 'Exactly one primary action for the turn. Determines `downstream_skill_to_invoke`.',
156
+ properties: {
157
+ action: { type: 'string', enum: [..._ROUTING_ACTIONS], description: 'The turn\'s primary action.' },
158
+ reason: { type: 'string', pattern: '\\S', description: 'Why this action, in one sentence. Trimmed and rejected when empty.' },
159
+ case_id: { type: ['string', 'null'], description: 'The case this action acts on, when it acts on a symptom.' },
160
+ },
161
+ required: ['action', 'reason'],
162
+ },
163
+ secondary: {
164
+ type: 'array',
165
+ maxItems: 2,
166
+ description: 'Up to 2 secondary actions woven into the same outbound message.',
167
+ items: {
168
+ type: 'object',
169
+ properties: {
170
+ action: { type: 'string', enum: [..._ROUTING_ACTIONS], description: 'The secondary action.' },
171
+ compose_as: {
172
+ type: 'string',
173
+ enum: [..._COMPOSE_AS_VALUES],
174
+ description: 'How this rides in the message. Pick one of the listed values — it is a placement slot, not a free-text description of what to say.',
175
+ },
176
+ },
177
+ required: ['action', 'compose_as'],
178
+ },
179
+ },
180
+ deferred: {
181
+ type: 'array',
182
+ description: 'Mentions deliberately not addressed this turn.',
183
+ items: {
184
+ type: 'object',
185
+ properties: {
186
+ item: { type: 'string', description: 'What is being deferred.' },
187
+ defer_reason: { type: 'string', pattern: '\\S', description: 'Why it waits. Trimmed and rejected when empty.' },
188
+ },
189
+ required: ['defer_reason'],
190
+ },
191
+ },
192
+ },
193
+ required: ['primary'],
194
+ },
195
+ },
196
+ required: ['trace', 'turn_plan'],
197
+ },
198
+ };
199
+
200
+ const uid = (prefix) => `${prefix}_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
201
+
202
+ function fail(error, data = {}) {
203
+ return JSON.stringify({ success: false, error, data });
204
+ }
205
+
206
+ function foldToken(value) {
207
+ const folded = foldAccents(String(value).trim().toLowerCase());
208
+ return folded.replace(/[\s\-/]+/g, '_');
209
+ }
210
+
211
+ function unwrapScalar(value) {
212
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
213
+ for (const key of ['value', 'action', 'name']) {
214
+ if (typeof value[key] === 'string') return value[key];
215
+ }
216
+ }
217
+ if (Array.isArray(value) && value.length === 1) return value[0];
218
+ return value;
219
+ }
220
+
221
+ function coerceRoutingEnum(value, valid, synonyms, field, repairs) {
222
+ const raw = unwrapScalar(value);
223
+ if (typeof raw !== 'string') return value;
224
+ const trimmed = raw.trim();
225
+ if (valid.includes(trimmed)) return trimmed;
226
+ const folded = foldToken(trimmed);
227
+ const hit = valid.find((m) => foldToken(m) === folded) || synonyms[folded];
228
+ if (!hit || !valid.includes(hit)) return trimmed;
229
+ repairs.push(`${field}: '${trimmed}' → '${hit}'`);
230
+ return hit;
231
+ }
232
+
233
+ function derivedDownstreamSkill(primaryAction) {
234
+ return _DOWNSTREAM_SKILL[primaryAction] || null;
235
+ }
236
+
237
+ function validateTurnPlan(turnPlan, repairs) {
238
+ const primary = turnPlan.primary;
239
+ if (!primary || typeof primary !== 'object' || Array.isArray(primary)) {
240
+ return { error: fail('turn_plan.primary is required — exactly one action') };
241
+ }
242
+ const primaryAction = coerceRoutingEnum(primary.action, _ROUTING_ACTIONS, _ACTION_SYNONYMS, 'primary.action', repairs);
243
+ if (!_ROUTING_ACTIONS.includes(primaryAction)) {
244
+ return { error: fail(`primary.action '${primaryAction}' not in action-taxonomy`, { primary_action: primaryAction, valid_actions: [..._ROUTING_ACTIONS].sort() }) };
245
+ }
246
+ const primaryReason = typeof primary.reason === 'string' ? primary.reason.trim() : '';
247
+ if (!primaryReason) return { error: fail('turn_plan.primary.reason is required (non-empty string)') };
248
+ const primaryCaseId = (typeof primary.case_id === 'string' ? primary.case_id.trim() : '') || null;
249
+
250
+ const secondaryRaw = turnPlan.secondary || [];
251
+ if (!Array.isArray(secondaryRaw)) return { error: fail('turn_plan.secondary must be a list (0-2 items)') };
252
+ if (secondaryRaw.length > 2) return { error: fail('turn_plan.secondary has at most 2 items', { n: secondaryRaw.length }) };
253
+ const secondaryActions = [];
254
+ for (let i = 0; i < secondaryRaw.length; i += 1) {
255
+ const secondary = secondaryRaw[i];
256
+ if (!secondary || typeof secondary !== 'object' || Array.isArray(secondary)) return { error: fail('turn_plan.secondary[*] must be objects', { index: i }) };
257
+ const action = coerceRoutingEnum(secondary.action, _ROUTING_ACTIONS, _ACTION_SYNONYMS, 'secondary.action', repairs);
258
+ if (!_ROUTING_ACTIONS.includes(action)) return { error: fail(`secondary[${i}].action '${action}' not in action-taxonomy`, { index: i, action }) };
259
+ const composeAs = coerceRoutingEnum(secondary.compose_as, _COMPOSE_AS_VALUES, _COMPOSE_SYNONYMS, 'secondary.compose_as', repairs);
260
+ if (!_COMPOSE_AS_VALUES.includes(composeAs)) return { error: fail(`secondary[${i}].compose_as must be one of ${[..._COMPOSE_AS_VALUES].sort().join(', ')}`, { index: i, compose_as: composeAs }) };
261
+ secondaryActions.push({ action, composeAs });
262
+ }
263
+
264
+ const deferredRaw = turnPlan.deferred || [];
265
+ if (!Array.isArray(deferredRaw)) return { error: fail('turn_plan.deferred must be a list') };
266
+ const deferredItems = [];
267
+ for (let i = 0; i < deferredRaw.length; i += 1) {
268
+ const deferred = deferredRaw[i];
269
+ if (!deferred || typeof deferred !== 'object' || Array.isArray(deferred)) return { error: fail('turn_plan.deferred[*] must be objects', { index: i }) };
270
+ const reason = typeof deferred.defer_reason === 'string' ? deferred.defer_reason.trim() : '';
271
+ if (!reason) return { error: fail(`deferred[${i}].defer_reason is required (non-empty)`, { index: i }) };
272
+ const item = (typeof deferred.item === 'string' ? deferred.item.trim() : '') || reason;
273
+ deferredItems.push({ item, deferReason: reason });
274
+ }
275
+
276
+ return { primaryAction, primaryReason, primaryCaseId, secondaryActions, deferredItems };
277
+ }
278
+
279
+ function gateRefusedEarlierThisTurn(trace) {
280
+ const steps = Array.isArray(trace?.steps) ? trace.steps : [];
281
+ return steps.some((step) => {
282
+ if (step?.tool_name !== 'submitRoutingDecision') return false;
283
+ const output = typeof step.tool_output === 'string' ? step.tool_output : JSON.stringify(step.tool_output || '');
284
+ return output.includes('case_id_opened_or_updated is required for decision.action');
285
+ });
286
+ }
287
+
288
+ function validateTrace(trace) {
289
+ const mentionsRaw = trace.mentions_evaluated || [];
290
+ if (!Array.isArray(mentionsRaw)) return { error: fail('trace.mentions_evaluated must be a list') };
291
+ const findings = [];
292
+ for (let i = 0; i < mentionsRaw.length; i += 1) {
293
+ const mention = mentionsRaw[i];
294
+ if (!mention || typeof mention !== 'object' || Array.isArray(mention)) return { error: fail('trace.mentions_evaluated[*] must be objects', { index: i }) };
295
+ // A non-symptom mention (medication, appointment, allergy, emotion) opens no case, so case_id is optional; null records the absence.
296
+ const caseId = (typeof mention.case_id_opened_or_updated === 'string' ? mention.case_id_opened_or_updated.trim() : '') || null;
297
+ const reasoning = typeof mention.clinical_reasoning === 'string' ? mention.clinical_reasoning.trim() : '';
298
+ if (!reasoning) return { error: fail(`mentions_evaluated[${i}].clinical_reasoning is required`, { index: i }) };
299
+ let decision = mention.decision;
300
+ if (typeof decision === 'string' && decision.trim()) decision = { action: decision.trim() };
301
+ if (!decision || typeof decision !== 'object' || Array.isArray(decision)) {
302
+ return { error: fail(`mentions_evaluated[${i}].decision is required (object with at least \`action\`)`, { index: i }) };
303
+ }
304
+ const decisionAction = typeof decision.action === 'string' ? decision.action.trim() : '';
305
+ if (!decisionAction) return { error: fail(`mentions_evaluated[${i}].decision.action is required (string)`, { index: i }) };
306
+ const canonicalAction = coerceRoutingEnum(decisionAction, _ROUTING_ACTIONS, _ACTION_SYNONYMS, null, []);
307
+ if (!_ROUTING_ACTIONS.includes(canonicalAction)) {
308
+ return { error: fail(`mentions_evaluated[${i}].decision.action is not a known action: '${decisionAction}'.`, { index: i, valid_actions: _ROUTING_ACTIONS }) };
309
+ }
310
+ if (!caseId && _CASE_IMPLYING_ACTIONS.has(canonicalAction)) {
311
+ return {
312
+ error: fail(
313
+ `mentions_evaluated[${i}].case_id_opened_or_updated is required for decision.action='${decisionAction}' — this action acts on a symptom, so the mention must name the case it opened or updated.`,
314
+ {
315
+ index: i,
316
+ decision_action: decisionAction,
317
+ recovery: 'Open the case with openCondition(ctcae_term, episode_id, mention_id, verbatim_quote), record the read with recordClinicalImpression, and put the returned case_id here. Do not retry by relabelling the action — you judged this mention to be a symptom, and a symptom the patient reported needs its case whichever action you route it under.',
318
+ },
319
+ ),
320
+ };
321
+ }
322
+ const flags = mention.safety_flags_received || [];
323
+ if (flags != null && !Array.isArray(flags)) {
324
+ return { error: fail(`mentions_evaluated[${i}].safety_flags_received must be a list`, { index: i }) };
325
+ }
326
+ if (Array.isArray(flags) && flags.length) {
327
+ // Accept the model's most common shape — a plain string ('acknowledged', 'escalated') — as well as an object.
328
+ const disposition = typeof mention.safety_flag_disposition === 'string'
329
+ ? mention.safety_flag_disposition.trim()
330
+ : mention.safety_flag_disposition;
331
+ const hasDisposition = typeof disposition === 'string'
332
+ ? disposition.length > 0
333
+ : (disposition && typeof disposition === 'object' && !Array.isArray(disposition));
334
+ if (!hasDisposition) {
335
+ return { error: fail(`mentions_evaluated[${i}].safety_flag_disposition is required when safety_flags_received is non-empty`, { index: i, mention_id: mention.mention_id }) };
336
+ }
337
+ }
338
+ findings.push({ caseId, clinicalReasoning: reasoning, decisionAction });
339
+ }
340
+ return { findings };
341
+ }
342
+
343
+ function buildDecision({ patientId, turnId, plan, findings, now }) {
344
+ const kind = plan.secondaryActions.length ? 'orchestration' : (_ACTION_TO_DISPOSITION_KIND[plan.primaryAction] || 'communication');
345
+ return new RoutingDecision({
346
+ schemaVersion: '1',
347
+ decisionId: uid('decision'),
348
+ patientId,
349
+ turnId,
350
+ committedAt: now,
351
+ assessment: {
352
+ assessmentId: uid('assessment'),
353
+ patientId,
354
+ turnId,
355
+ performedAt: now,
356
+ previousId: null,
357
+ summary: plan.primaryReason,
358
+ notes: [],
359
+ findings,
360
+ },
361
+ disposition: {
362
+ dispositionId: uid('disposition'),
363
+ patientId,
364
+ kind,
365
+ primaryAction: plan.primaryAction,
366
+ primaryReason: plan.primaryReason,
367
+ primaryCaseId: plan.primaryCaseId,
368
+ secondaryActions: plan.secondaryActions,
369
+ deferredItems: plan.deferredItems,
370
+ authoredAt: now,
371
+ },
372
+ provenance: {
373
+ agentDevice: 'clinical-agent-v2',
374
+ onBehalfOf: 'peopl-health',
375
+ recordedAt: now,
376
+ },
377
+ });
378
+ }
379
+
380
+ async function handler(args = {}, context = {}) {
381
+ try {
382
+ const runtime = context?.toolRuntimeContext || null;
383
+ if (!runtime?.turnId || !runtime?.patientCode || !runtime?.trace) {
384
+ return fail('submitRoutingDecision requires an active turn context (turnId, patientCode, trace).');
385
+ }
386
+ const trace = args?.trace;
387
+ const turnPlan = args?.turn_plan;
388
+ if (!trace || typeof trace !== 'object' || Array.isArray(trace)) return fail('trace is required (non-empty object)');
389
+ if (!turnPlan || typeof turnPlan !== 'object' || Array.isArray(turnPlan)) return fail('turn_plan is required (non-empty object)');
390
+ const prerequisite = validateRoutingPrerequisites(runtime.trace, {
391
+ enabledSkills: runtime.enabledSkills,
392
+ skillActivationIteration: runtime.skillActivationIteration,
393
+ currentIteration: runtime.currentIteration,
394
+ });
395
+ if (prerequisite) {
396
+ return fail(prerequisite.error, {
397
+ recovery: prerequisite.recovery,
398
+ required_tool_ids: prerequisite.requiredToolIds,
399
+ });
400
+ }
401
+
402
+ const repairs = [];
403
+ const plan = validateTurnPlan(turnPlan, repairs);
404
+ if (plan.error) return plan.error;
405
+ const traceResult = validateTrace(trace);
406
+ if (traceResult.error) return traceResult.error;
407
+
408
+ const patientId = runtime.patientCode;
409
+ const turnId = runtime.turnId;
410
+
411
+ const [existing] = await readRoutingDecisions({ patientId, turnId });
412
+ if (existing) {
413
+ return fail('decision_already_committed_for_turn', { existing_decision_id: existing.decisionId, committed_at: existing.committedAt });
414
+ }
415
+
416
+ const namedCaseIds = [...new Set([...traceResult.findings.map((f) => f.caseId), plan.primaryCaseId].filter(Boolean))];
417
+ let cases = [];
418
+ if (namedCaseIds.length) {
419
+ cases = await readSymptomCases({ patientId });
420
+ const known = new Set(cases.map((c) => c.condition.conditionId));
421
+ const unknown = namedCaseIds.filter((id) => !known.has(id));
422
+ if (unknown.length) {
423
+ return fail('case_id_opened_or_updated names a case that does not exist for this patient', {
424
+ unknown_case_ids: unknown,
425
+ known_cases: cases.map((c) => ({
426
+ case_id: c.condition.conditionId,
427
+ ctcae_term: c.condition.ctcaeTerm,
428
+ status: c.condition.clinicalStatus,
429
+ })),
430
+ recovery: 'Pick the case_id from known_cases whose ctcae_term is the symptom you meant. If none matches, the case does not exist yet: call openCondition first and use the id it returns. Never invent an id.',
431
+ });
432
+ }
433
+ }
434
+
435
+ const decision = buildDecision({ patientId, turnId, plan, findings: traceResult.findings, now: new Date().toISOString() });
436
+ await storeRoutingDecision({ patientId, routingDecision: decision });
437
+ await closeDispositionForClosedCase({ patientId, turnId, caseId: plan.primaryCaseId, cases });
438
+
439
+ runtime.trace.setSignals({ branchTaken: 'ai_agent' });
440
+
441
+ if (!namedCaseIds.length && gateRefusedEarlierThisTurn(runtime.trace)) {
442
+ logger.warn('[submitRoutingDecision] committed with no case after the case gate refused this turn', {
443
+ patientId,
444
+ turnId,
445
+ actions: traceResult.findings.map((f) => f.decisionAction),
446
+ });
447
+ runtime.trace.setSignals({ routingDowngradedAfterCaseGate: true });
448
+ }
449
+
450
+ const downstream = derivedDownstreamSkill(plan.primaryAction);
451
+ runtime.trace.setSignals({ downstreamSkill: downstream || null });
452
+ const data = { decision_id: decision.decisionId, downstream_skill_to_invoke: downstream };
453
+ const deliveryNeedsSkill = clinicalIntakeRequiresRisk(runtime.trace) && !hasAlternateTerminalCommit(runtime.trace);
454
+ const downstreamSkill = deliveryNeedsSkill ? await attachRequiredSkill(runtime, downstream) : null;
455
+ if (downstreamSkill) data.activated_skills = [downstreamSkill];
456
+ if (repairs.length) data.auto_repairs = repairs;
457
+ return JSON.stringify({ success: true, data });
458
+ } catch (err) {
459
+ return JSON.stringify({ success: false, error: err?.message || 'submitRoutingDecision failed', data: {} });
460
+ }
461
+ }
462
+
463
+ module.exports = {
464
+ definition,
465
+ handler,
466
+ };
@@ -0,0 +1,130 @@
1
+ const { ZodError } = require('zod');
2
+
3
+ const { str, arr, buildRedFlag, normalizeGateEscalation } = require('../helpers/recommendationGateHelper');
4
+ const { urgentGateIssues } = require('../services/recommendationValidationService');
5
+ const { storeSafetyGate, safetyGateExists } = require('../../fhir');
6
+ const { RecommendationSafetyGate, ESCALATION_ROUTES } = require('../../shared/dtos/RecommendationSafetyGate');
7
+ const { logger } = require('../../utils/logger');
8
+
9
+ const definition = {
10
+ name: 'submitSafetyGate',
11
+ description: '**Does:** Commits the safety-gate evaluation (red flags mapped to high-risk adverse events, urgency, escalation route) for THIS turn\'s recommendation run. Call ONCE when generating a plan. Verification arithmetic and escalation-field consistency are repaired server-side (disclosed in `auto_repairs`); only a contradictory URGENT gate is rejected — an urgent gate demands `max_action_time_hours` (1-24), an `escalation_route`, and ≥1 confirmed/partially_confirmed red flag. An urgent gate does not notify anyone by itself: escalate via reportMedicalEscalation.\n\n**Required inputs:** `urgent_under_24h`, `summary`. Per red flag in `red_flags`: `name` + `verification_status`. `max_action_time_hours` / `escalation_route` / `reason_for_escalation` apply only when urgent.\n\n**Returns:** `accepted`, `run_id`, `urgent_under_24h`, `escalation_route`, `red_flags_count`, `must_escalate_now`, `auto_repairs`.\n\n**Side effects:** persists the gate as a run-scoped FHIR RiskAssessment.',
12
+ strict: false,
13
+ parameters: {
14
+ type: 'object',
15
+ properties: {
16
+ urgent_under_24h: {
17
+ type: 'boolean',
18
+ description: 'True when the situation demands action within 24h. Requires max_action_time_hours + escalation_route + a confirmed/partially_confirmed red flag.',
19
+ },
20
+ max_action_time_hours: {
21
+ type: 'integer',
22
+ description: '1-24 when urgent_under_24h=true; null otherwise. Nulled server-side on a non-urgent gate.',
23
+ },
24
+ escalation_route: {
25
+ type: 'string',
26
+ enum: ESCALATION_ROUTES,
27
+ description: 'Global escalation route: emergencia | urgencias | equipo_tratante_hoy. Required when urgent; nulled otherwise.',
28
+ },
29
+ reason_for_escalation: {
30
+ type: 'string',
31
+ description: 'Why this gate escalates. Nulled server-side on a non-urgent gate.',
32
+ },
33
+ summary: {
34
+ type: 'string',
35
+ description: 'Plain-language gate summary.',
36
+ },
37
+ red_flags: {
38
+ type: 'array',
39
+ description: 'Red flags evaluated this turn. Each: `{name, verification_status, escalation_route, events_confirmed[], events_denied[], related_aes[], definition[{clinical_event, ctcae_grades_reference[]}], grounded_in[]}`. verification_status is repaired from the events (denied ⇒ denied; no confirmed events ⇒ inconclusive; confirmed but a definition clinical_event is unconfirmed ⇒ partially_confirmed).',
40
+ items: { type: 'object' },
41
+ },
42
+ },
43
+ required: ['urgent_under_24h', 'summary'],
44
+ },
45
+ };
46
+
47
+ async function handler(args = {}, context = {}) {
48
+ try {
49
+ const runtime = context?.toolRuntimeContext || null;
50
+ if (!runtime?.turnId || !runtime?.patientCode) {
51
+ return JSON.stringify({ success: false, error: 'submitSafetyGate requires an active turn context (turnId, patientCode).', data: {} });
52
+ }
53
+ if (typeof args?.urgent_under_24h !== 'boolean') {
54
+ return JSON.stringify({ success: false, error: 'urgent_under_24h is required and must be a boolean.', data: {} });
55
+ }
56
+ const summary = str(args?.summary).trim();
57
+ if (!summary) {
58
+ return JSON.stringify({ success: false, error: 'summary is required.', data: {} });
59
+ }
60
+
61
+ const repairs = [];
62
+ const runId = `recrun-chat-${runtime.turnId}`;
63
+ const redFlags = arr(args?.red_flags).map((raw, index) => buildRedFlag(raw, repairs, index));
64
+
65
+ const { urgent, maxActionTimeHours, escalationRoute, reasonForEscalation } = normalizeGateEscalation(args, repairs);
66
+ const issues = urgentGateIssues({ urgent, maxActionTimeHours, escalationRoute, redFlags });
67
+ if (issues.length) {
68
+ return JSON.stringify({ success: false, error: 'gate_inconsistent', data: { urgent_gate_requires: issues } });
69
+ }
70
+
71
+ if (await safetyGateExists({ runId })) {
72
+ return JSON.stringify({ success: false, error: 'gate_already_committed_for_turn', data: { run_id: runId } });
73
+ }
74
+
75
+ const safetyGate = new RecommendationSafetyGate({
76
+ runId,
77
+ patientId: runtime.patientCode,
78
+ origin: 'chat',
79
+ turnId: runtime.turnId,
80
+ urgentUnder24h: urgent,
81
+ maxActionTimeHours,
82
+ escalationRoute,
83
+ reasonForEscalation,
84
+ summary,
85
+ redFlags,
86
+ createdAt: new Date().toISOString(),
87
+ });
88
+
89
+ await storeSafetyGate({ patientId: runtime.patientCode, safetyGate });
90
+
91
+ const trace = runtime.trace || null;
92
+ if (trace) {
93
+ trace.setSignals({
94
+ safetyGate: {
95
+ runId,
96
+ urgentUnder24h: urgent,
97
+ // The plan tool validates inheritance off this signal; there is no readSafetyGate.
98
+ maxActionTimeHours,
99
+ escalationRoute,
100
+ redFlagsCount: redFlags.length,
101
+ },
102
+ });
103
+ } else {
104
+ logger.warn('[submitSafetyGate] no trace on runtime context; safety-gate signal not recorded', { turnId: runtime.turnId });
105
+ }
106
+
107
+ return JSON.stringify({
108
+ success: true,
109
+ data: {
110
+ accepted: true,
111
+ run_id: runId,
112
+ urgent_under_24h: urgent,
113
+ escalation_route: escalationRoute,
114
+ red_flags_count: redFlags.length,
115
+ must_escalate_now: urgent,
116
+ auto_repairs: repairs,
117
+ },
118
+ });
119
+ } catch (err) {
120
+ if (err instanceof ZodError) {
121
+ return JSON.stringify({ success: false, error: 'gate_schema_invalid', data: { issues: err.issues.map((issue) => ({ path: issue.path.join('.'), problem: issue.message })) } });
122
+ }
123
+ return JSON.stringify({ success: false, error: err?.message || 'submitSafetyGate failed', data: {} });
124
+ }
125
+ }
126
+
127
+ module.exports = {
128
+ definition,
129
+ handler,
130
+ };