@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
package/lib/index.d.ts CHANGED
@@ -2,9 +2,18 @@ declare module '@peopl-health/nexus' {
2
2
  // Core Types
3
3
  export interface MessageData {
4
4
  id?: string;
5
+ messageId?: string;
6
+ message_id?: string;
5
7
  from: string;
6
8
  code?: string;
9
+ contactCode?: string | null;
10
+ contactRole?: 'caregiver' | null;
11
+ contactName?: string | null;
12
+ contactLabel?: string | null;
13
+ body?: string;
7
14
  message?: string;
15
+ timestamp?: string | Date;
16
+ createdAt?: string | Date;
8
17
  fileUrl?: string;
9
18
  fileType?: 'text' | 'image' | 'document' | 'audio' | 'video';
10
19
  contentSid?: string;
@@ -14,11 +23,17 @@ declare module '@peopl-health/nexus' {
14
23
  command?: CommandData;
15
24
  keyword?: string;
16
25
  flow?: InteractiveData;
17
- type?: 'message' | 'interactive' | 'media' | 'command' | 'keyword' | 'flow';
26
+ type?: 'message' | 'interactive' | 'media' | 'command' | 'keyword' | 'flow' | 'empty';
18
27
  }
19
28
 
29
+ export function registerInteractiveRoute(
30
+ prefix: string,
31
+ handler: (tap: { code: string; payload: string | null; title: string | null; messageData: unknown }) => unknown
32
+ ): void;
33
+ export function clearInteractiveRoutes(): void;
34
+
20
35
  export interface InteractiveData {
21
- type: 'button' | 'list' | 'flow';
36
+ type: 'button' | 'list' | 'flow' | 'quick_reply';
22
37
  payload?: string;
23
38
  title?: string;
24
39
  description?: string;
@@ -51,8 +66,8 @@ declare module '@peopl-health/nexus' {
51
66
  patientId?: string;
52
67
  runId?: string;
53
68
  nombre?: string;
54
- active: boolean;
55
69
  stopped?: boolean;
70
+ pausedAt?: Date | null;
56
71
  nextSid?: string[];
57
72
  createdAt: Date;
58
73
  }
@@ -116,13 +131,13 @@ declare module '@peopl-health/nexus' {
116
131
  name: string;
117
132
  description?: string;
118
133
  parameters?: any;
119
- handler: (args: any) => any;
134
+ handler: (args: any) => string | Promise<string>;
120
135
  }
121
136
 
122
137
  export interface AssistantConfigDefinition {
123
138
  extends?: typeof BaseAssistant;
124
139
  create?: (this: BaseAssistant, code: string, context?: any) => Promise<any>;
125
- tools?: Array<AssistantToolDefinition | { name: string; definition?: any; handler: (args: any) => any }>;
140
+ tools?: Array<AssistantToolDefinition | { name: string; definition?: any; handler: (args: any) => string | Promise<string> }>;
126
141
  setup?: (this: BaseAssistant, context: { assistantId: string; thread?: any; options?: any }) => void;
127
142
  }
128
143
 
@@ -138,7 +153,7 @@ declare module '@peopl-health/nexus' {
138
153
  assistantId?: string;
139
154
  thread?: any;
140
155
  client?: any;
141
- tools?: Array<AssistantToolDefinition | { name: string; definition?: any; handler: (args: any) => any }>;
156
+ tools?: Array<AssistantToolDefinition | { name: string; definition?: any; handler: (args: any) => string | Promise<string> }>;
142
157
  setup?: (context: { assistantId: string; thread?: any; options?: any }) => void;
143
158
  status?: string;
144
159
  } | any);
@@ -146,9 +161,9 @@ declare module '@peopl-health/nexus' {
146
161
  thread: any;
147
162
  status: string;
148
163
  createdAt: Date;
149
- registerTool(definition: AssistantToolDefinition | string, schema?: any, handler?: (args: any) => any): void;
164
+ registerTool(definition: AssistantToolDefinition | string, schema?: any, handler?: (args: any) => string | Promise<string>): void;
150
165
  getToolSchemas(): any[];
151
- executeTool(name: string, args: any): Promise<any>;
166
+ executeTool(name: string, args: any): Promise<string>;
152
167
  getPreviousMessages(thread?: any): Promise<Array<{ role: string; content: any }>>;
153
168
  createThread(code: string, context?: any): Promise<any>;
154
169
  sendMessage(userId: string, message: string, options?: any): Promise<any>;
@@ -172,6 +187,9 @@ declare module '@peopl-health/nexus' {
172
187
  body: string;
173
188
  media: any | null;
174
189
  type: 'message' | 'interactive' | 'media';
190
+ raw?: { role?: string; replyRequested?: boolean };
191
+ contactCode?: string;
192
+ contactRole?: 'caregiver' | null;
175
193
  }
176
194
 
177
195
  export interface MessageStatusEventData {
@@ -194,7 +212,6 @@ declare module '@peopl-health/nexus' {
194
212
  constructor(config: any);
195
213
  abstract initialize(): Promise<void>;
196
214
  abstract sendMessage(messageData: MessageData): Promise<any>;
197
- abstract sendScheduledMessage(scheduledMessage: ScheduledMessage): Promise<void>;
198
215
  abstract getConnectionStatus(): boolean;
199
216
  abstract disconnect(): Promise<void>;
200
217
  }
@@ -206,6 +223,16 @@ declare module '@peopl-health/nexus' {
206
223
 
207
224
  export function overrideGetAssistantById(resolver: (assistantId: string, thread?: any) => any): void;
208
225
  export function configureAssistants(config: any): void;
226
+ export interface PreprocessingOpsAlert {
227
+ label: string;
228
+ summary: string;
229
+ }
230
+
231
+ export interface PreprocessingResult {
232
+ handled?: boolean;
233
+ alert?: true | PreprocessingOpsAlert;
234
+ }
235
+
209
236
  export function setPreprocessingHandler(
210
237
  handler: (payload: IncomingPreprocessingPayload) => any | Promise<any>
211
238
  ): void;
@@ -218,7 +245,6 @@ declare module '@peopl-health/nexus' {
218
245
  constructor(config: TwilioConfig);
219
246
  initialize(): Promise<void>;
220
247
  sendMessage(messageData: MessageData): Promise<any>;
221
- sendScheduledMessage(scheduledMessage: ScheduledMessage): Promise<void>;
222
248
  getConnectionStatus(): boolean;
223
249
  disconnect(): Promise<void>;
224
250
  }
@@ -227,27 +253,33 @@ declare module '@peopl-health/nexus' {
227
253
  constructor(config: BaileysConfig);
228
254
  initialize(): Promise<void>;
229
255
  sendMessage(messageData: MessageData): Promise<any>;
230
- sendScheduledMessage(scheduledMessage: ScheduledMessage): Promise<void>;
231
256
  getConnectionStatus(): boolean;
232
257
  disconnect(): Promise<void>;
233
258
  }
234
259
 
235
260
  export class NexusMessaging {
236
- constructor(config?: any);
261
+ constructor(config?: NexusMessagingConfig);
237
262
  initializeProvider(providerType: 'twilio' | 'baileys', providerConfig: TwilioConfig | BaileysConfig): Promise<void>;
238
263
  setMessageStorage(storage: any): void;
239
264
  setHandlers(handlers: MessageHandlers): void;
240
265
  sendMessage(messageData: MessageData): Promise<any>;
241
266
  sendScheduledMessage(scheduledMessage: ScheduledMessage): Promise<void>;
242
- processIncomingMessage(messageData: MessageData): Promise<any>;
267
+ processIncomingMessage(messageData: MessageData & { type: NonNullable<MessageData['type']> }, options?: IncomingMessageOptions): Promise<any>;
243
268
  getEventBus(): import('events').EventEmitter;
244
269
  getBatchingManager(): BatchingManager;
245
270
  getPipeline(): ProcessingPipeline;
246
271
  getAssistantProcessor(): AssistantProcessor;
247
- processInstruction(code: string, instruction: string, role?: string): Promise<string | null>;
248
- processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<string | null>;
272
+ getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
273
+ initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
274
+ getWorkflowRunner(): WorkflowRunner;
275
+ processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
+ processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
+ processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
278
+ processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
279
+ processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
249
280
  isConnected(): boolean;
250
- disconnect(): Promise<void>;
281
+ shutdown(options?: ShutdownOptions): Promise<DrainResult>;
282
+ disconnect(options?: ShutdownOptions): Promise<DrainResult>;
251
283
  }
252
284
 
253
285
  export class MongoStorage {
@@ -283,7 +315,7 @@ declare module '@peopl-health/nexus' {
283
315
  getVariant(): string;
284
316
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
285
317
  runConversation(config?: any): Promise<any>;
286
- runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
318
+ runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
287
319
  }
288
320
 
289
321
  export interface LLMProvider {
@@ -291,7 +323,7 @@ declare module '@peopl-health/nexus' {
291
323
  getClient?(): any;
292
324
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
293
325
  runConversation(config?: any): Promise<any>;
294
- runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
326
+ runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
295
327
  transcribeAudio?(options?: any): Promise<any>;
296
328
  }
297
329
 
@@ -299,7 +331,7 @@ declare module '@peopl-health/nexus' {
299
331
 
300
332
  // Main Nexus Class
301
333
  export interface NexusConfig {
302
- messaging?: any;
334
+ messaging?: NexusMessagingConfig;
303
335
  }
304
336
 
305
337
  export interface NerOptions {
@@ -308,6 +340,11 @@ declare module '@peopl-health/nexus' {
308
340
  nerTimeoutMs?: number;
309
341
  }
310
342
 
343
+ export interface IncomingMessageOptions {
344
+ /** Called with the saved message's id once it is persisted, before the turn runs. Not called when nothing was persisted. */
345
+ onSaved?: (messageId: string) => void | Promise<void>;
346
+ }
347
+
311
348
  export interface InitializeOptions {
312
349
  provider?: 'twilio' | 'baileys';
313
350
  providerConfig?: TwilioConfig | BaileysConfig;
@@ -317,6 +354,40 @@ declare module '@peopl-health/nexus' {
317
354
  parser?: boolean;
318
355
  parserConfig?: ParserConfig;
319
356
  ner?: NerOptions;
357
+ recommendationRecovery?: RecommendationRecoveryOptions;
358
+ inboundRecovery?: InboundRecoveryOptions;
359
+ reviewDrafts?: ReviewDraftsOptions;
360
+ reviewAlerts?: ReviewAlertsOptions;
361
+ program?: ProgramOptions;
362
+ /** Allowed outbound numbers; unset allows all. */
363
+ outboundAllowlist?: string | string[];
364
+ }
365
+
366
+ export interface ProgramOptions {
367
+ /** The program label in the Symptoms and Monitoreo bases. Defaults to `auna`. */
368
+ source?: string;
369
+ /** The program label in the Config base. Defaults to `auna`. */
370
+ configSource?: string;
371
+ }
372
+
373
+ export interface RecommendationRecoveryOptions {
374
+ enabled: boolean;
375
+ intervalMs?: number;
376
+ }
377
+
378
+ export interface ReviewDraftsOptions {
379
+ enabled?: boolean;
380
+ intervalMs?: number;
381
+ }
382
+
383
+ export interface ReviewAlertsOptions {
384
+ enabled?: boolean;
385
+ intervalMs?: number;
386
+ }
387
+
388
+ export interface InboundRecoveryOptions {
389
+ enabled: boolean;
390
+ intervalMs?: number;
320
391
  }
321
392
 
322
393
  export interface NerEntity {
@@ -333,9 +404,13 @@ declare module '@peopl-health/nexus' {
333
404
  setHandlers(handlers: MessageHandlers): void;
334
405
  sendMessage(messageData: MessageData): Promise<any>;
335
406
  sendScheduledMessage(scheduledMessage: ScheduledMessage): Promise<void>;
336
- processMessage(rawMessage: any): Promise<any>;
407
+ processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
408
+ processMessage(rawMessage: any, options?: IncomingMessageOptions): Promise<any>;
337
409
  isConnected(): boolean;
338
- disconnect(): Promise<void>;
410
+ beginDrain(): void;
411
+ isDraining(): boolean;
412
+ shutdown(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
413
+ disconnect(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
339
414
  getMessaging(): NexusMessaging;
340
415
  getStorage(): MongoStorage | null;
341
416
  getMessageParser(): MessageParser | null;
@@ -347,7 +422,6 @@ declare module '@peopl-health/nexus' {
347
422
  export function calculateDelay(sendTime: string | Date, timeZone?: string): number;
348
423
  export function ensureWhatsAppFormat(code: any): string | null;
349
424
  export function convertTwilioToInternalFormat(twilioMessage: any): any;
350
- export function downloadMediaFromTwilio(mediaUrl: string, credentials: any): Promise<Buffer>;
351
425
  export function getMediaTypeFromContentType(contentType: string): string;
352
426
  export function extractTitle(message: any, mediaType: string): string | null;
353
427
  export function useMongoDBAuthState(uri: string, dbName: string, sessionId: string): Promise<any>;
@@ -360,16 +434,209 @@ declare module '@peopl-health/nexus' {
360
434
  export function setModelDatabase(modelName: string, dbName: string): void;
361
435
  export function getModelDatabase(modelName: string): string | null;
362
436
 
437
+ export interface ContextSyncOptions {
438
+ dryRun?: boolean;
439
+ limit?: number;
440
+ patientScope?: (patientId: string) => boolean;
441
+ }
442
+
443
+ export interface ContextSyncResult {
444
+ ok: boolean;
445
+ reason?: string;
446
+ dryRun?: boolean;
447
+ scanned?: number;
448
+ planned?: number;
449
+ written?: number;
450
+ retracted?: number;
451
+ failed?: number;
452
+ advanced?: boolean;
453
+ reconciling?: boolean;
454
+ missingCreatedTime?: number;
455
+ patients?: number;
456
+ unreadable?: number;
457
+ stats?: Record<string, number>;
458
+ watermark?: Date | null;
459
+ }
460
+
461
+ export interface ClinicalContextSyncResult {
462
+ ok: boolean;
463
+ facts: ContextSyncResult;
464
+ legacy: ContextSyncResult | null;
465
+ /** The regimen closer's counts, without the per-patient list; null while REGIMEN_CLOSER_WRITE_LIVE is off. */
466
+ closer: Omit<RegimenCloserResult, 'patients'> | null;
467
+ }
468
+
469
+ export function syncContextFacts(options?: ContextSyncOptions): Promise<ContextSyncResult>;
470
+ export function syncLegacyContext(options?: Omit<ContextSyncOptions, 'limit'>): Promise<ContextSyncResult>;
471
+ export function syncClinicalContext(options?: Omit<ContextSyncOptions, 'limit'>): Promise<ClinicalContextSyncResult>;
472
+
473
+ export interface OutreachBrief {
474
+ reason?: string | null;
475
+ lastTriageAt?: string | null;
476
+ maxGrade?: number | null;
477
+ positiveSymptoms?: string[];
478
+ lastInboundAt?: string | null;
479
+ lastOutboundAt?: string | null;
480
+ lastOutreach?: string | null;
481
+ checkIn?: { type: string; reminderId?: string | null; planId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
482
+ recentCheckIns?: string[];
483
+ exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
484
+ asOf?: string | null;
485
+ }
486
+
487
+ export interface CheckInDueResult {
488
+ decision: 'write' | 'hold' | 'skipped';
489
+ holdReason: string | null;
490
+ nextCheckAt?: string | null;
491
+ sent: boolean;
492
+ }
493
+
494
+ export interface OutreachDecision {
495
+ /** 'skipped' when the turn never ran — superseded, or dropped by a preProcess hook. */
496
+ decision: 'write' | 'hold' | 'skipped';
497
+ rationale: string;
498
+ holdReason: string | null;
499
+ nextCheckAt: string | null;
500
+ /** Drafted patient-facing text. Present only on a dry run. */
501
+ draft?: string | null;
502
+ /** Why the out-of-window template would refuse the draft. Present only on a dry run. */
503
+ carrierRejection?: string | null;
504
+ /** Whether the provider accepted the fixed-template send. This is not proof of delivery. */
505
+ accepted?: boolean;
506
+ /** Whether the provider status is already terminal delivered/read. */
507
+ delivered: boolean;
508
+ deliveryStatus?: string | null;
509
+ /** True only when downstream work remains queued. */
510
+ deferred?: boolean;
511
+ turnId: string | null;
512
+ traceId: string | null;
513
+ }
514
+
515
+ export interface ScheduledFollowUpResult {
516
+ decision: 'write' | 'skipped';
517
+ holdReason: string | null;
518
+ accepted: boolean;
519
+ delivered: boolean;
520
+ deliveryStatus?: string | null;
521
+ deferred?: boolean;
522
+ idempotent?: boolean;
523
+ retired?: boolean;
524
+ }
525
+
526
+ export interface OutreachSweepResult {
527
+ ran: boolean;
528
+ weekday: number;
529
+ mode?: 'continuity' | 'monday_triage_recovery';
530
+ source?: 'weekly' | 'patient_scope';
531
+ targetDays?: string[];
532
+ dryRun?: boolean;
533
+ counts: Record<string, number>;
534
+ rejectedBy?: Record<string, number>;
535
+ decisions?: Array<Record<string, any>>;
536
+ }
537
+
538
+ export function runProactiveOutreachSweep(options?: {
539
+ now?: Date;
540
+ dryRun?: boolean;
541
+ limit?: number;
542
+ concurrency?: number;
543
+ patientScope?: string[] | null;
544
+ /** Dry-run-only: skips the prior-sweep, recent-outbound, recent-activity, inactivity, outreach-cooldown and unanswered-outreach guards; keeps the ops opt-out and the pending-reminder collision guard. Shows a wider cohort than a live run admits. */
545
+ includePreviouslySwept?: boolean;
546
+ /** continuity, or the Monday weekly-triage completion recovery lane. */
547
+ mode?: 'continuity' | 'monday_triage_recovery';
548
+ /** daily: patients inactive for 7+ days. legacy: the Thursday/Saturday post-triage cohort (Mon/Tue and Wed/Thu triages). */
549
+ cadence?: 'daily' | 'legacy';
550
+ /** weekly: the triage questionnaire view. patient_scope: the scoped patients outside that view; requires continuity, daily and a patientScope. */
551
+ source?: 'weekly' | 'patient_scope';
552
+ }): Promise<OutreachSweepResult>;
553
+
554
+ export interface ContextFactRow {
555
+ variableId: string;
556
+ value?: unknown;
557
+ status?: string | null;
558
+ validTime?: string | Date | null;
559
+ /** Set by currentRegimen on an oral fact over 90 days old: kept, but not confirmed as current. */
560
+ unconfirmed?: boolean;
561
+ [key: string]: any;
562
+ }
563
+
564
+ export interface UnitRegimen {
565
+ /** May be empty; each drug appears once. */
566
+ drugs: string[];
567
+ since: string | null;
568
+ lastApplication: string;
569
+ nextSession: string | null;
570
+ /** false when the unit's last application is over 100 days ago and no session is scheduled: the regimen is history, not treatment. */
571
+ current: boolean;
572
+ }
573
+
574
+ export interface ChemoContext {
575
+ ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
576
+ esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
577
+ inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
578
+ proximaSesion: { fecha: string; tipo: string; confirmada?: boolean; hora?: string | null } | null;
579
+ esquemaPrevio: { farmacos: string[]; hasta: string } | null;
580
+ [key: string]: any;
581
+ }
582
+
583
+ /** The chemo unit's record for a patient: null when there is none, undefined when it cannot be read. */
584
+ export function readRecordedChemo(code: string): Promise<ChemoContext | null | undefined>;
585
+
586
+ /**
587
+ * Narrows context-fact rows to the current treatment, preferring the chemo unit's regimen for infused drugs.
588
+ * `today` is a Mexico-time YYYY-MM-DD day. `source` is 'unreadable' when `chemo` is undefined; the facts are still narrowed.
589
+ * Oral facts are always kept (`unconfirmed` past 90 days). Without a unit record, infused and radiotherapy facts are kept within
590
+ * 60 days of the newest treatment fact of any kind. Statuses are not filtered: callers choose which to show.
591
+ */
592
+ export function currentRegimen(input: { chemo: ChemoContext | null | undefined; facts: ContextFactRow[] | null | undefined; today?: string }): {
593
+ source: 'unit' | 'facts' | 'unreadable' | 'none';
594
+ unit: UnitRegimen | null;
595
+ facts: ContextFactRow[];
596
+ };
597
+
598
+ export interface RegimenClosure {
599
+ conceptKey: string;
600
+ concept: string | null;
601
+ drug: string;
602
+ status: string | null;
603
+ since: string;
604
+ proposedStatus: 'stopped';
605
+ endDate: string;
606
+ endFrom: 'esquemaPrevio' | 'inicioEsquema';
607
+ evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
608
+ }
609
+
610
+ export interface RegimenCloserResult {
611
+ ok: boolean;
612
+ dryRun: boolean;
613
+ closures: number;
614
+ written: number;
615
+ failed: number;
616
+ unreadable: number;
617
+ reason?: string;
618
+ skipped: Record<string, number>;
619
+ patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
620
+ }
621
+
622
+ /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
623
+ export function dryRunRegimenClosures(options?: { today?: string }): Promise<RegimenCloserResult>;
624
+
625
+ /** Writes those closures as `stopped` facts (source `unit`, validTime = end date); a dry run unless `dryRun: false` with a `patientScope`. */
626
+ export function closeStoppedRegimens(options?: { dryRun?: boolean; patientScope?: (patientId: string) => boolean; today?: string }): Promise<RegimenCloserResult>;
627
+
363
628
  export const routes: any;
364
629
  export function setupDefaultRoutes(app: any): void;
365
630
  export function createRouter(routeDefinitions: Record<string, string>, controllers: Record<string, Function>): any;
366
631
 
367
632
  // Queue Adapters
368
633
  export interface QueueJobOptions {
634
+ jobId?: string;
369
635
  priority?: number;
370
636
  delay?: number;
371
637
  attempts?: number;
372
638
  backoff?: { type: 'fixed' | 'exponential'; delay: number };
639
+ repeat?: { cron: string; tz?: string };
373
640
  }
374
641
 
375
642
  export interface QueueJobStatus {
@@ -379,6 +646,7 @@ declare module '@peopl-health/nexus' {
379
646
  }
380
647
 
381
648
  export abstract class QueueAdapter {
649
+ readonly supportsRepeat: boolean;
382
650
  constructor(config?: any);
383
651
  abstract enqueue(jobType: string, payload: any, options?: QueueJobOptions): Promise<string>;
384
652
  abstract process(jobType: string, handler: (payload: any) => Promise<any>): Promise<void>;
@@ -420,16 +688,17 @@ declare module '@peopl-health/nexus' {
420
688
  export interface Workflow {
421
689
  kind: string;
422
690
  dedupeKey: (trigger: any) => string;
423
- prepare: (trigger: any) => Promise<any>;
691
+ prepare: (trigger: any, checkpoints?: any, save?: (patch: any) => Promise<void>) => Promise<any>;
692
+ retrySchedule?: number[];
424
693
  }
425
694
 
426
695
  export interface WorkflowRunner {
427
696
  register(workflow: Workflow): Promise<Workflow>;
428
- enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string>;
697
+ enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string | null>;
698
+ sweep(only?: string[]): Promise<string[]>;
699
+ stop(): void;
429
700
  }
430
701
 
431
- export function createWorkflowRunner(options: { queueAdapter: QueueAdapter }): WorkflowRunner;
432
-
433
702
  // Memory System
434
703
  export interface PatientMemoryDocument {
435
704
  _id: any;
@@ -462,6 +731,7 @@ declare module '@peopl-health/nexus' {
462
731
  export interface ClinicalDataResult {
463
732
  clinicalContext: string;
464
733
  lastSymptoms: string;
734
+ nutritionPlan?: string;
465
735
  patientMemories?: string;
466
736
  conversationSummaries?: string;
467
737
  }
@@ -556,15 +826,528 @@ declare module '@peopl-health/nexus' {
556
826
  export function getPatientMemory(): any;
557
827
  export function getConversationSummary(): any;
558
828
 
829
+ export type SupportService = 'nutrition' | 'psychology';
830
+ export type SupportDisposition = 'group' | 'individual' | 'escalated' | 'reviewRequired' | 'none';
831
+ export type SupportPriority = 'routine' | 'soon' | 'urgent';
832
+ export type SupportInvitationClass = 'first' | 'followup';
833
+ export type SupportDeliveryStatus = 'sent' | 'delivered' | 'read' | 'failed' | 'unknown';
834
+ export type SupportEngagementState = 'notInvited' | 'invited' | 'registered' | 'attended' | 'declined';
835
+
836
+ export interface SupportEvidenceInput {
837
+ source: 'triage' | 'chat' | 'fhir' | 'airtable';
838
+ sourceId: string;
839
+ code: string;
840
+ summary?: string | null;
841
+ confidence?: number | null;
842
+ }
843
+
844
+ export interface SupportEvidence extends SupportEvidenceInput {
845
+ key?: string;
846
+ summary: string | null;
847
+ confidence: number | null;
848
+ }
849
+
850
+ export interface SupportSafety {
851
+ suicidalIdeation?: boolean;
852
+ immediateRisk?: boolean;
853
+ urgentMedicalRisk?: boolean;
854
+ needsHumanConfirmation?: boolean;
855
+ }
856
+
857
+ export interface SupportRoutingDecisionBaseInput {
858
+ disposition: SupportDisposition;
859
+ groupEligible: boolean;
860
+ priority?: SupportPriority;
861
+ confidence: number;
862
+ reasonCodes?: string[];
863
+ evidence: SupportEvidenceInput[];
864
+ safety: SupportSafety;
865
+ }
866
+
867
+ export type SupportRoutingDecisionInput = SupportRoutingDecisionBaseInput & ({
868
+ service: 'nutrition';
869
+ nutritionRisk: 'green' | 'yellow' | 'red' | 'unknown';
870
+ urgentIntakeEligible: boolean;
871
+ } | {
872
+ service: 'psychology';
873
+ psychologyRisk: 'green' | 'orange' | 'red' | 'unknown';
874
+ });
875
+
876
+ export interface SupportRoutingRecommendationInput {
877
+ schemaVersion?: string;
878
+ decisionVersion?: string;
879
+ patientId: string;
880
+ origin: 'triage' | 'chat' | 'fhir';
881
+ sourceId: string;
882
+ createdAt: string;
883
+ decisions: SupportRoutingDecisionInput[];
884
+ }
885
+
886
+ export interface SupportCandidateRecord {
887
+ candidateId: string;
888
+ patientId: string;
889
+ service: SupportService;
890
+ disposition: SupportDisposition;
891
+ groupEligible: boolean;
892
+ urgentIntakeEligible: boolean;
893
+ priority: SupportPriority;
894
+ confidence?: number;
895
+ nutritionRisk?: 'green' | 'yellow' | 'red' | 'unknown' | null;
896
+ psychologyRisk?: 'green' | 'orange' | 'red' | 'unknown' | null;
897
+ reasonCodes?: string[];
898
+ evidence?: SupportEvidence[];
899
+ sourceEventIds?: string[];
900
+ activeInvitationKey?: string | null;
901
+ cooldownInvitationKey?: string | null;
902
+ revision?: number;
903
+ [key: string]: unknown;
904
+ }
905
+
906
+ export interface SupportActionRecord {
907
+ candidateId: string;
908
+ service: SupportService;
909
+ type: 'group_registration' | 'urgent_nutrition_intake';
910
+ invitationClass: SupportInvitationClass | null;
911
+ idempotencyKey?: string | null;
912
+ targetKey: string;
913
+ priority: SupportPriority;
914
+ }
915
+
916
+ export interface SupportActionResult {
917
+ schemaVersion: '1';
918
+ patientId: string;
919
+ sourceId: string;
920
+ actions: SupportActionRecord[];
921
+ }
922
+
923
+ export interface SupportDeliveryContext {
924
+ invitationClassByService?: Partial<Record<SupportService, SupportInvitationClass>>;
925
+ targetKeyByService?: Partial<Record<SupportService, string>>;
926
+ attendanceEvidenceByService?: Partial<Record<SupportService, {
927
+ patientId: string;
928
+ service: SupportService;
929
+ evidenceId: string;
930
+ }>>;
931
+ }
932
+
933
+ export interface SupportDashboardMetric {
934
+ records: Array<Record<string, unknown>>;
935
+ indicator: number;
936
+ sample: number;
937
+ total: number;
938
+ struct: string[];
939
+ }
940
+
941
+ export interface SupportDashboardSnapshot {
942
+ generatedAt: string;
943
+ metrics: { exceptions: SupportDashboardMetric };
944
+ }
945
+
946
+ export type SupportDashboardCandidateRecord = Pick<SupportCandidateRecord,
947
+ 'candidateId' | 'patientId' | 'service' | 'disposition'
948
+ > & Partial<SupportCandidateRecord>;
949
+
950
+ export function registerDashboardProvider(
951
+ source: 'auna.support.v1',
952
+ provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
953
+ ): void;
954
+
955
+ export type ContactCategory = 'clinical' | 'triage' | 'sessions' | 'followup' | 'invitations' | 'unclassified';
956
+
957
+ /** What sendMessage returns when the contact gate holds a send back; it never reached the provider. */
958
+ export interface ContactCappedSendResult {
959
+ success: false;
960
+ messageId: null;
961
+ status: 'contact_capped';
962
+ reason: 'outside_hours' | 'daily_cap' | 'weekly_cap';
963
+ category: ContactCategory;
964
+ delivered: false;
965
+ deferred: false;
966
+ }
967
+
968
+ export function registerContactCategories(categories: {
969
+ contentSids?: Record<string, ContactCategory>;
970
+ triggeredBy?: Record<string, ContactCategory>;
971
+ }): void;
972
+
973
+ export const supportCandidateService: {
974
+ updateSupportOperationalReview(request: {
975
+ patientId: string;
976
+ service: SupportService;
977
+ reasonCode: 'classification_failed' | 'attendance_unavailable' | 'safety_unconfirmed' | 'classification_safety_unconfirmed' | 'invitation_claim_failed';
978
+ sourceId: string;
979
+ resolved?: boolean;
980
+ noClinicalDecision?: boolean;
981
+ now?: Date;
982
+ }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
983
+ readSupportDashboardCandidates(options?: { limit?: number }): Promise<SupportDashboardCandidateRecord[]>;
984
+ readSupportDashboardCandidate(candidateId: string): Promise<SupportDashboardCandidateRecord | null>;
985
+ DASHBOARD_READ_LIMIT: number;
986
+ approveCandidate(candidateId: string, options: {
987
+ reviewedRevision: number;
988
+ reviewedRisk: 'green' | 'yellow';
989
+ Model?: unknown;
990
+ }): Promise<SupportCandidateRecord | null>;
991
+ candidatePatch(existing: SupportCandidateRecord | null | undefined, recommendation: SupportRoutingRecommendationInput, decision: SupportRoutingDecisionInput): Partial<SupportCandidateRecord>;
992
+ claimInvitation(request: {
993
+ candidateId: string;
994
+ invitationClass: SupportInvitationClass;
995
+ invitationCycle: string;
996
+ templateVersion: string;
997
+ now?: Date;
998
+ }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
999
+ clearCandidateEscalation(candidateId: string, options: {
1000
+ reviewedRevision: number;
1001
+ approvedForGroup?: boolean;
1002
+ reviewedRisk?: 'green' | 'yellow';
1003
+ Model?: unknown;
1004
+ }): Promise<SupportCandidateRecord | null>;
1005
+ evidenceKey(item: Pick<SupportEvidence, 'source' | 'sourceId' | 'code'>): string;
1006
+ initialState(decision: SupportRoutingDecisionInput): SupportDisposition;
1007
+ markCandidateAccepted(request: { patientId: string; service: SupportService; sessionId?: string | null }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1008
+ markCandidateDeclined(request: { patientId: string; service: SupportService; preference?: 'another_date' | 'not_now' | 'never' }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1009
+ nextState(existing: SupportCandidateRecord | null | undefined, decision: SupportRoutingDecisionInput): SupportDisposition;
1010
+ normalizeEvidence(items?: SupportEvidenceInput[]): Array<SupportEvidence & { key: string }>;
1011
+ recordEngagement(request: {
1012
+ patientId: string;
1013
+ service: SupportService;
1014
+ state: SupportEngagementState;
1015
+ evidenceId?: string | null;
1016
+ occurredAt?: string | Date | null;
1017
+ preference?: 'another_date' | 'not_now' | 'never' | null;
1018
+ }, options?: { Model?: unknown; historicalAttendance?: boolean }): Promise<SupportCandidateRecord | null>;
1019
+ recordLegacyInvitationResponse(request: {
1020
+ patientId: string;
1021
+ service: SupportService;
1022
+ outcome: 'accepted' | 'declined';
1023
+ sessionId?: string | null;
1024
+ preference?: 'another_date' | 'not_now' | 'never';
1025
+ }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1026
+ recordSentInvitationResponse(request: {
1027
+ patientId: string;
1028
+ service: SupportService;
1029
+ outcome: 'accepted' | 'declined';
1030
+ sessionId?: string | null;
1031
+ preference?: 'another_date' | 'not_now' | 'never';
1032
+ }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1033
+ recordSupportRoutingRecommendation(recommendation: SupportRoutingRecommendationInput, options?: { Model?: unknown }): Promise<SupportCandidateRecord[]>;
1034
+ rescheduleDeclinedCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1035
+ settleInvitation(request: {
1036
+ candidateId: string;
1037
+ idempotencyKey: string;
1038
+ status: SupportDeliveryStatus;
1039
+ providerMessageId?: string | null;
1040
+ error?: string | null;
1041
+ now?: Date;
1042
+ }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
1043
+ };
1044
+
1045
+ export const supportActionService: {
1046
+ prepareSupportAction(request: {
1047
+ patientId: string;
1048
+ sourceId: string;
1049
+ candidates?: SupportCandidateRecord[];
1050
+ resolveDeliveryContext?: (context: {
1051
+ patientId: string;
1052
+ candidates: SupportCandidateRecord[];
1053
+ }) => SupportDeliveryContext | Promise<SupportDeliveryContext>;
1054
+ now?: Date;
1055
+ }, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
1056
+ };
1057
+
1058
+ export type SupportLightColor = 'green' | 'yellow' | 'orange' | 'red' | 'unknown';
1059
+ export type SupportLightSource = 'ai' | 'human';
1060
+ export type SupportLightOutcome = 'applied' | 'pending' | 'withdrawn' | 'unchanged';
1061
+ export type CollectiveRefusal = 'light_red' | 'light_orange' | 'light_unconfirmed' | 'invitation_paused' | 'individual_therapy'
1062
+ | 'already_invited_this_week' | 'weekly_limit' | 'no_capacity';
1063
+
1064
+ export interface SupportLightEvidence {
1065
+ source: 'triage' | 'chat' | 'specialist' | 'sweep';
1066
+ sourceId: string;
1067
+ summary?: string | null;
1068
+ }
1069
+
1070
+ export interface SupportLightRecord {
1071
+ patientId: string;
1072
+ service: SupportService;
1073
+ color: SupportLightColor;
1074
+ source: SupportLightSource;
1075
+ setBy: string;
1076
+ setAt: Date;
1077
+ evidence: SupportLightEvidence[];
1078
+ reason: string | null;
1079
+ pendingImprovement: {
1080
+ color: SupportLightColor;
1081
+ proposedBy: string;
1082
+ proposedAt: Date;
1083
+ evidence: SupportLightEvidence[];
1084
+ reason: string | null;
1085
+ } | null;
1086
+ revision: number;
1087
+ }
1088
+
1089
+ export type SupportLightBoardRecord = Omit<SupportLightRecord, 'evidence' | 'pendingImprovement'> & {
1090
+ pendingImprovement: Omit<NonNullable<SupportLightRecord['pendingImprovement']>, 'evidence'> | null;
1091
+ };
1092
+
1093
+ export interface SupportLightEventRecord {
1094
+ patientId: string;
1095
+ service: SupportService;
1096
+ outcome: 'applied' | 'pending' | 'withdrawn' | 'accepted' | 'rejected';
1097
+ from: SupportLightColor | null;
1098
+ to: SupportLightColor;
1099
+ source: SupportLightSource;
1100
+ actor: string;
1101
+ evidence: SupportLightEvidence[];
1102
+ reason: string | null;
1103
+ revision: number;
1104
+ at: Date;
1105
+ }
1106
+
1107
+ export const supportLightService: {
1108
+ applySupportLight(request: {
1109
+ patientId: string;
1110
+ service: SupportService;
1111
+ color: SupportLightColor;
1112
+ source: SupportLightSource;
1113
+ actor?: string | null;
1114
+ evidence?: SupportLightEvidence[];
1115
+ reason?: string | null;
1116
+ now?: Date;
1117
+ reviewedRevision?: number | null;
1118
+ }, options?: { Model?: unknown; EventModel?: unknown }): Promise<{ light: SupportLightRecord | null; outcome: SupportLightOutcome | 'stale' }>;
1119
+ resolvePendingImprovement(request: {
1120
+ patientId: string;
1121
+ service: SupportService;
1122
+ isAccepted: boolean;
1123
+ actor: string;
1124
+ reviewedRevision: number;
1125
+ now?: Date;
1126
+ }, options?: { Model?: unknown; EventModel?: unknown }): Promise<SupportLightRecord | null>;
1127
+ readSupportLights(patientId: string, options?: { Model?: unknown }): Promise<SupportLightRecord[]>;
1128
+ readSupportLightBoard(filters?: {
1129
+ service?: SupportService | null;
1130
+ color?: SupportLightColor | null;
1131
+ isPendingOnly?: boolean;
1132
+ }, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
1133
+ readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
1134
+ readSupportLightEvents(filters: {
1135
+ since: Date | string;
1136
+ service?: SupportService | null;
1137
+ outcome?: SupportLightEventRecord['outcome'] | null;
1138
+ to?: SupportLightColor | null;
1139
+ }, options?: { limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
1140
+ applyChatSupportReadings(recommendation: Pick<SupportRoutingRecommendationInput, 'patientId' | 'decisions'>, options?: { acceptedServices?: SupportService[] | null; isTurnLive?: () => boolean; now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
1141
+ service: SupportService;
1142
+ color: SupportLightColor;
1143
+ outcome: SupportLightOutcome | 'stale' | 'error';
1144
+ revision: number | null;
1145
+ }>>;
1146
+ };
1147
+
1148
+ export const supportInvitability: {
1149
+ LIGHT_SCALE: Readonly<Record<SupportService, readonly SupportLightColor[]>>;
1150
+ GROUP_INVITABLE: readonly Readonly<Record<string, unknown>>[];
1151
+ isSafeGroupCandidate(candidate: Partial<SupportCandidateRecord>): boolean;
1152
+ nextLight(
1153
+ current: { color?: SupportLightColor | null; pendingImprovement?: { color: SupportLightColor } | null } | null | undefined,
1154
+ proposal: { service: SupportService; color: SupportLightColor; source: SupportLightSource },
1155
+ ): { outcome: SupportLightOutcome; color?: SupportLightColor; source?: SupportLightSource; pendingImprovement?: { color: SupportLightColor } | null };
1156
+ collectiveOffer(request: {
1157
+ service: SupportService;
1158
+ color?: SupportLightColor;
1159
+ isInvitationPaused?: boolean;
1160
+ hasInvitationThisWeek?: boolean;
1161
+ collectivesThisWeek?: number;
1162
+ hasCapacity?: boolean;
1163
+ isInIndividualTherapy?: boolean;
1164
+ psychologyColor?: SupportLightColor;
1165
+ }): { allowed: boolean; reason: CollectiveRefusal | null };
1166
+ supportWeek(date: Date | string): string | null;
1167
+ };
1168
+
1169
+ export interface SupportLightSweepChange {
1170
+ patientId: string;
1171
+ service: SupportService;
1172
+ outcome: SupportLightOutcome;
1173
+ color: SupportLightColor;
1174
+ revision: number | null;
1175
+ }
1176
+
1177
+ export const supportLightEvaluationService: {
1178
+ evaluatePatientSupport(request: {
1179
+ patientId: string;
1180
+ now?: Date;
1181
+ windowDays?: number;
1182
+ }, options?: { provider?: unknown; getConfig?: unknown; readMessages?: unknown; applyLight?: unknown }): Promise<{
1183
+ outcome: 'evaluated' | 'partial' | 'not_configured' | 'no_messages' | 'incomplete' | 'unparseable';
1184
+ changes?: Omit<SupportLightSweepChange, 'patientId'>[];
1185
+ }>;
1186
+ runSupportLightSweep(request?: {
1187
+ now?: Date;
1188
+ patientIds?: string[] | null;
1189
+ scope?: string[] | null;
1190
+ cadenceHours?: number;
1191
+ activeWithinHours?: number;
1192
+ windowDays?: number;
1193
+ limit?: number;
1194
+ }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
1195
+ outcome: 'completed' | 'incomplete' | 'not_configured';
1196
+ evaluated: number;
1197
+ partial: number;
1198
+ busy: number;
1199
+ skipped: number;
1200
+ failed: number;
1201
+ changes: SupportLightSweepChange[];
1202
+ }>;
1203
+ };
1204
+
559
1205
  // BatchingManager — per-chatId concurrency control
560
1206
  export interface BatchingConfig {
561
1207
  enabled?: boolean;
562
1208
  abortOnNewMessage?: boolean;
563
1209
  immediateRestart?: boolean;
564
1210
  typingIndicator?: boolean;
1211
+ instructionSettleMs?: number;
565
1212
  hooks?: Record<string, Function | Function[]>;
566
1213
  }
567
1214
 
1215
+ export type NutritionSafetyFindingCode =
1216
+ | 'cannot_eat'
1217
+ | 'cannot_keep_fluids'
1218
+ | 'bleeding'
1219
+ | 'severe_abdominal_pain';
1220
+ export type NutritionSafetyFindingValue = 'yes' | 'no' | 'unknown';
1221
+ export type NutritionSafetyQuestionCode =
1222
+ | 'can_eat'
1223
+ | 'can_keep_fluids'
1224
+ | 'bleeding'
1225
+ | 'severe_abdominal_pain';
1226
+ export type NutritionSafetyEvidenceSourceType = 'chat' | 'flow' | 'historical' | 'forecast';
1227
+ export type NutritionSafetyDisposition = 'clear' | 'clarify' | 'escalate' | 'review_required';
1228
+
1229
+ export interface NutritionSafetyEvidenceRefInput {
1230
+ finding: NutritionSafetyFindingCode;
1231
+ source_type: NutritionSafetyEvidenceSourceType;
1232
+ source_id: string;
1233
+ observed_at: string;
1234
+ }
1235
+
1236
+ export interface NutritionSafetyEvidenceRef {
1237
+ finding: NutritionSafetyFindingCode;
1238
+ sourceType: NutritionSafetyEvidenceSourceType;
1239
+ sourceId: string;
1240
+ observedAt: string;
1241
+ traceId?: string;
1242
+ }
1243
+
1244
+ export interface NutritionSafetyDecisionInput {
1245
+ submission_revision: number;
1246
+ screen_revision: number;
1247
+ findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
1248
+ evidence_refs: NutritionSafetyEvidenceRefInput[];
1249
+ questions_needed: NutritionSafetyQuestionCode[];
1250
+ disposition: NutritionSafetyDisposition;
1251
+ }
1252
+
1253
+ export class NutritionSafetyDecision {
1254
+ constructor(payload: NutritionSafetyDecisionInput);
1255
+ submissionRevision: number;
1256
+ screenRevision: number;
1257
+ findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
1258
+ evidenceRefs: NutritionSafetyEvidenceRef[];
1259
+ questionsNeeded: NutritionSafetyQuestionCode[];
1260
+ disposition: NutritionSafetyDisposition;
1261
+ }
1262
+
1263
+ export interface NutritionSafetyDeliveryDirective {
1264
+ operationId: string;
1265
+ body: string;
1266
+ }
1267
+
1268
+ export interface NutritionSafetyCommitRequest {
1269
+ decision: NutritionSafetyDecision;
1270
+ patientCode: string;
1271
+ turnId: string;
1272
+ traceId: string;
1273
+ sourceId: string;
1274
+ observedAt: string;
1275
+ }
1276
+
1277
+ export interface NutritionSafetyCommitResult {
1278
+ outcome: string;
1279
+ status?: string;
1280
+ screen?: { status: string; [key: string]: any };
1281
+ questionsNeeded?: NutritionSafetyQuestionCode[];
1282
+ questions_needed?: NutritionSafetyQuestionCode[];
1283
+ deliveryDirective?: NutritionSafetyDeliveryDirective;
1284
+ }
1285
+
1286
+ export interface NutritionSafetyRepository {
1287
+ commitDecision(request: NutritionSafetyCommitRequest): Promise<NutritionSafetyCommitResult>;
1288
+ claimDelivery?(request: {
1289
+ operationId: string;
1290
+ patientCode: string;
1291
+ turnId: string;
1292
+ traceId: string | null;
1293
+ sourceId: string | null;
1294
+ }): Promise<{ acquired: boolean }>;
1295
+ settleDelivery?(request: {
1296
+ operationId: string;
1297
+ outcome: 'sent' | 'known_not_sent' | 'unknown';
1298
+ providerMessageId: string | null;
1299
+ patientCode: string;
1300
+ turnId: string | null;
1301
+ traceId: string | null;
1302
+ }): Promise<boolean | void>;
1303
+ }
1304
+
1305
+ export interface ToolRuntimeRepositories {
1306
+ nutritionSafety?: NutritionSafetyRepository;
1307
+ [key: string]: any;
1308
+ }
1309
+
1310
+ export const FINDING_CODES: readonly NutritionSafetyFindingCode[];
1311
+ export const FINDING_VALUES: readonly NutritionSafetyFindingValue[];
1312
+ export const FINDING_TO_QUESTION: Readonly<Record<NutritionSafetyFindingCode, NutritionSafetyQuestionCode>>;
1313
+ export const QUESTION_CODES: readonly NutritionSafetyQuestionCode[];
1314
+ export const EVIDENCE_SOURCE_TYPES: readonly NutritionSafetyEvidenceSourceType[];
1315
+ export const DISPOSITIONS: readonly NutritionSafetyDisposition[];
1316
+
1317
+ export interface NexusMessagingConfig {
1318
+ messageBatching?: BatchingConfig;
1319
+ assistant?: {
1320
+ mode?: 'local' | 'queue';
1321
+ toolRuntimeRepos?: ToolRuntimeRepositories;
1322
+ [key: string]: any;
1323
+ };
1324
+ [key: string]: any;
1325
+ }
1326
+
1327
+ export interface DrainResult {
1328
+ drained: boolean;
1329
+ waitedMs: number;
1330
+ abandoned: Array<{ chatId: string | null; runId: string }>;
1331
+ }
1332
+
1333
+ export interface TurnAdmission {
1334
+ accepted: boolean;
1335
+ reason?: string;
1336
+ }
1337
+
1338
+ export interface ShutdownOptions {
1339
+ drainMs?: number;
1340
+ abortGraceMs?: number;
1341
+ teardownMs?: number;
1342
+ sweepStopMs?: number;
1343
+ closeStorage?: boolean;
1344
+ }
1345
+
1346
+ export class DrainingError extends Error {
1347
+ constructor(chatId: string);
1348
+ code: 'draining';
1349
+ }
1350
+
568
1351
  export class BatchingManager {
569
1352
  constructor(options: {
570
1353
  provider?: MessageProvider;
@@ -573,16 +1356,21 @@ declare module '@peopl-health/nexus' {
573
1356
  setProvider(provider: MessageProvider): void;
574
1357
  isProcessing(chatId: string): boolean;
575
1358
  isActiveRun(chatId: string, runId: string): boolean;
1359
+ isDraining(): boolean;
1360
+ getAbortSignal(runId: string): AbortSignal | undefined;
1361
+ drain(options?: { timeoutMs?: number; abortGraceMs?: number }): Promise<DrainResult>;
576
1362
  handleBatchedProcessing(
577
1363
  chatId: string,
578
1364
  processingFn: (runId: string) => Promise<any>,
579
- sendResponseFn: (result: any) => Promise<void>
580
- ): Promise<void>;
1365
+ sendResponseFn: (result: any) => Promise<void>,
1366
+ discardResponseFn?: (result: any) => Promise<void>
1367
+ ): Promise<TurnAdmission>;
581
1368
  enqueueProcessing(
582
1369
  chatId: string,
583
1370
  processingFn: (runId: string) => Promise<any>,
584
- sendResponseFn: (result: any) => Promise<void>
585
- ): Promise<void>;
1371
+ sendResponseFn: (result: any) => Promise<void>,
1372
+ discardResponseFn?: (result: any) => Promise<void>
1373
+ ): Promise<TurnAdmission>;
586
1374
  }
587
1375
 
588
1376
  // ProcessingPipeline — hook lifecycle for all LLM operations
@@ -590,7 +1378,11 @@ declare module '@peopl-health/nexus' {
590
1378
  skip?: boolean;
591
1379
  additionalInstructions?: string;
592
1380
  additionalMessages?: Array<Record<string, any>>;
593
- toolChoice?: Record<string, any> | null;
1381
+ toolChoice?: string | Record<string, any> | null;
1382
+ /** Registered tool ids to add for this turn only. Invalid ids are ignored and the list is capped at eight. */
1383
+ additionalToolIds?: string[];
1384
+ /** Recorded on the turn trace under `signals.consumer`; cannot collide with nexus-owned keys. */
1385
+ signals?: Record<string, any>;
594
1386
  metadata?: Record<string, any>;
595
1387
  }
596
1388
 
@@ -607,21 +1399,31 @@ declare module '@peopl-health/nexus' {
607
1399
  run(
608
1400
  context: ProcessingContext,
609
1401
  executeFn: (preProcessResult: PreProcessResult, shouldContinue: () => boolean) => Promise<any>,
610
- shouldContinue?: () => boolean
1402
+ shouldContinue?: () => boolean,
1403
+ discardResult?: (result: any) => Promise<void>
611
1404
  ): Promise<any>;
612
1405
  }
613
1406
 
614
1407
  // AssistantProcessor
1408
+ export type ClinicalTurnKind = 'patient' | 'operator_instruction' | 'system' | 'proactive_outreach' | 'unknown';
1409
+
1410
+ export interface AssistantRunOptions {
1411
+ [key: string]: any;
1412
+ turnKind?: ClinicalTurnKind;
1413
+ }
1414
+
615
1415
  export interface AssistantProcessorConfig {
616
1416
  mode?: 'local' | 'queue';
617
1417
  queueAdapter?: QueueAdapter;
618
1418
  sendMessage?: (messageData: MessageData) => Promise<any>;
619
1419
  storeRunMetrics?: (code: string, thread: any, result: any, timings?: Record<string, any>) => Promise<void>;
1420
+ llmMonitor?: { enqueueTurn(turnId: string): Promise<string | null> } | null;
1421
+ toolRuntimeRepos?: ToolRuntimeRepositories;
620
1422
  }
621
1423
 
622
1424
  export interface ProcessInput {
623
1425
  code: string;
624
- runOptions?: Record<string, any>;
1426
+ runOptions?: AssistantRunOptions;
625
1427
  message?: any | null;
626
1428
  }
627
1429
 
@@ -631,18 +1433,26 @@ declare module '@peopl-health/nexus' {
631
1433
  prompt?: string | null;
632
1434
  preset?: string | null;
633
1435
  response_id?: string | null;
1436
+ turnId?: string | null;
1437
+ traceId?: string | null;
634
1438
  run?: any;
635
1439
  predictionTimeMs?: number;
636
1440
  retries?: number;
637
1441
  completed?: boolean;
1442
+ /** Set when the turn never reached the model, e.g. a thread with no preset or prompt. */
1443
+ skipped?: 'no_assistant';
1444
+ /** Internal delivery ownership receipt; never contains the directive body. */
1445
+ deliveryDirective?: { operationId: string; claimed: boolean; settled: boolean };
638
1446
  }
639
1447
 
640
1448
  export class AssistantProcessor {
641
1449
  constructor(config: AssistantProcessorConfig);
642
1450
  setSendMessage(fn: AssistantProcessorConfig['sendMessage']): void;
643
1451
  resolveThread(code: string): Promise<{ thread: any; assistant: any } | null>;
644
- executeLLM(thread: any, assistant: any, runOptions?: Record<string, any>, message?: any): Promise<LLMResult>;
1452
+ executeLLM(thread: any, assistant: any, runOptions?: AssistantRunOptions, message?: any): Promise<LLMResult>;
645
1453
  process(input: ProcessInput): Promise<LLMResult | null>;
646
1454
  sendResponse(code: string, result: any): Promise<string | null>;
1455
+ discardResponse(code: string, result: any): Promise<boolean>;
647
1456
  }
1457
+
648
1458
  }