@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
@@ -33,6 +33,16 @@ class GatewayProvider extends BaseLLMProvider {
33
33
  return this._sub(vendor)._operatorInstructionTurn(additionalInstructions);
34
34
  }
35
35
 
36
+ _buildInput(config = {}) {
37
+ const { vendor } = this._route(config.modelConfig?.model);
38
+ return this._sub(vendor)._buildInput(config);
39
+ }
40
+
41
+ _orderRuntimeMessages(input, modelConfig = null) {
42
+ const { vendor } = this._route(modelConfig?.model);
43
+ return this._sub(vendor)._orderRuntimeMessages(input);
44
+ }
45
+
36
46
  _route(model) {
37
47
  if (!model) return { vendor: 'openai', model: undefined };
38
48
  const slash = model.indexOf('/');
@@ -55,7 +65,7 @@ class GatewayProvider extends BaseLLMProvider {
55
65
  sessionManager: this.sessionManager,
56
66
  });
57
67
  } catch (err) {
58
- throw new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`);
68
+ throw Object.assign(new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`), { permanent: true });
59
69
  }
60
70
  return this._subs[vendor];
61
71
  }
@@ -74,10 +84,10 @@ class GatewayProvider extends BaseLLMProvider {
74
84
  model = composed.modelConfig?.model || null;
75
85
  }
76
86
  const { vendor, model: routedModel } = this._route(model);
77
- if (vendor !== 'openai') {
78
- throw new Error(`runStructured is only supported for OpenAI models; routed model '${model}' resolved to '${vendor}'`);
87
+ if (vendor !== 'openai' && vendor !== 'anthropic') {
88
+ throw Object.assign(new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`), { permanent: true });
79
89
  }
80
- return this._sub('openai').runStructured({ ...params, model: routedModel });
90
+ return this._sub(vendor).runStructured({ ...params, model: routedModel });
81
91
  }
82
92
  }
83
93
 
@@ -7,10 +7,23 @@ const { safeParse } = require('../../utils/jsonUtils');
7
7
 
8
8
  const { logger } = require('../../utils/logger');
9
9
 
10
- const { BaseLLMProvider } = require('./BaseLLMProvider');
10
+ const runtimeConfig = require('../../config/runtimeConfig');
11
+
12
+ const { BaseLLMProvider, isSuperseded } = require('./BaseLLMProvider');
11
13
  const { handleFunctionCalls } = require('./OpenAIResponsesProviderTools');
12
14
 
13
- const DEFAULT_MAX_FUNCTION_ROUNDS = 5;
15
+ const DEFAULT_MAX_FUNCTION_ROUNDS = 12;
16
+
17
+ function resolveMaxFunctionRounds(explicit) {
18
+ if (Number.isInteger(explicit) && explicit > 0) return explicit;
19
+ const raw = runtimeConfig.get('MAX_FUNCTION_ROUNDS');
20
+ const n = parseInt(raw, 10);
21
+ if (n > 0) return n;
22
+ if (raw !== undefined) {
23
+ logger.warn('[OpenAIResponsesProvider] Invalid MAX_FUNCTION_ROUNDS, falling back to default', { value: raw, default: DEFAULT_MAX_FUNCTION_ROUNDS });
24
+ }
25
+ return DEFAULT_MAX_FUNCTION_ROUNDS;
26
+ }
14
27
 
15
28
  class OpenAIResponsesProvider extends BaseLLMProvider {
16
29
  constructor(options = {}) {
@@ -20,7 +33,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
20
33
  organization,
21
34
  client,
22
35
  defaultModels = {},
23
- maxFunctionRounds = DEFAULT_MAX_FUNCTION_ROUNDS,
36
+ maxFunctionRounds,
24
37
  } = options;
25
38
 
26
39
  if (!client && !apiKey) {
@@ -28,7 +41,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
28
41
  }
29
42
 
30
43
  this.client = client || new OpenAI({ apiKey, organization });
31
- this.maxFunctionRounds = maxFunctionRounds;
44
+ this.maxFunctionRounds = resolveMaxFunctionRounds(maxFunctionRounds);
32
45
  this.defaults = {
33
46
  responseModel: 'gpt-5',
34
47
  chatModel: 'gpt-4o-mini',
@@ -53,10 +66,10 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
53
66
  instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
54
67
  modelConfig, metadata = {}, assistant, phiProcessor = null,
55
68
  promptVariables = null, promptVersion = null, resolvedPromptId = null, resolvedPresetId = null, trace = null,
56
- shadow = false, shouldContinue = null
69
+ shadow = false, shouldContinue = null, onFirstIteration = null, isOutreach = false, signal = null
57
70
  }, options = {}) {
58
71
  const executeTools = options.toolExecutor || handleFunctionCalls;
59
- const shadowSuperseded = () => shadow && !shouldContinue();
72
+ const superseded = () => isSuperseded(shouldContinue);
60
73
  let totalRetries = 0;
61
74
  const allToolsExecuted = [];
62
75
  const allToolCalls = [];
@@ -92,8 +105,9 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
92
105
  });
93
106
  }
94
107
 
108
+ const requestOptions = signal ? { signal } : undefined;
95
109
  const makeAPICall = (inputData) => retryWithBackoff(
96
- () => this.client.responses.create({ input: inputData, ...apiCallConfig }),
110
+ () => this.client.responses.create({ input: inputData, ...apiCallConfig }, requestOptions),
97
111
  { providerName: this.constructor.name }
98
112
  );
99
113
 
@@ -103,14 +117,37 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
103
117
  let producingIteration = trace?.addIteration({ response, durationMs, apiCallConfig }) || null;
104
118
  let finalResponse = response;
105
119
 
120
+ let bridgeNote = null;
121
+ if (onFirstIteration) {
122
+ const narrationText = (response.output || [])
123
+ .filter(item => item.type === 'message')
124
+ .map(item => this._messageItemToText(item))
125
+ .filter(Boolean)
126
+ .join(' ')
127
+ .trim();
128
+ const iterationCalls = (response.output || []).filter(item => item.type === 'function_call');
129
+ const iterationToolNames = iterationCalls.map(item => item.name);
130
+ const hasToolCalls = Boolean(assistant) && iterationToolNames.length > 0;
131
+ const { text: bridgeText, reasoning: bridgeReasoning } = this._bridgeFrom(
132
+ iterationCalls.map(item => ({ name: item.name, input: safeParse(item.arguments || '{}') })));
133
+ try {
134
+ const decision = onFirstIteration({ narrationText, bridgeText, bridgeReasoning, hasToolCalls, deliveryOnly: this._isTerminalOnly(iterationToolNames) });
135
+ if (decision?.dedupNote) bridgeNote = decision.dedupNote;
136
+ } catch (err) {
137
+ logger.warn('[OpenAIResponsesProvider] bridge callback failed', { error: err.message });
138
+ }
139
+ }
140
+
106
141
  if (assistant && response.output) {
107
142
  let currentInput = [...input];
143
+ let shouldBreakForDelivery = false;
144
+ let shouldBreakForUnavailableRecovery = false;
108
145
 
109
146
  apiCallConfig.tool_choice = followUpToolChoice;
110
147
 
111
148
  for (let round = 1; round <= this.maxFunctionRounds; round++) {
112
- if (shadowSuperseded()) {
113
- logger.info('[OpenAIResponsesProvider] shadow superseded — aborting tool loop', { round });
149
+ if (superseded()) {
150
+ logger.info('[OpenAIResponsesProvider] turn superseded — aborting tool loop', { round, shadow });
114
151
  break;
115
152
  }
116
153
  const functionCalls = finalResponse.output.filter(item => item.type === 'function_call');
@@ -120,7 +157,24 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
120
157
  const { outputs, toolsExecuted } = await executeTools(functionCalls, assistant, phiProcessor, producingIteration);
121
158
 
122
159
  currentInput.push(...finalResponse.output, ...outputs);
160
+ if (bridgeNote) {
161
+ currentInput.push({ role: 'developer', content: bridgeNote });
162
+ bridgeNote = null;
163
+ }
123
164
  allToolsExecuted.push(...toolsExecuted);
165
+ const terminalOnly = this._isTerminalOnly(functionCalls.map(c => c.name));
166
+ if (terminalOnly && (isOutreach
167
+ ? this._outreachCommitted(allToolsExecuted, assistant?.toolRuntimeContext?.outreachReminderType)
168
+ : this._deliveryCommitted(toolsExecuted))) { shouldBreakForDelivery = true; break; }
169
+ const unavailableRecovery = terminalOnly
170
+ ? this._unavailableToolRecovery(toolsExecuted, toolSchemas)
171
+ : null;
172
+ if (unavailableRecovery) {
173
+ shouldBreakForUnavailableRecovery = true;
174
+ trace?.setSignals?.({ deliveryRecoveryUnavailable: unavailableRecovery });
175
+ logger.warn('[OpenAIResponsesProvider] Delivery recovery tool unavailable — stopping terminal retry loop', unavailableRecovery);
176
+ break;
177
+ }
124
178
 
125
179
  const { result: { result: followUp, retries: followUpRetries }, durationMs: followUpDurationMs } = await withTiming(() => makeAPICall(currentInput));
126
180
  totalRetries += followUpRetries;
@@ -128,12 +182,20 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
128
182
  producingIteration = trace?.addIteration({ response: followUp, durationMs: followUpDurationMs, apiCallConfig }) || null;
129
183
  finalResponse = followUp;
130
184
  }
185
+
186
+ // Budget exhausted mid-work: the loop stopped while the model still wanted tools, so the reply may be empty. Make it
187
+ // visible — but not on a supersede or delivery break, which also exit with pending calls and are not exhaustion.
188
+ const pendingCalls = (finalResponse.output || []).filter(item => item.type === 'function_call');
189
+ if (pendingCalls.length && !superseded() && !shouldBreakForDelivery && !shouldBreakForUnavailableRecovery) {
190
+ logger.warn('[OpenAIResponsesProvider] Tool-iteration budget exhausted with pending tool calls', { maxFunctionRounds: this.maxFunctionRounds, pending: pendingCalls.map(c => c.name) });
191
+ trace?.setSignals?.({ toolBudgetExhausted: true });
192
+ }
131
193
  }
132
194
 
133
195
  return { response: finalResponse, toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
134
196
  }
135
197
 
136
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
198
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
137
199
  let modelConfig = null;
138
200
  let resolvedInstructions = instructions;
139
201
  if (promptId || presetId) {
@@ -143,7 +205,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
143
205
  }
144
206
 
145
207
  const apiConfig = {
146
- ...this._mapModelConfig(modelConfig || {}),
208
+ ...this._mapModelConfig({ ...(modelConfig || {}), ...(maxOutputTokens ? { max_output_tokens: maxOutputTokens } : {}) }),
147
209
  instructions: resolvedInstructions || '',
148
210
  };
149
211
  if (model) apiConfig.model = model;
@@ -1,5 +1,7 @@
1
+ const { isToolFailure, toolFailureError } = require('../helpers/toolResultHelper');
2
+
1
3
  const { logger } = require('../../utils/logger');
2
- const { safeParse } = require('../../utils/jsonUtils');
4
+ const { safeParse, normalizeModelStrings } = require('../../utils/jsonUtils');
3
5
 
4
6
  const { hasTool, executeTool: registryExecuteTool } = require('../../services/toolRegistryService');
5
7
 
@@ -13,12 +15,17 @@ async function executeFunctionCall(assistant, call, phiProcessor) {
13
15
  try {
14
16
  decodedArgs = JSON.parse(await phiProcessor?.decodeBody(argsStr, code) ?? argsStr);
15
17
  } catch (e) {
16
- logger.warn('[executeFunctionCall] arg decode produced invalid JSON, falling back to original args', { name, error: e.message });
18
+ logger.warn('[executeFunctionCall] arg decode produced invalid JSON, falling back to original args', { name, errorType: e?.name || 'Error' });
19
+ }
20
+ const normalizedArgs = normalizeModelStrings(decodedArgs);
21
+ if (JSON.stringify(normalizedArgs) !== JSON.stringify(decodedArgs)) {
22
+ logger.warn('[executeFunctionCall] decoded literal unicode escapes in tool arguments', { name, call_id: call.call_id });
23
+ decodedArgs = normalizedArgs;
17
24
  }
18
25
 
19
26
  logger.info('[executeFunctionCall] Calling', { name, call_id: call.call_id });
20
27
 
21
- let result, success = true;
28
+ let result, isSuccess = true;
22
29
  let errorMessage = null;
23
30
  const source = hasTool(name) ? 'registry' : 'assistant';
24
31
  try {
@@ -29,17 +36,24 @@ async function executeFunctionCall(assistant, call, phiProcessor) {
29
36
  }
30
37
  logger.info('[executeFunctionCall] Completed', { name, call_id: call.call_id, source, duration_ms: Date.now() - startTime });
31
38
  } catch (error) {
32
- errorMessage = error?.message || 'Tool execution failed';
33
- result = JSON.stringify({ success: false, error: errorMessage });
34
- success = false;
35
- logger.error('[executeFunctionCall] Failed', { name, call_id: call.call_id, error: error?.message });
39
+ result = JSON.stringify({ success: false, error: error?.message || 'Tool execution failed' });
40
+ isSuccess = false;
41
+ logger.error('[executeFunctionCall] Failed', { name, call_id: call.call_id, errorType: error?.name || 'Error' });
36
42
  }
37
43
 
44
+ if (isSuccess && isToolFailure(result)) isSuccess = false;
45
+
38
46
  try {
39
47
  result = await phiProcessor?.encodeBody(result, code) ?? result;
40
48
  } catch (e) {
41
- logger.error('[executeFunctionCall] PHI encoding failed, returning safe error', { name, call_id: call.call_id, error: e.message });
49
+ logger.error('[executeFunctionCall] PHI encoding failed, returning safe error', { name, call_id: call.call_id, errorType: e?.name || 'Error' });
42
50
  result = JSON.stringify({ success: false, error: 'PHI encoding failed' });
51
+ isSuccess = false;
52
+ errorMessage = 'PHI encoding failed';
53
+ }
54
+
55
+ if (!isSuccess && errorMessage === null) {
56
+ errorMessage = toolFailureError(result);
43
57
  }
44
58
 
45
59
  return {
@@ -53,7 +67,7 @@ async function executeFunctionCall(assistant, call, phiProcessor) {
53
67
  tool_arguments: args,
54
68
  tool_output: result,
55
69
  execution_time_ms: Date.now() - startTime,
56
- success,
70
+ success: isSuccess,
57
71
  error: errorMessage,
58
72
  source,
59
73
  call_id: call.call_id,
@@ -67,6 +81,7 @@ async function handleFunctionCalls(functionCalls, assistant, phiProcessor, itera
67
81
 
68
82
  const outputs = [];
69
83
  const toolsExecuted = [];
84
+ if (assistant?.toolRuntimeContext) assistant.toolRuntimeContext.currentIteration = iteration;
70
85
 
71
86
  for (const call of functionCalls) {
72
87
  const { functionOutput, toolData } = await executeFunctionCall(assistant, call, phiProcessor);
@@ -1,10 +1,12 @@
1
1
  const { OpenAI } = require('openai');
2
2
 
3
+ const { logger } = require('../../utils/logger');
3
4
  const { retryWithBackoff } = require('../../utils/retryUtils');
4
5
  const { withTiming } = require('../../utils/tracingDecorator');
5
6
  const { safeParse } = require('../../utils/jsonUtils');
6
7
 
7
8
  const { OpenAIResponsesProvider } = require('./OpenAIResponsesProvider');
9
+ const { isSuperseded } = require('./BaseLLMProvider');
8
10
  const { handleFunctionCalls } = require('./OpenAIResponsesProviderTools');
9
11
 
10
12
  const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
@@ -37,7 +39,7 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
37
39
 
38
40
  async _invokeModel({
39
41
  instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
40
- modelConfig, assistant, phiProcessor = null, trace = null
42
+ modelConfig, assistant, phiProcessor = null, trace = null, shouldContinue = null, signal = null
41
43
  }, options = {}) {
42
44
  const executeTools = options.toolExecutor || handleFunctionCalls;
43
45
  let totalRetries = 0;
@@ -58,8 +60,9 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
58
60
  apiCallConfig.tool_choice = toolChoice;
59
61
  }
60
62
 
63
+ const requestOptions = signal ? { signal } : undefined;
61
64
  const makeAPICall = (msgs) => retryWithBackoff(
62
- () => this.client.chat.completions.create({ messages: msgs, ...apiCallConfig }),
65
+ () => this.client.chat.completions.create({ messages: msgs, ...apiCallConfig }, requestOptions),
63
66
  { providerName: this.constructor.name }
64
67
  );
65
68
 
@@ -74,6 +77,10 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
74
77
  apiCallConfig.tool_choice = followUpToolChoice;
75
78
 
76
79
  for (let round = 1; round <= this.maxFunctionRounds; round++) {
80
+ if (isSuperseded(shouldContinue)) {
81
+ logger.info('[OpenRouterProvider] turn superseded — aborting tool loop', { round });
82
+ break;
83
+ }
77
84
  const message = finalResponse.choices?.[0]?.message;
78
85
  const toolCalls = message?.tool_calls || [];
79
86
  if (!toolCalls.length) break;
@@ -8,13 +8,46 @@ const { withTracing } = require('../../utils/tracingDecorator.js');
8
8
 
9
9
  const { Thread } = require('../../models/threadModel.js');
10
10
 
11
- const { switchThreadStoppedStatus, setThreadPromptId } = require('../../helpers/threadHelper.js');
11
+ const { switchThreadStoppedStatus, setThreadPromptId } = require('../../services/threadService.js');
12
12
  const { processThreadMessage } = require('../../helpers/processHelper.js');
13
13
  const { cleanupFiles } = require('../../helpers/filesHelper.js');
14
14
 
15
- const { getMessages } = require('../../services/messageService');
15
+ const { getMessages, countMessages } = require('../../services/messageService');
16
16
 
17
17
  const { getAssistantById } = require('./assistantResolver');
18
+ const { PAUSED, UNASSIGNED, coverUnansweredPatient } = require('./pausedSafetyNetService');
19
+
20
+ const MEDIA_BACKLOG_LIMIT = 10;
21
+
22
+ const fetchMediaBacklog = async (code, trigger) => {
23
+ const [lastOutbound] = await getMessages(
24
+ { numero: code, from_me: true, createdAt: { $lt: trigger.createdAt } },
25
+ { sort: { createdAt: -1 }, limit: 1 }
26
+ );
27
+
28
+ const createdAt = { $lte: trigger.createdAt };
29
+ if (lastOutbound) createdAt.$gt = lastOutbound.createdAt;
30
+
31
+ const query = {
32
+ numero: code,
33
+ from_me: false,
34
+ 'media.key': { $exists: true, $ne: null },
35
+ 'media.metadata.processedContent': null,
36
+ _id: { $ne: trigger._id },
37
+ createdAt
38
+ };
39
+
40
+ const rows = await getMessages(query, { sort: { createdAt: 1 }, limit: MEDIA_BACKLOG_LIMIT + 1 });
41
+
42
+ if (rows.length > MEDIA_BACKLOG_LIMIT) {
43
+ const total = await countMessages(query);
44
+ logger.warn('[preProcessMessages] Media backlog truncated', {
45
+ code, limit: MEDIA_BACKLOG_LIMIT, dropped: total - MEDIA_BACKLOG_LIMIT
46
+ });
47
+ }
48
+
49
+ return rows.slice(0, MEDIA_BACKLOG_LIMIT);
50
+ };
18
51
 
19
52
  const createAssistantCore = async (code, assistant_id, _messages = [], force = false) => {
20
53
  const findThread = await Thread.findOne({ code: code });
@@ -79,10 +112,15 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
79
112
  return { shouldProcess: false, messages: null, timings, pendingMediaUpdates: [] };
80
113
  }
81
114
 
115
+ if (thread.stopped) await coverUnansweredPatient({ code, reason: thread.pausedAt ? PAUSED : UNASSIGNED });
116
+
117
+ const backlog = await fetchMediaBacklog(code, lastMessage[0]);
118
+ const replies = [...backlog, ...lastMessage];
119
+
82
120
  const provider = createLLMProvider({ variant: getProviderVariant() });
83
- logger.info(`[preProcessMessages] Processing ${lastMessage.length} messages in parallel`);
121
+ logger.info(`[preProcessMessages] Processing ${replies.length} messages in parallel`, { media_backlog: backlog.length });
84
122
  const processStart = Date.now();
85
- const processResult = await processThreadMessage(code, lastMessage, provider);
123
+ const processResult = await processThreadMessage(code, replies, provider);
86
124
 
87
125
  const { results: processResults, timings: processTimings } = processResult;
88
126
  timings.process_messages_ms = Date.now() - processStart;
@@ -99,10 +137,16 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
99
137
  };
100
138
  }
101
139
 
102
- const patientMsg = processResults.some(r => r.isPatient);
140
+ const hasPatientMsg = Boolean(processResults[processResults.length - 1]?.isPatient);
103
141
  const allTempFiles = processResults.flatMap(r => r.tempFiles || []);
104
142
 
105
143
  const pendingMediaUpdates = processResults.reduce((acc, r) => {
144
+ if (r.failed) {
145
+ logger.warn('[preProcessMessages] Media read failed; leaving it unprocessed so a later turn retries', {
146
+ message_id: r.reply?.message_id, mediaType: r.reply?.media?.mediaType, code
147
+ });
148
+ return acc;
149
+ }
106
150
  const processedContent = r.messages && r.messages.length > 0
107
151
  ? r.messages
108
152
  .filter(msg => msg.content.text !== r.reply?.body)
@@ -122,8 +166,8 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
122
166
 
123
167
  await cleanupFiles(allTempFiles);
124
168
 
125
- if (!patientMsg || thread.stopped) {
126
- logger.info('[preProcessMessages] Skipping AI processing', { patientMsg, stopped: thread.stopped, code });
169
+ if (!hasPatientMsg || thread.stopped) {
170
+ logger.info('[preProcessMessages] Skipping AI processing', { hasPatientMsg, stopped: thread.stopped, code });
127
171
  return { shouldProcess: false, messages: null, timings, pendingMediaUpdates };
128
172
  }
129
173
 
@@ -0,0 +1,93 @@
1
+ const { stripTurnMarkers } = require('../../helpers/patientMessageHelper');
2
+ const { logger } = require('../../utils/logger');
3
+ const { MapCache } = require('../../utils/MapCache');
4
+ const { isBridgeEnabled, getBlockedPhrases } = require('../flags/bridgeConfig');
5
+
6
+ const MAX_WORDS = 25;
7
+ const BRIDGE_RATE_LIMIT_MS = 60000;
8
+ const CONTEXT_MARKER_PREFIX_RX = /^\s*(\[\s*(?:puente|sistema|equipo|plataforma)\b[^\]]*\]\s*)+/i;
9
+ const INTERNAL_STRUCTURE_RX = /[[\]]|\*\*|^#{1,6}\s|\n/;
10
+ const THIRD_PERSON_RX = /(^|[.\n]\s*)((?:[Ll]a|[Ee]l) paciente|[A-ZÁÉÍÓÚÑ][a-záéíóúñ]{2,})(,?\s+[a-záéíóúñ]+){0,6}\s+(menciona|reporta|refiere|confirma|presenta|llega con|acaba de|va a dar|llevaba|est[aá] con|comparte)/;
11
+
12
+ const bridgeTimestamps = new MapCache({ maxSize: 1000, ttl: BRIDGE_RATE_LIMIT_MS });
13
+
14
+ const wordPadded = text => ` ${text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()} `;
15
+
16
+ function screenBridgeText(text) {
17
+ const trimmed = stripTurnMarkers((text || '').replace(CONTEXT_MARKER_PREFIX_RX, '')).trim();
18
+ if (trimmed.length < 2) return { reason: 'empty_bridge_text' };
19
+ if (trimmed.split(/\s+/).length > MAX_WORDS) return { reason: 'over_word_cap' };
20
+ if (INTERNAL_STRUCTURE_RX.test(trimmed)) return { reason: 'internal_structure' };
21
+ if (THIRD_PERSON_RX.test(trimmed)) return { reason: 'third_person_note' };
22
+
23
+ const padded = wordPadded(trimmed);
24
+ const phrase = getBlockedPhrases().find(candidate => padded.includes(` ${candidate} `));
25
+ return phrase ? { reason: 'blocked_phrase', phrase } : { text: trimmed };
26
+ }
27
+
28
+ function buildDedupNote(bridgeText) {
29
+ return '[sistema] Ya enviaste la siguiente burbuja al paciente como mensaje puente: ' +
30
+ `"${bridgeText}". Tu mensaje final NO debe repetir saludo, nombre del paciente, ` +
31
+ 'ni acuse del inbound — eso ya fue entregado. Empieza directo con el contenido ' +
32
+ 'clínico. El mensaje final es la SEGUNDA burbuja que verá el paciente, no la primera.';
33
+ }
34
+
35
+ function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage }) {
36
+ const authored = typeof bridgeText === 'string' && bridgeText.trim() ? bridgeText : null;
37
+
38
+ if (!isBridgeEnabled()) return { sent: false, reason: 'disabled', proposed: Boolean(authored) };
39
+
40
+ const skip = (reason, extra = {}, phrase = null) => {
41
+ logger.info('[bridge] skipped', { code, reason, ...(phrase ? { phrase } : {}) });
42
+ return { sent: false, reason, proposed: Boolean(authored), ...(phrase ? { phrase } : {}), ...extra };
43
+ };
44
+
45
+ if (typeof shouldContinue === 'function' && !shouldContinue()) return skip('superseded');
46
+ if (!hasToolCalls) return skip('text_only_iter1_would_duplicate_final');
47
+ if (deliveryOnly) return skip('delivery_only_iter1_would_duplicate_final');
48
+ if (!authored) return skip('no_bridge_field');
49
+
50
+ const { text, reason, phrase } = screenBridgeText(authored);
51
+ if (!text) return skip(reason, {}, phrase);
52
+
53
+ const pending = bridgeTimestamps.get(code);
54
+ if (pending !== undefined) {
55
+ return skip('recent_bridge_in_thread', pending.delivered ? { dedupNote: pending.dedupNote } : {});
56
+ }
57
+
58
+ const dedupNote = buildDedupNote(text);
59
+ const entry = { dedupNote, delivered: false, clearWhenDelivered: false };
60
+ bridgeTimestamps.set(code, entry);
61
+ const failed = (err) => {
62
+ bridgeTimestamps.delete(code);
63
+ logger.warn('[bridge] send failed', { code, error: err.message });
64
+ };
65
+ const delivered = () => {
66
+ entry.delivered = true;
67
+ if (entry.clearWhenDelivered && bridgeTimestamps.get(code) === entry) bridgeTimestamps.delete(code);
68
+ };
69
+ try {
70
+ Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId }))
71
+ .then(delivered)
72
+ .catch(failed);
73
+ } catch (err) {
74
+ failed(err);
75
+ }
76
+
77
+ logger.info('[bridge] sent', { code });
78
+ return { sent: true, reason: null, proposed: true, text, dedupNote };
79
+ }
80
+
81
+ function clearBridgeState(code) {
82
+ const pending = bridgeTimestamps.get(code);
83
+ if (pending && !pending.delivered) {
84
+ pending.clearWhenDelivered = true;
85
+ return;
86
+ }
87
+ bridgeTimestamps.delete(code);
88
+ }
89
+
90
+ module.exports = {
91
+ maybeSendBridge,
92
+ clearBridgeState,
93
+ };
@@ -0,0 +1,134 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const { getMessages } = require('../../services/messageService');
4
+ const { replyContactFor } = require('../../helpers/caregiverHelper');
5
+ const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
6
+ const { checkInsPausedUntil } = require('../../services/threadService');
7
+ const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
8
+ const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
9
+ const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
10
+ const { logger } = require('../../utils/logger');
11
+
12
+ const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
13
+ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
14
+ const TRIGGERED_BY_PREFIX = 'send_reminder:';
15
+ const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
16
+ const EXCERPT_LENGTH = 160;
17
+ const LAST_MESSAGE_SCAN = 5;
18
+
19
+ const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
20
+
21
+ function mandatoryInstruction(firstName, question) {
22
+ return `${firstName || 'La paciente'} no ha vuelto a escribir y quedó un tema abierto que querías retomar. Esto es lo que decidiste preguntarle: "${question}".
23
+
24
+ Antes de escribir, revisa la conversación desde que decidiste preguntarlo. Si ya lo respondió — a ti o al equipo —, no se lo vuelvas a preguntar: retoma desde lo que dijo y pregunta solo lo que siga faltando; si ya no falta nada, cierra en una línea breve y cálida. No le preguntes si el equipo ya la contactó o ya le dio indicaciones: eso no te toca a ti; si tu pregunta lo incluía, quita esa parte.
25
+
26
+ Escríbele tú, de forma breve y natural, en tu tono de siempre, como quien retoma algo pendiente de una conversación. NO digas que pidió un recordatorio ni que se lo prometiste — no lo hizo. No menciones alertas, planes, seguimientos programados ni nada del sistema. No repitas un mensaje que ya le enviaste. Si contesta, sigue la conversación con normalidad.`;
27
+ }
28
+
29
+ async function recentCheckIns(code, now) {
30
+ const rows = await getMessages(
31
+ {
32
+ numero: code,
33
+ from_me: true,
34
+ createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
35
+ $or: [
36
+ { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
37
+ { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
38
+ ],
39
+ },
40
+ { sort: { createdAt: 1 }, select: 'createdAt' },
41
+ );
42
+ return (rows || []).map((row) => new Date(row.createdAt).toISOString());
43
+ }
44
+
45
+ // Templates (cards, forms) and automations (the triage ack) would hide what the agent or the team last wrote; staff sign with their email.
46
+ const OWN_WRITTEN = { $or: [{ origin: 'assistant' }, { origin: 'whatsapp_platform', content_sid: null, triggeredBy: { $regex: '@' } }] };
47
+ const PATIENT_WRITTEN = { origin: { $ne: 'instruction' } };
48
+
49
+ async function lastMessage(code, now, fromMe) {
50
+ const rows = await getMessages(
51
+ { numero: code, from_me: fromMe, ...(fromMe ? OWN_WRITTEN : PATIENT_WRITTEN), createdAt: { $lt: now } },
52
+ { sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
53
+ ) || [];
54
+ const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
55
+ if (!row) return null;
56
+ const text = String(row.plainBody || row.body || '').trim();
57
+ return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
58
+ }
59
+
60
+ async function recentExchange(code, now) {
61
+ const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
62
+ const [patient, own, ownToday, sessionOpen] = await Promise.all([
63
+ lastMessage(code, now, false),
64
+ lastMessage(code, now, true),
65
+ getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
66
+ replyContactFor(code).then((contact) => isWithin24HourWindow(code, { contactCode: contact?.contactCode || null })),
67
+ ]);
68
+ return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
69
+ }
70
+
71
+ async function briefFor(code, now, checkIn) {
72
+ const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
73
+ return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
74
+ }
75
+
76
+ async function countOtherPlans(code, { planId = null, reminderId, nets = null }) {
77
+ try {
78
+ const [activeNets, followUps] = await Promise.all([nets || readActiveNets(code), readPendingFollowUpsForPatient({ code })]);
79
+ const otherNets = (activeNets || []).filter((candidate) => candidate.carePlan.planId !== planId && candidate.carePlan.status === 'armed');
80
+ const otherFollowUps = (followUps || []).filter((plan) => plan.reminderId !== reminderId);
81
+ return otherNets.length + otherFollowUps.length;
82
+ } catch (error) {
83
+ logger.warn('[checkInDue] other plans unreadable; stand-down left unverified', { reminderId, error: error.message });
84
+ return null;
85
+ }
86
+ }
87
+
88
+ async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
89
+ let checkIn;
90
+ if (type === 'contingencia') {
91
+ const planId = String(reminderId).replace(/-patient$/, '');
92
+ const nets = await readActiveNets(code);
93
+ const net = nets.find((candidate) => candidate.carePlan.planId === planId);
94
+ if (!net) return { mode: 'stale', reason: 'net_not_active' };
95
+ const urgency = escalationUrgencyOf(net);
96
+ const netQuestion = net.patientReminder?.message || question;
97
+ if (MANDATORY_URGENCIES.has(urgency)) {
98
+ return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
99
+ }
100
+ if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused', planId };
101
+ checkIn = {
102
+ type,
103
+ reminderId,
104
+ planId,
105
+ dueAt: null,
106
+ question: netQuestion,
107
+ concern: net.carePlan.concern,
108
+ awaiting: net.carePlan.awaitingCharacterization,
109
+ armedAt: net.carePlan.createdAt,
110
+ urgency,
111
+ otherPlans: await countOtherPlans(code, { planId, reminderId, nets }),
112
+ };
113
+ return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
114
+ }
115
+
116
+ const plan = await readPendingReminderForPatient({ code, reminderId });
117
+ if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
118
+ if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
119
+ checkIn = {
120
+ type,
121
+ reminderId,
122
+ planId: null,
123
+ dueAt: plan.fireAt || null,
124
+ question: plan.message || question,
125
+ concern: plan.windowReasoning,
126
+ awaiting: null,
127
+ armedAt: null,
128
+ urgency: null,
129
+ otherPlans: await countOtherPlans(code, { reminderId }),
130
+ };
131
+ return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
132
+ }
133
+
134
+ module.exports = { checkInTriggeredBy, planCheckInDue };