@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
@@ -1,9 +1,33 @@
1
+ const moment = require('moment-timezone');
2
+
1
3
  const { DefaultMemoryManager } = require('../memory/DefaultMemoryManager');
4
+ const { REFUSAL, isPurelyConversational } = require('../helpers/clinicalWorkflowGuard');
5
+ const { isToolFailure, toolRecoveryContract } = require('../helpers/toolResultHelper');
6
+ const { buildDateAnchor } = require('../helpers/dateAnchorHelper');
7
+ const { withHospitalization } = require('../helpers/hospitalizationContextHelper');
8
+ const { getConversationalTokens } = require('../services/clinicalExtractionService');
2
9
  const { composePrompt, resolveTools } = require('../services/promptComposerService');
10
+ const { resolveSkillCatalog } = require('../services/skillService');
11
+ const { RISK_HEADLINE_MARKER } = require('../services/riskHeadlineService');
12
+ const { resolveClinicalContext } = require('../services/clinicalContextReadService');
13
+ const { radiotherapyBlockFor, withRadiotherapyBlock } = require('../services/radiotherapyContextService');
14
+ const { isContingencyRuleBlockLive } = require('../flags/contingencyFlags');
15
+ const { snapshotClinicalFlags } = require('../flags/flagSnapshot');
16
+ const { TURN_KIND } = require('../context/turnContext');
17
+ const { extractPatientMessage } = require('../../helpers/patientMessageHelper');
3
18
  const runtimeConfig = require('../../config/runtimeConfig');
19
+ const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
4
20
  const { logger } = require('../../utils/logger');
21
+ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
22
+ const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
5
23
  const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
6
24
  const { isJsonBlob } = require('../../utils/formatUtils');
25
+ const { isPlainObject, safeParse, decodeLiteralUnicodeEscapes } = require('../../utils/jsonUtils');
26
+ const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
27
+
28
+ const EXCHANGE_LINE_LENGTH = 400;
29
+
30
+ const CONSUMER_SIGNALS_KEY = 'consumer';
7
31
 
8
32
  const { getToolSchemas: getRegistrySchemas } = require('../../services/toolRegistryService');
9
33
  const { getMessages } = require('../../services/messageService');
@@ -13,6 +37,41 @@ const { logBugReportToAirtable } = require('../../controllers/bugReportControlle
13
37
  const DEFAULT_MAX_CONVERSATION_RETRIES = 3;
14
38
  const CONVERSATION_CONTINUATION = '(continuar)';
15
39
 
40
+ const outreachMinute = (value) => {
41
+ const match = String(value || '').trim().match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);
42
+ return match ? `${match[1]}T${match[2]}` : null;
43
+ };
44
+
45
+ const localFireTime = (value) => {
46
+ const at = moment.tz(value, DEFAULT_TIMEZONE);
47
+ return value && at.isValid() ? `${at.format('YYYY-MM-DD HH:mm')} (hora de la paciente)` : sanitizeInlineText(value);
48
+ };
49
+
50
+ const NEGATIVE_GUIDANCE_MARKER = '**When NOT to call';
51
+ const CONTINGENCY_RULE = [
52
+ '[REGLA DE CONTINGENCIA (prioritaria) para este turno]',
53
+ 'Llama `setContingencyPlan` con `action: \'arm\'` cuando, leído contra el `grade_scale` del término, todavía falte un dato que podría poner el caso en un grado por encima de tu lectura actual. Nómbralo en `awaiting_characterization`, escrito como la paciente podría contestarlo.',
54
+ 'Si ya sabes todo lo necesario para descartar los grados mayores, NO armes. Si el caso es serio y ya está completamente evaluado, escala: una evaluación terminada necesita una persona, no un check-in.',
55
+ 'Lo que decide es la rúbrica, no lo alarmante que suene el síntoma. Un pendiente que no puede mover el grado no es motivo para armar, y esperar al equipo tampoco: una escalación no rutinaria normalmente arma su propia red (una `routine` no, así que ahí decide el techo).',
56
+ ].join('\n');
57
+ const TERMINAL_DELIVERY_TOOLS = new Set(['DeliverPatientMessage']);
58
+ const BRIDGE_TOOL = 'SendBridgeMessage';
59
+ const EXTRACTION_TOOL = 'extractClinicalInfo';
60
+ const CONVERSATIONAL_REQUEST = 'conversational';
61
+ const DELIVERY_NUDGE = 'sistema: el turno no puede cerrar sin un mensaje para el paciente. Llama ahora a DeliverPatientMessage con message_text en español. No repitas herramientas clínicas ya ejecutadas en este turno.';
62
+ const MAX_DELIVERY_NUDGES = 2;
63
+ const OUTREACH_DECISION_TOOL = 'submitOutreachDecision';
64
+ const OUTREACH_NUDGE = 'sistema: este turno de contacto proactivo no puede cerrar incompleto. Si aún no decidiste, llama a submitOutreachDecision. Si ya registraste write, NO repitas esa decisión: llama ahora a DeliverPatientMessage. Si registraste hold con next_check_at, ese hold no cierra hasta que lo programes: llama ahora a schedulePatientReminder con reminder_date igual a ese next_check_at; si rechaza esa hora, elige una que acepte y registra de nuevo el hold con esa misma hora. Si ya no hace falta volver a preguntar, registra de nuevo el hold con next_check_at null: contingency_already_armed solo si otro plan activo lo cubre; si no, usa el hold_reason que corresponda y, si es una red, resuélvela con setContingencyPlan. No cambies a write solo para poder cerrar. Un hold sin next_check_at sí puede cerrar sin mensaje.';
65
+ const DELIVERY_FALLBACK_MESSAGES = [
66
+ 'Gracias por tu mensaje. Si necesitas apoyo, escríbeme cuando quieras.',
67
+ 'Gracias por escribirme. Aquí estoy cuando necesites algo.',
68
+ 'Recibí tu mensaje. Cuando quieras contarme más o pedir apoyo, escríbeme.',
69
+ ];
70
+
71
+ function isSuperseded(shouldContinue) {
72
+ return typeof shouldContinue === 'function' && !shouldContinue();
73
+ }
74
+
16
75
  class BaseLLMProvider {
17
76
  constructor(options = {}) {
18
77
  if (new.target === BaseLLMProvider) {
@@ -36,47 +95,131 @@ class BaseLLMProvider {
36
95
  instructions = null, additionalInstructions = null, metadata = {},
37
96
  assistant, promptVersion = null, promptVariables = null,
38
97
  toolChoice = 'auto', prePromptResult = null, phiProcessor = null,
39
- shadow = false, shouldContinue = null
98
+ shadow = false, shouldContinue = null, onFirstIteration = null, signal = null,
99
+ outreachBrief = null,
40
100
  } = config;
41
101
  const trace = assistant?.toolRuntimeContext?.trace || null;
102
+ const turnKind = assistant?.toolRuntimeContext?.turnKind || TURN_KIND.UNKNOWN;
103
+ const isOutreach = turnKind === TURN_KIND.PROACTIVE_OUTREACH;
42
104
 
43
105
  const {
44
- resolvedPrompt, snippetIds, promptId: resolvedPromptId, presetToolIds,
106
+ resolvedPrompt, interpolatedVariables, snippetIds, promptId: resolvedPromptId,
107
+ presetToolIds, presetSkillIds,
45
108
  presetId: resolvedPresetId, presetVersion: resolvedPresetVersion, modelConfig,
46
109
  } = await composePrompt({ presetId, presetVersion, promptId: assistantId, variables: promptVariables });
47
110
 
48
- const { toolIds, filtered, descriptions: toolDescriptions } = await resolveTools({
111
+ const { toolIds, filtered, descriptions: toolDescriptions, unregisteredToolIds = [] } = await resolveTools({
49
112
  promptId: resolvedPromptId || assistantId, assistant, presetToolIds,
50
113
  });
114
+ const requestedAdditionalToolIds = Array.isArray(prePromptResult?.additionalToolIds)
115
+ ? [...new Set(prePromptResult.additionalToolIds
116
+ .filter(id => typeof id === 'string' && id.trim())
117
+ .map(id => id.trim()))].slice(0, MAX_ADDITIONAL_TOOL_IDS)
118
+ : [];
119
+ const registeredAdditionalToolIds = requestedAdditionalToolIds.length > 0
120
+ ? getRegistrySchemas(requestedAdditionalToolIds)
121
+ .map(schema => schema.function?.name)
122
+ .filter(Boolean)
123
+ : [];
124
+ const resolvedToolIds = filtered
125
+ ? [...new Set([...toolIds, ...registeredAdditionalToolIds])]
126
+ : toolIds;
51
127
 
52
- const toolSchemas = this._resolveToolSchemas({ assistant, toolIds, filtered, toolDescriptions });
53
- const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult, additionalInstructions });
54
- const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig });
55
-
56
- // Capture before _invokeModel: the divergence oracle replays this shadow request shape.
57
- if (shadow && assistant?.toolRuntimeContext) {
58
- assistant.toolRuntimeContext.divergenceInputs = {
59
- clinicalData: {
60
- clinicalContext: promptVariables?.clinical_context || '',
61
- lastSymptoms: promptVariables?.last_symptoms || '',
62
- patientMemories: promptVariables?.patient_memories || '',
63
- conversationSummaries: promptVariables?.conversation_summaries || '',
64
- },
65
- input,
66
- model: modelConfig?.model || null,
67
- toolIds: Array.isArray(toolIds) ? toolIds : [],
68
- additionalInstructions: additionalInstructions || null,
69
- };
128
+ const rejectedAdditionalToolIds = requestedAdditionalToolIds
129
+ .filter(id => !registeredAdditionalToolIds.includes(id));
130
+ if (rejectedAdditionalToolIds.length > 0) {
131
+ logger.warn('[BaseLLMProvider] Ignoring unregistered runtime tools', {
132
+ toolIds: rejectedAdditionalToolIds,
133
+ });
70
134
  }
71
135
 
72
- trace?.setPrompt({ resolved: devContent, resolvedPresetId, resolvedPresetVersion });
136
+ const skillCatalog = await resolveSkillCatalog(presetSkillIds);
137
+ const enabledSkills = skillCatalog.map((skill) => skill.name);
138
+ if (assistant?.toolRuntimeContext) {
139
+ assistant.toolRuntimeContext.enabledSkills = enabledSkills;
140
+ }
141
+
142
+ const resolvedSchemas = this._scopeOutreachDecisionTool(this._resolveToolSchemas({
143
+ assistant, toolIds: resolvedToolIds, filtered, toolDescriptions,
144
+ }), isOutreach);
145
+ const { toolChoice: flooredToolChoice, toolSchemas, narrowed } = this._applyDeliveryFloor(
146
+ toolChoice, resolvedSchemas, Boolean(assistant?.toolRuntimeContext), turnKind);
147
+ const effectiveToolIds = toolSchemas.map(s => s.function?.name).filter(Boolean);
148
+ const instructionToolIds = narrowed || isOutreach ? effectiveToolIds : resolvedToolIds;
149
+ const requestedToolChoice = prePromptResult?.toolChoice;
150
+ const requestedToolName = requestedToolChoice?.name || requestedToolChoice?.function?.name || null;
151
+ const supportedGenericChoices = new Set(['auto', 'none', 'required', 'any']);
152
+ const isGenericToolChoice = (typeof requestedToolChoice === 'string'
153
+ && supportedGenericChoices.has(requestedToolChoice))
154
+ || (isPlainObject(requestedToolChoice) && !requestedToolName
155
+ && supportedGenericChoices.has(requestedToolChoice.type));
156
+ const runtimeToolChoice = requestedToolName
157
+ ? (effectiveToolIds.includes(requestedToolName) ? requestedToolChoice : null)
158
+ : (isGenericToolChoice ? requestedToolChoice : null);
159
+ if (requestedToolName && runtimeToolChoice === null) {
160
+ logger.warn('[BaseLLMProvider] Ignoring forced choice for an unavailable runtime tool', {
161
+ toolId: requestedToolName,
162
+ });
163
+ }
164
+ const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
165
+ const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
166
+ const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
167
+ const allowFollowUp = assistant?.toolRuntimeContext?.outreachAllowsFollowUp !== false;
168
+ const auditedPrompt = [
169
+ devContent,
170
+ catalogBlock,
171
+ additionalInstructions ? this._operatorInstructionTurn(additionalInstructions, modelConfig).content : '',
172
+ isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds, allowFollowUp })[0]?.content || '') : '',
173
+ ruleBlock,
174
+ ].filter(Boolean).join('\n\n');
175
+ const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null, allowFollowUp });
176
+
177
+ if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
178
+ trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
179
+ }
180
+
181
+ if (trace?.setSignals) {
182
+ const runtime = assistant?.toolRuntimeContext || null;
183
+ const currentPatientText = this._aggregatedPatientText(context) ?? runtime?.patientInput?.text;
184
+ let workflowRequired = true;
185
+ let decisionReason = 'untyped_turn_fail_closed';
186
+ if (turnKind === TURN_KIND.OPERATOR_INSTRUCTION || turnKind === TURN_KIND.SYSTEM
187
+ || turnKind === TURN_KIND.PROACTIVE_OUTREACH) {
188
+ workflowRequired = false;
189
+ decisionReason = 'no_patient_input';
190
+ } else if (turnKind === TURN_KIND.PATIENT && typeof currentPatientText === 'string') {
191
+ try {
192
+ workflowRequired = !isPurelyConversational(currentPatientText, await getConversationalTokens());
193
+ decisionReason = workflowRequired ? 'substantive_patient_input' : 'conversational_patient_input';
194
+ } catch (error) {
195
+ logger.warn('[BaseLLMProvider] conversational classification failed; requiring clinical workflow', {
196
+ error: error.message,
197
+ });
198
+ decisionReason = 'classification_failed_closed';
199
+ }
200
+ } else if (turnKind === TURN_KIND.PATIENT) {
201
+ decisionReason = 'patient_input_without_text_fail_closed';
202
+ }
203
+ trace.setSignals({
204
+ clinicalIntakeDecisionRequired: workflowRequired,
205
+ clinicalIntakeDecisionReason: decisionReason,
206
+ });
207
+ }
208
+
209
+ trace?.setPrompt({ resolvedPresetId, resolvedPresetVersion });
210
+ trace?.setSignals?.({
211
+ offeredToolIds: effectiveToolIds,
212
+ enabledSkills,
213
+ flags: snapshotClinicalFlags(),
214
+ ...(unregisteredToolIds.length > 0 && { unregisteredToolIds }),
215
+ });
73
216
 
74
217
  const { response, toolsExecuted, retries, usage } = await this._invokeModel({
75
218
  instructions: instructions || devContent || '',
76
219
  input,
77
220
  toolSchemas,
78
- toolChoice: prePromptResult?.toolChoice || toolChoice,
79
- followUpToolChoice: toolChoice,
221
+ toolChoice: narrowed ? flooredToolChoice : runtimeToolChoice || flooredToolChoice,
222
+ followUpToolChoice: flooredToolChoice,
80
223
  modelConfig,
81
224
  metadata,
82
225
  assistant,
@@ -88,6 +231,9 @@ class BaseLLMProvider {
88
231
  trace,
89
232
  shadow,
90
233
  shouldContinue,
234
+ onFirstIteration,
235
+ signal,
236
+ isOutreach,
91
237
  });
92
238
 
93
239
  return {
@@ -98,9 +244,9 @@ class BaseLLMProvider {
98
244
  tools_executed: toolsExecuted,
99
245
  retries,
100
246
  usage,
101
- resolved_prompt: devContent,
247
+ resolved_prompt: auditedPrompt,
102
248
  snippet_ids: snippetIds,
103
- tool_ids: toolIds,
249
+ tool_ids: effectiveToolIds,
104
250
  preset_id: resolvedPresetId,
105
251
  preset_version: resolvedPresetVersion,
106
252
  preset: resolvedPresetId ? { id: resolvedPresetId, version: resolvedPresetVersion } : null,
@@ -108,6 +254,17 @@ class BaseLLMProvider {
108
254
  };
109
255
  }
110
256
 
257
+ // The decision tool belongs to the turn kind, not to a preset: without it an outreach turn cannot
258
+ // close and the brief is dropped, and on any other turn it would invite a decision nobody asked for.
259
+ _scopeOutreachDecisionTool(schemas, isOutreach) {
260
+ const others = schemas.filter(s => s.function?.name !== OUTREACH_DECISION_TOOL);
261
+ if (!isOutreach) return others;
262
+ const decision = schemas.find(s => s.function?.name === OUTREACH_DECISION_TOOL)
263
+ || getRegistrySchemas([OUTREACH_DECISION_TOOL])[0];
264
+ if (!decision) throw new Error('OUTREACH_DECISION_TOOL_UNAVAILABLE');
265
+ return [...others, decision];
266
+ }
267
+
111
268
  _resolveToolSchemas({ assistant, toolIds, filtered, toolDescriptions }) {
112
269
  const assistantSchemas = assistant?.getToolSchemas?.() || [];
113
270
  const registrySchemas = getRegistrySchemas();
@@ -124,13 +281,17 @@ class BaseLLMProvider {
124
281
  return activeToolSchemas.map(s => {
125
282
  const name = s.function?.name;
126
283
  if (name && toolDescriptions[name]) {
284
+ if (s.function.description?.includes(NEGATIVE_GUIDANCE_MARKER)
285
+ && !toolDescriptions[name].includes(NEGATIVE_GUIDANCE_MARKER)) {
286
+ logger.warn('[BaseLLMProvider] Airtable description drops the when-NOT-to-call guidance written in code', { tool: name });
287
+ }
127
288
  return { ...s, function: { ...s.function, description: toolDescriptions[name] } };
128
289
  }
129
290
  return s;
130
291
  });
131
292
  }
132
293
 
133
- _buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult, additionalInstructions }) {
294
+ _buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult }) {
134
295
  let devContent = resolvedPrompt;
135
296
  if (toolSchemas.length > 0) {
136
297
  const toolNames = toolSchemas.map(s => s.function?.name).join(', ');
@@ -139,21 +300,14 @@ class BaseLLMProvider {
139
300
  if (prePromptResult?.additionalInstructions) {
140
301
  devContent += `\n\n${prePromptResult.additionalInstructions}`;
141
302
  }
142
- if (additionalInstructions) {
143
- devContent += this._operatorInstructionSuffix(additionalInstructions);
144
- }
145
303
  return devContent;
146
304
  }
147
305
 
148
- _operatorInstructionSuffix(additionalInstructions) {
149
- return `\n\n[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}`;
150
- }
151
-
152
- _operatorInstructionTurn() {
153
- return { role: 'user', content: CONVERSATION_CONTINUATION };
306
+ _operatorInstructionTurn(additionalInstructions) {
307
+ return { role: 'developer', content: `[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}` };
154
308
  }
155
309
 
156
- _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null }) {
310
+ _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null, allowFollowUp = true }) {
157
311
  let messages = this._convertItemsToApiFormat(context || []);
158
312
  if (Array.isArray(prePromptResult?.additionalMessages) && prePromptResult.additionalMessages.length > 0) {
159
313
  messages = [...messages, ...this._convertItemsToApiFormat(prePromptResult.additionalMessages)];
@@ -161,7 +315,271 @@ class BaseLLMProvider {
161
315
  if (additionalInstructions) {
162
316
  messages = [...messages, this._operatorInstructionTurn(additionalInstructions, modelConfig)];
163
317
  }
164
- return this._sanitizeInput([...this._buildMemoryMessage(promptVariables), ...messages]);
318
+ return this._sanitizeInput([
319
+ ...this._buildSkillCatalogMessage(skillCatalog),
320
+ ...this._buildMemoryMessage(promptVariables),
321
+ ...this._buildClinicalMessage(promptVariables, interpolatedVariables),
322
+ ...this._buildContingencyMessage(promptVariables),
323
+ ...this._buildFollowUpPolicyMessage(toolIds),
324
+ ...this._buildFollowUpMessage(promptVariables),
325
+ ...this._buildFollowUpCheckMessage(toolIds),
326
+ ...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
327
+ ...this._buildClockMessage(promptVariables, interpolatedVariables),
328
+ ...messages,
329
+ ...this._buildOutreachBriefMessage({ outreachBrief, toolIds, allowFollowUp }),
330
+ ...this._buildContingencyRuleMessage({ toolIds, promptVariables }),
331
+ ]);
332
+ }
333
+
334
+ _buildFollowUpPolicyMessage(toolIds = []) {
335
+ const available = new Set(toolIds || []);
336
+ if (!available.has('schedulePatientReminder') && !available.has('setContingencyPlan')) return [];
337
+ return [{
338
+ role: 'developer',
339
+ content: [
340
+ '## Seguimiento, recordatorio y contingencia — no son intercambiables',
341
+ '- SEGUIMIENTO: tú decides volver a contactar para mantener continuidad cuando ya no falta un dato clínico que pueda cambiar el riesgo. Elige cuándo y redacta la pregunta exacta para esa persona. Usa schedulePatientReminder con reminder_type seguimiento y la utility_basis concreta. Prográmalo cuando indicaste una acción (medicamento de venta libre, autocuidado, educación) cuyo efecto se ve en 24–72 h; cuando la paciente ya dio el dato y quieres saber si el síntoma vuelve o cruza un umbral que nombraste; cuando cerraste un episodio que vale la pena revisar; o cuando tiene un evento próximo (inicio de tratamiento, cita, infusión) cuyo resultado importa. Si en este turno le indicaste un medicamento, una medida de autocuidado o que contacte a alguien (dentista, su médico, urgencias), o le transmitiste un tratamiento que indicó el equipo, decide el seguimiento en este mismo turno: si no hay ya un seguimiento activo que lo cubra, programa uno a 24–48 h (una red abierta no lo impide: la red espera su dato y el seguimiento pregunta por lo indicado) con utility_basis agreed_action: si fue un medicamento o una medida, para saber si funcionó; si fue una cita o un estudio, para saber si pudo agendarlo o si ya fue y cuándo. Pedirle «avísame cómo te va» no sustituye ese seguimiento. No lo programes por inactividad sola. Si la paciente vuelve a escribir antes, el seguimiento sigue pendiente y lo verás en «Seguimientos ya programados»: mantenlo, actualízalo o cancélalo según lo que cambió.',
342
+ '- RECORDATORIO: sólo existe si la paciente pidió explícitamente que se lo recuerdes o aceptó explícitamente tu oferta de recordárselo. Usa schedulePatientReminder con el tipo concreto (medicamento, cita, examen u otros) y exactamente a la hora que pidió. No lo adelantes para que llegue antes de una cita o tarea salvo que ella haya pedido ese adelanto. No infieras un recordatorio porque mencionó o agendó algo, ni lo uses para preguntar cómo sigue o vigilar incertidumbre clínica.',
343
+ '- CONTINGENCIA: protege una incertidumbre clínica todavía abierta; falta un dato u observación que podría cambiar el grado, la urgencia o la conducta. Usa setContingencyPlan: la contingencia define qué se espera, cuánto silencio tolerar y, si corresponde, la escalada posterior. Nunca la sustituyas por seguimiento ni por recordatorio.',
344
+ 'Regla de desempate: si esperas saber “cómo sigue” por continuidad, es seguimiento; si la paciente pidió explícitamente o aceptó que le recuerdes hacer algo, es recordatorio; si esperas un dato porque no tenerlo podría volver insegura la conducta, es contingencia. Una tarea acordada o agendada sin esa petición no es un recordatorio. Una contingencia activa gana sólo mientras siga faltando su dato; cuando la resuelves porque la paciente ya lo dio o porque la preocupación quedó atendida, la vigilancia que queda es un seguimiento, no una red rearmada ni un cierre del tema. Una indicación del equipo de agendar o hacerse una visita o un estudio no resuelve por sí sola una red cuyo dato sigue faltando: la red se mantiene tal como está y, además, programa el seguimiento sobre la visita o el estudio: una red abierta no lo detiene.',
345
+ ].join('\n'),
346
+ }];
347
+ }
348
+
349
+ // Rides as a turn-scoped developer block, never as a stored message: a proactive brief is true for
350
+ // this morning only, and anything persisted into history would still read as a standing rule weeks later.
351
+ _buildOutreachBriefMessage({ outreachBrief = null, toolIds = [], allowFollowUp = true }) {
352
+ if (!outreachBrief || typeof outreachBrief !== 'object') return [];
353
+ if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
354
+
355
+ const lines = (entries) => entries
356
+ .map(([label, value, maxLength]) => {
357
+ const raw = Array.isArray(value) ? value.join(', ') : value;
358
+ const text = sanitizeInlineText(String(raw ?? ''), maxLength).trim();
359
+ return text ? `- ${label}: ${text}` : null;
360
+ })
361
+ .filter(Boolean);
362
+
363
+ if (outreachBrief.checkIn) return this._buildCheckInDueMessage(outreachBrief, lines);
364
+
365
+ const why = lines([
366
+ ['último triaje contestado', outreachBrief.lastTriageAt],
367
+ ['grado máximo en ese triaje', outreachBrief.maxGrade],
368
+ ['síntomas positivos', outreachBrief.positiveSymptoms],
369
+ ['motivo', outreachBrief.reason],
370
+ ]);
371
+ const since = lines([
372
+ ['último mensaje suyo', outreachBrief.lastInboundAt],
373
+ ['último mensaje tuyo', outreachBrief.lastOutboundAt],
374
+ ['contacto proactivo anterior', outreachBrief.lastOutreach],
375
+ ]);
376
+
377
+ const parts = [
378
+ '[CONTACTO PROACTIVO (prioritario) para este turno]',
379
+ 'Nadie te ha escrito. Te toca decidir si esta persona sabe de ti hoy, y con qué palabras.',
380
+ ];
381
+ if (why.length) parts.push('', '## Por qué aparece hoy', ...why);
382
+ if (since.length) parts.push('', '## Qué ha pasado desde entonces', ...since);
383
+ parts.push(
384
+ '',
385
+ ...(allowFollowUp ? [
386
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
387
+ 'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
388
+ ] : [
389
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora o sostener.`,
390
+ 'En este turno no programes seguimientos ni recordatorios, aunque otras reglas lo pidan: si te responde, la conversación decide lo que sigue. Si sostienes, deja next_check_at en null.',
391
+ ]),
392
+ '',
393
+ 'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
394
+ 'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
395
+ 'LÍMITE UTILITY: escribe sólo cuando puedas anclar el contacto en algo concreto que la paciente contó, preguntó o acordó, o en una interacción de cuidado todavía vigente. La inactividad por sí sola no basta. Si escribes, registra esa ancla en utility_basis; si sólo queda un saludo general para generar engagement, registra hold con hold_reason no_utility_anchor y utility_basis null. El mensaje tiene que nombrar esa ancla; preguntarle cómo se ha sentido o invitarla a escribir si tiene dudas no es un ancla.',
396
+ 'Debe entenderse por sí mismo: si mencionas fechas, un documento o algo que le enviaste, di cuáles. No enumeres señales de alarma; si vigilas algo concreto, menciona sólo esa señal y pídele que te escriba en cuanto aparezca.',
397
+ 'No repitas un mensaje que ya le enviaste, y no menciones automatizaciones, listas ni seguimientos programados.',
398
+ );
399
+
400
+ return [{ role: 'developer', content: parts.join('\n') }];
401
+ }
402
+
403
+ _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
404
+ const ago = (at) => {
405
+ const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
406
+ if (!Number.isFinite(minutes) || minutes < 0) return '';
407
+ return minutes < 60 ? ` (hace ${minutes} min)` : ` (hace ${Math.floor(minutes / 60)} h ${minutes % 60} min)`;
408
+ };
409
+ const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
410
+ const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
411
+ const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
412
+ const pending = lines([
413
+ ['este check-in', self],
414
+ ['tipo', checkIn.type === 'contingencia' ? 'red de contingencia' : 'seguimiento que programaste: esta pregunta todavía no le ha llegado'],
415
+ ['lo que querías preguntarle', checkIn.question],
416
+ ['por qué quedó abierto', checkIn.concern],
417
+ ['qué dato esperabas', checkIn.awaiting],
418
+ ['desde', local(checkIn.armedAt)],
419
+ ['nivel de la escalación', checkIn.urgency],
420
+ ]);
421
+ const conversation = lines([
422
+ ['su último mensaje', said(exchange?.patient), EXCHANGE_LINE_LENGTH],
423
+ ['tu último mensaje (tuyo o del equipo)', said(exchange?.own), EXCHANGE_LINE_LENGTH],
424
+ ['mensajes tuyos o del equipo hoy', exchange ? String(exchange.ownMessagesToday) : null],
425
+ ]);
426
+ const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
427
+ const parts = [
428
+ '[CHECK-IN QUE VENCE (prioritario) para este turno]',
429
+ 'Venció el plazo para retomar algo pendiente con esta persona. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a escribirle o si ya no hace falta.',
430
+ '', '## Qué quedó pendiente', ...pending,
431
+ ];
432
+ if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
433
+ parts.push(
434
+ '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
435
+ '',
436
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
437
+ '- Este check-in es el seguimiento que está venciendo ahora, aunque lo veas programado unos minutos más tarde: ya no está pendiente y no se puede actualizar. Si decides esperar, programa uno nuevo.',
438
+ '- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
439
+ '- Si tu último mensaje ya le hace esta pregunta o la cubre, y hoy estuvo en la conversación y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
440
+ '- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
441
+ '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
442
+ '- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
443
+ '- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
444
+ '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
445
+ exchange?.sessionOpen === false
446
+ ? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo a lo que quieres saber.'
447
+ : 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego entra a lo que quieres saber.',
448
+ 'En un seguimiento que programaste es la primera vez que se lo preguntas: no digas que ya se lo habías preguntado. En una red, si tu mensaje anterior ya se lo preguntó, dilo en pocas palabras («te había preguntado por…» o «le había preguntado por…», según cómo le hables). Esa única pregunta va por lo que sigue faltando de lo que esperabas saber; si lo que querías preguntarle trae varias, elige la que más importa hoy. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
449
+ 'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
450
+ 'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
451
+ );
452
+ return [{ role: 'developer', content: parts.join('\n') }];
453
+ }
454
+
455
+ _buildSkillCatalogMessage(skillCatalog) {
456
+ const described = (Array.isArray(skillCatalog) ? skillCatalog : []).filter((skill) => skill?.name && skill?.description);
457
+ if (!described.length) return [];
458
+ const lines = described.map((skill) => `- \`${sanitizeInlineText(skill.name)}\` — ${sanitizeInlineText(skill.description)}`);
459
+ return [{
460
+ role: 'developer',
461
+ content: `## Skills disponibles\nCada una se carga con \`Skill(skill="<nombre>")\`, que devuelve su cuerpo completo. La descripción dice qué cubre y cuándo cargarla.\n${lines.join('\n')}`,
462
+ }];
463
+ }
464
+
465
+ _buildContingencyRuleMessage({ toolIds = [], promptVariables = {} }) {
466
+ if (!isContingencyRuleBlockLive()) return [];
467
+ if (!(toolIds || []).includes('setContingencyPlan')) return [];
468
+ const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
469
+ if (active.some((net) => (net?.carePlan?.armedBy ?? 'agent') === 'agent')) return [];
470
+ if (!String(promptVariables?.last_symptoms || '').trim()) return [];
471
+ return [{
472
+ role: 'developer',
473
+ content: CONTINGENCY_RULE,
474
+ }];
475
+ }
476
+
477
+ _buildContingencyMessage(promptVariables) {
478
+ const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
479
+ const cancelled = Array.isArray(promptVariables?.cancelled_contingencies) ? promptVariables.cancelled_contingencies : [];
480
+ if (!active.length && !cancelled.length) return [];
481
+
482
+ // Free-text plan fields are model-authored, but they re-enter as developer-priority text:
483
+ // collapse whitespace and cap length so a stored field can never smuggle block structure.
484
+
485
+ const parts = ['## Redes de seguridad (contingencias)'];
486
+ for (const net of active) {
487
+ const plan = net?.carePlan || {};
488
+ const target = plan.relatedCaseId || plan.relatedClusterId || 'sin caso: vigila a la persona, no un síntoma';
489
+ const windows = net?.patientReminder?.firesAfterSilenceMinutes
490
+ ? `check-in al paciente tras ${net.patientReminder.firesAfterSilenceMinutes} min de silencio`
491
+ : '';
492
+ parts.push(`- ACTIVA ${plan.planId} — vigila: ${sanitizeInlineText(plan.concern)} (${target}). Espera observar: ${sanitizeInlineText(plan.awaitingCharacterization)}. ${windows}.`);
493
+ }
494
+ for (const net of cancelled) {
495
+ const plan = net?.carePlan || {};
496
+ parts.push(`- (este turno) ${plan.planId} — la red que vigilaba "${sanitizeInlineText(plan.concern)}" se desactivó automáticamente porque el paciente escribió. Si todavía falta un dato de la rúbrica que podría subir el grado, considera rearmarla con setContingencyPlan. Si ya no falta ese dato y sólo quieres saber cómo sigue, programa un seguimiento (schedulePatientReminder, reminder_type seguimiento) en lugar de rearmarla.`);
497
+ }
498
+ return [{ role: 'developer', content: parts.join('\n') }];
499
+ }
500
+
501
+ // Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
502
+ // because an unresolved net later asks the patient a question they had already answered.
503
+ // Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
504
+ // A net is marked fired before its own check-in turn runs, so during that turn its check-in has not reached the patient yet.
505
+ _buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
506
+ if (!(toolIds || []).includes('setContingencyPlan')) return [];
507
+ const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
508
+ if (!active.length) return [];
509
+ const dueNet = outreachBrief?.checkIn?.planId || null;
510
+ const waiting = active.map(({ carePlan: plan = {} } = {}) => {
511
+ let fired = '';
512
+ if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
513
+ else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
514
+ return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
515
+ });
516
+ return [{
517
+ role: 'developer',
518
+ content: [
519
+ '## Antes de entregar tu respuesta: redes activas',
520
+ ...waiting,
521
+ 'DECISIÓN ESTE TURNO: si el paciente ya respondió lo que una red espera después de que se armó — en este mensaje o en uno anterior, también cuando se lo contestó al equipo —, resuélvela ahora con setContingencyPlan {action: \'resolve\', plan_id: \'<plan>\', resolution_reasoning: \'…\'} o cierra el caso; si no, su check-in le volverá a preguntar lo mismo. Si cambió la preocupación o la ventana, usa {action: \'rearm\'}. Lo que el paciente contó antes de que se armara no cuenta, y una indicación del equipo tampoco es una respuesta. Si nada responde lo que espera, no hagas nada con la red.',
522
+ ].join('\n'),
523
+ [TAIL_PLACEMENT]: true,
524
+ }];
525
+ }
526
+
527
+ // Rides behind the history, next to the turn: a rule buried in the policy block above was not applied.
528
+ _buildFollowUpCheckMessage(toolIds = []) {
529
+ if (!(toolIds || []).includes('schedulePatientReminder')) return [];
530
+ return [{
531
+ role: 'developer',
532
+ content: [
533
+ '## Antes de entregar tu respuesta',
534
+ '- Si en esta respuesta indicas un medicamento, una medida de cuidado o que contacte a alguien (su médico, el dentista, urgencias), o transmites una indicación del equipo, programa en este turno un seguimiento con schedulePatientReminder (reminder_type seguimiento, utility_basis agreed_action) a 24–48 h: si fue un medicamento o una medida, para saber si funcionó; si fue una cita, visita o estudio, para saber si pudo agendarla o si ya fue y cuándo (el resultado se pregunta más adelante, cuando ya ocurrió). Nunca lo programes a más de 48 h. No lo hagas si ya hay un seguimiento que lo cubra o si la paciente pidió que no; una red abierta no lo impide. Pedirle «avísame cómo te va» no lo sustituye.',
535
+ '- Un síntoma físico nuevo o que empeora en una persona en tratamiento oncológico o que terminó quimio hace poco es clínico aunque parezca de otra especialidad: regístralo como síntoma y escálalo si corresponde; no lo mandes sólo como pedido non_oncology_medical.',
536
+ ].join('\n'),
537
+ [TAIL_PLACEMENT]: true,
538
+ }];
539
+ }
540
+
541
+ _buildFollowUpMessage(promptVariables) {
542
+ const pending = Array.isArray(promptVariables?.active_follow_ups) ? promptVariables.active_follow_ups : [];
543
+ if (!pending.length) return [];
544
+ const rows = pending.map((item) => `- ${sanitizeInlineText(item.reminderId)} a las ${localFireTime(item.fireAt)}: ${sanitizeInlineText(item.message, 600)}`);
545
+ return [{
546
+ role: 'developer',
547
+ content: [
548
+ '## Seguimientos ya programados',
549
+ ...rows,
550
+ 'Siguen pendientes aunque la paciente haya vuelto a escribir. Si esta conversación ya respondió su pregunta o la volvió innecesaria, cancélalo (schedulePatientReminder con reminder_action_type cancel y su reminder_id); si cambió lo que hay que preguntar o cuándo, actualízalo; si sigue valiendo, déjalo. No crees otro seguimiento que lo cruce.',
551
+ ].join('\n'),
552
+ [TAIL_PLACEMENT]: true,
553
+ }];
554
+ }
555
+
556
+ _buildClinicalMessage(promptVariables, interpolatedVariables = []) {
557
+ const inPrompt = new Set(interpolatedVariables);
558
+ const context = this._clinicalText(promptVariables?.clinical_context, 'clinical_context');
559
+ const symptoms = this._clinicalText(promptVariables?.last_symptoms, 'last_symptoms');
560
+ const parts = [];
561
+ if (context && !inPrompt.has('clinical_context')) {
562
+ parts.push(`## Contexto clínico del paciente\n${context}`);
563
+ }
564
+ if (symptoms && !inPrompt.has('last_symptoms')) {
565
+ parts.push(`## Síntomas recientes\n${symptoms}`);
566
+ }
567
+ const nutritionPlan = this._clinicalText(promptVariables?.nutrition_plan, 'nutrition_plan');
568
+ if (nutritionPlan && !inPrompt.has('nutrition_plan')) {
569
+ parts.push(`## Plan de nutrición indicado por el equipo (indicado; no asumas que el paciente ya lo cumple)\n${nutritionPlan}`);
570
+ }
571
+ if (parts.length === 0) return [];
572
+ // Refreshed most turns (symptoms, risks); ahead of the history it rewrote the whole cached
573
+ // conversation. Informational only, so it rides behind it like the clock. Directives stay in system.
574
+ return [{ role: 'developer', content: parts.join('\n\n'), [TAIL_PLACEMENT]: true }];
575
+ }
576
+
577
+ _clinicalText(value, field) {
578
+ if (typeof value === 'string') return value.trim();
579
+ if (value != null) {
580
+ logger.warn('[BaseLLMProvider] Non-string clinical variable, omitting from runtime context', { field, type: typeof value });
581
+ }
582
+ return '';
165
583
  }
166
584
 
167
585
  _buildMemoryMessage(promptVariables) {
@@ -172,6 +590,20 @@ class BaseLLMProvider {
172
590
  return [{ role: 'developer', content: `Usa la siguiente información que conoces del paciente para personalizar tu respuesta. Adapta tu tono, contenido o recomendaciones según estas preferencias y contexto cuando sea relevante. No menciones que tienes esta información almacenada.\n\n${memoryParts.join('\n\n')}` }];
173
591
  }
174
592
 
593
+ // The date is minute-granular, so it changes on every request. Anthropic renders system ahead of
594
+ // messages, so leaving it in the runtime system block rewrites the whole conversation each turn;
595
+ // TAIL_PLACEMENT moves it behind the history instead. Providers that ignore the marker keep
596
+ // rendering it where _buildInput puts it.
597
+ _buildClockMessage(promptVariables, interpolatedVariables = []) {
598
+ if (!promptVariables?.current_date) return [];
599
+ if (interpolatedVariables.includes('current_date')) return [];
600
+ return [{
601
+ role: 'developer',
602
+ content: `Fecha y hora actual: ${promptVariables.current_date}`,
603
+ [TAIL_PLACEMENT]: true,
604
+ }];
605
+ }
606
+
175
607
  async _invokeModel() {
176
608
  throw new Error(`${this.constructor.name} must implement _invokeModel()`);
177
609
  }
@@ -200,6 +632,7 @@ class BaseLLMProvider {
200
632
  ...config,
201
633
  threadId: conversationId,
202
634
  assistantId,
635
+ compactOlderTriage: true,
203
636
  }
204
637
  });
205
638
 
@@ -212,16 +645,33 @@ class BaseLLMProvider {
212
645
 
213
646
  logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
214
647
 
648
+ const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
215
649
  const override = config.clinicalData;
216
650
  const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
217
651
  const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
218
652
  const promptVariables = {
219
653
  clinical_context: clinicalData?.clinicalContext ?? '',
220
654
  last_symptoms: clinicalData?.lastSymptoms ?? '',
221
- current_date: getCurrentMexicoDateTime(),
655
+ nutrition_plan: clinicalData?.nutritionPlan ?? '',
656
+ current_date: buildDateAnchor(),
222
657
  patient_memories: clinicalData?.patientMemories ?? '',
223
658
  conversation_summaries: clinicalData?.conversationSummaries ?? '',
659
+ active_contingencies: config.contingencySnapshot?.surviving ?? [],
660
+ cancelled_contingencies: config.contingencySnapshot?.cancelled ?? [],
661
+ active_follow_ups: config.followUpSnapshot ?? [],
224
662
  };
663
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({
664
+ riskHeadlinePresent: typeof promptVariables.clinical_context === 'string'
665
+ && promptVariables.clinical_context.includes(RISK_HEADLINE_MARKER),
666
+ });
667
+
668
+ const { block, source } = await resolveClinicalContext({
669
+ patientId: thread.code,
670
+ legacyBlock: promptVariables.clinical_context,
671
+ });
672
+ const rtBlock = await radiotherapyBlock;
673
+ promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
674
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
225
675
 
226
676
  const result = await this.runConversation({
227
677
  threadId: conversationId,
@@ -240,18 +690,18 @@ class BaseLLMProvider {
240
690
  await this.conversationManager.processResponse(result, thread, config);
241
691
  this.sessionManager?.recordActivity(thread.code);
242
692
 
243
- const completed = result.status === 'completed';
244
- const output = result.output_text || this._extractMessageOutput(result);
693
+ const isCompleted = result.status === 'completed';
694
+ const output = result.output_text ?? '';
245
695
  const toolsExecuted = result.tools_executed?.length || 0;
246
696
 
247
697
  logger.info('[executeRun] Complete', {
248
698
  runId: result.id,
249
- completed,
699
+ completed: isCompleted,
250
700
  outputLength: output?.length || 0,
251
701
  toolsExecuted
252
702
  });
253
703
 
254
- return { run: result, completed, output, tools_executed: result.tools_executed || [], retries: result.retries || 0 };
704
+ return { run: result, completed: isCompleted, output, tools_executed: result.tools_executed || [], retries: result.retries || 0 };
255
705
  } catch (error) {
256
706
  logger.error('[executeRun] Failed', { conversationId, assistantId, error: error.message });
257
707
  throw error;
@@ -261,13 +711,59 @@ class BaseLLMProvider {
261
711
  async runConversation(config = {}) {
262
712
  const { threadId, assistantId } = config;
263
713
  const maxRetries = this.maxConversationRetries;
714
+ const isOutreach = config?.assistant?.toolRuntimeContext?.turnKind === TURN_KIND.PROACTIVE_OUTREACH;
264
715
 
265
716
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
266
717
  try {
267
718
  logger.info('[runConversation] Attempt', { attempt, maxRetries, threadId, assistantId });
719
+ // A retry starts from the original input, so a skill body handed over in an earlier attempt is not in context.
720
+ if (attempt > 1) {
721
+ config?.assistant?.toolRuntimeContext?.activatedSkills?.clear();
722
+ config?.assistant?.toolRuntimeContext?.skillActivationIteration?.clear();
723
+ }
268
724
 
269
725
  const result = await this._executeConversation(config);
270
- const extractedOutput = this._extractMessageOutput(result);
726
+ // DeliverPatientMessage is the curated patient reply; prefer it over any model narration in the final response.
727
+ const delivered = this._extractDeliveredMessage(config, result);
728
+ let extractedOutput = delivered?.trim() ? delivered : this._extractMessageOutput(result);
729
+
730
+ const recoveryUnavailable = config?.assistant?.toolRuntimeContext?.trace?.signals?.deliveryRecoveryUnavailable;
731
+ // Outreach has a two-part terminal contract: an explicit hold, or an explicit write plus a
732
+ // recorded patient message. Never turn silence into a flattering implicit hold, and never let
733
+ // a write decision reach the audit row when the model forgot DeliverPatientMessage.
734
+ if (isOutreach) {
735
+ const decision = config?.assistant?.toolRuntimeContext?.trace?.signals?.outreachDecision || null;
736
+ const hasDraft = Boolean(delivered?.trim());
737
+ const outreachCommitted = this._outreachCommitted(
738
+ result.tools_executed,
739
+ config?.assistant?.toolRuntimeContext?.outreachReminderType,
740
+ );
741
+ if (decision?.decision === 'hold' && !hasDraft && outreachCommitted) {
742
+ result.output_text = '';
743
+ return result;
744
+ }
745
+ if (decision?.decision !== 'write' || !hasDraft) {
746
+ const reason = !decision
747
+ ? 'decision_missing'
748
+ : (decision.decision === 'write'
749
+ ? 'delivery_missing'
750
+ : (decision.nextCheckAt ? 'planned_hold_without_reminder' : 'hold_with_delivery'));
751
+ config?.assistant?.toolRuntimeContext?.trace?.setSignals?.({ outreachContractIncomplete: reason });
752
+ logger.warn('[runConversation] Outreach contract incomplete', { attempt, threadId, reason });
753
+ result.output_text = '';
754
+ if (isSuperseded(config.shouldContinue)) return result;
755
+ if (attempt === maxRetries) {
756
+ throw new Error(`Outreach failed after ${attempt} attempts - ${reason}`);
757
+ }
758
+ await new Promise(r => setTimeout(r, 500));
759
+ continue;
760
+ }
761
+ }
762
+ if (!delivered?.trim() && this._deliveryExpected(result) && (extractedOutput?.trim() || recoveryUnavailable)) {
763
+ logger.warn('[runConversation] Delivery tool offered but never committed — substituting safe fallback for raw narration', { attempt, suppressedLength: extractedOutput?.length || 0 });
764
+ config?.assistant?.toolRuntimeContext?.trace?.setSignals?.({ deliveryFallbackUsed: true });
765
+ extractedOutput = this._deliveryFallbackMessage(config);
766
+ }
271
767
 
272
768
  if (extractedOutput?.trim()) {
273
769
  result.output_text = extractedOutput;
@@ -279,8 +775,8 @@ class BaseLLMProvider {
279
775
  return result;
280
776
  }
281
777
 
282
- if (config.shadow && !config.shouldContinue()) {
283
- logger.info('[runConversation] Shadow superseded — returning without retry', { attempt });
778
+ if (isSuperseded(config.shouldContinue)) {
779
+ logger.info('[runConversation] Superseded — returning without retry', { attempt, shadow: config.shadow });
284
780
  return result;
285
781
  }
286
782
 
@@ -290,17 +786,129 @@ class BaseLLMProvider {
290
786
  }
291
787
  await new Promise(r => setTimeout(r, 500));
292
788
  } catch (error) {
293
- logger.error('[runConversation] Attempt failed', { attempt, error: error.message });
294
- if (config.shadow && !config.shouldContinue()) {
295
- logger.info('[runConversation] Shadow superseded — abandoning after error', { attempt });
789
+ // Keyed on the signal, not the error type: an AbortError from some unrelated inner timeout is not a supersede.
790
+ const aborted = Boolean(config.signal?.aborted);
791
+ if (aborted || isSuperseded(config.shouldContinue)) {
792
+ logger.info('[runConversation] Superseded — abandoning after error', { attempt, shadow: config.shadow, aborted, error: error.message });
793
+ const ctx = config?.assistant?.toolRuntimeContext;
794
+ const abortCode = typeof config.signal?.reason?.code === 'string' ? config.signal.reason.code : null;
795
+ if (aborted && ctx) ctx.abort = { reason: abortCode || 'superseded', iteration: ctx.trace ? (ctx.trace.iterations?.length ?? 0) + 1 : null };
296
796
  return { status: 'cancelled', output_text: '', tools_executed: [], retries: 0 };
297
797
  }
298
- if (attempt === maxRetries) throw error;
798
+ if (attempt === maxRetries) {
799
+ logger.error('[runConversation] Attempt failed', { attempt, error: error.message });
800
+ throw error;
801
+ }
802
+ logger.warn('[runConversation] Attempt failed, retrying', { attempt, maxRetries, error: error.message });
299
803
  await new Promise(r => setTimeout(r, 500));
300
804
  }
301
805
  }
302
806
  }
303
807
 
808
+ _toolSucceeded(t) {
809
+ // The executor sets success=true unless the call threw; a tool can also fail by returning {success:false} in its output.
810
+ if (!t || t.success === false) return false;
811
+ if (isToolFailure(t.tool_output)) return false;
812
+ return true;
813
+ }
814
+
815
+ _unavailableToolRecovery(toolsExecuted, toolSchemas) {
816
+ const offered = new Set((toolSchemas || []).map(schema => schema.function?.name).filter(Boolean));
817
+ for (const tool of toolsExecuted || []) {
818
+ if (this._toolSucceeded(tool)) continue;
819
+ const recovery = toolRecoveryContract(tool?.tool_output);
820
+ if (recovery && !recovery.requiredToolIds.some(toolId => offered.has(toolId))) {
821
+ return {
822
+ toolName: tool.tool_name,
823
+ ...recovery,
824
+ };
825
+ }
826
+ }
827
+ return null;
828
+ }
829
+
830
+ _deliveryCommitted(toolsExecuted) {
831
+ return (toolsExecuted || []).some(t => TERMINAL_DELIVERY_TOOLS.has(t?.tool_name) && this._toolSucceeded(t));
832
+ }
833
+
834
+ _conversationalDraftToReuse(roundTools, previousRoundTools) {
835
+ if ((roundTools || []).length !== 1) return null;
836
+ const [intake] = roundTools;
837
+ if (intake?.tool_name !== EXTRACTION_TOOL || !this._toolSucceeded(intake)) return null;
838
+ if (safeParse(intake.tool_output)?.data?.non_clinical_request !== CONVERSATIONAL_REQUEST) return null;
839
+ const refused = (previousRoundTools || []).filter(t => TERMINAL_DELIVERY_TOOLS.has(t?.tool_name)).at(-1);
840
+ if (!refused || safeParse(refused.tool_output)?.error !== REFUSAL.intakeBeforeDelivery) return null;
841
+ return refused;
842
+ }
843
+
844
+ _outreachCommitted(toolsExecuted, reminderType = 'seguimiento') {
845
+ const successful = (toolsExecuted || []).filter(t => t?.tool_name === OUTREACH_DECISION_TOOL && this._toolSucceeded(t));
846
+ const args = successful.at(-1)?.tool_arguments || {};
847
+ const decision = args.decision;
848
+ if (decision === 'hold' && !args.next_check_at) return true;
849
+ if (decision === 'hold') {
850
+ const decidedMinute = outreachMinute(args.next_check_at);
851
+ const allowedTypes = reminderType === 'otros' ? ['otros'] : ['seguimiento', 'check_in'];
852
+ return (toolsExecuted || []).some((t) => t?.tool_name === 'schedulePatientReminder'
853
+ && this._toolSucceeded(t)
854
+ && allowedTypes.includes(t?.tool_arguments?.reminder_type)
855
+ && outreachMinute(t?.tool_arguments?.reminder_date) === decidedMinute);
856
+ }
857
+ return decision === 'write' && this._deliveryCommitted(toolsExecuted);
858
+ }
859
+
860
+ _deliveryExpected(result) {
861
+ return (result?.tool_ids || []).some(id => TERMINAL_DELIVERY_TOOLS.has(id));
862
+ }
863
+
864
+ _deliveryFallbackMessage(config) {
865
+ const key = String(config?.assistant?.toolRuntimeContext?.turnId
866
+ ?? config?.assistant?.toolRuntimeContext?.patientCode
867
+ ?? config?.threadId ?? '');
868
+ let hash = 0;
869
+ for (let i = 0; i < key.length; i++) hash = (hash * 31 + key.charCodeAt(i)) | 0;
870
+ return DELIVERY_FALLBACK_MESSAGES[Math.abs(hash) % DELIVERY_FALLBACK_MESSAGES.length];
871
+ }
872
+
873
+ _bridgeFrom(calls) {
874
+ const pick = (name, field) => {
875
+ const value = calls.find(call => call.name === name)?.input?.[field];
876
+ return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
877
+ };
878
+ const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
879
+ if (pick(EXTRACTION_TOOL, 'non_clinical_request') && pick(EXTRACTION_TOOL, 'raw_message') && extraction?.detected_tags?.length === 0) {
880
+ return { text: null, reasoning: null };
881
+ }
882
+ const authored = pick(BRIDGE_TOOL, 'message_text');
883
+ if (authored) return { text: authored, reasoning: pick(BRIDGE_TOOL, 'reasoning') };
884
+ return { text: pick(EXTRACTION_TOOL, 'bridge_text'), reasoning: pick(EXTRACTION_TOOL, 'bridge_reasoning') };
885
+ }
886
+
887
+ _isTerminalOnly(toolNames) {
888
+ return toolNames.length > 0 && toolNames.every(name => TERMINAL_DELIVERY_TOOLS.has(name));
889
+ }
890
+
891
+ _applyDeliveryFloor(toolChoice, toolSchemas, hasToolRuntimeContext = false, turnKind = null) {
892
+ // A proactive turn must be able to act clinically on what it finds, and to end without writing.
893
+ // Narrowing to the delivery tool would make both impossible.
894
+ if (turnKind === TURN_KIND.PROACTIVE_OUTREACH) return { toolChoice, toolSchemas, narrowed: false };
895
+ if (toolChoice !== 'none') return { toolChoice, toolSchemas, narrowed: false };
896
+ if (!hasToolRuntimeContext) return { toolChoice, toolSchemas, narrowed: false };
897
+ const deliveryOnly = toolSchemas.filter(s => TERMINAL_DELIVERY_TOOLS.has(s.function?.name));
898
+ if (!deliveryOnly.length) return { toolChoice, toolSchemas, narrowed: false };
899
+ return { toolChoice: 'auto', toolSchemas: deliveryOnly, narrowed: true };
900
+ }
901
+
902
+ _extractDeliveredMessage(config, result) {
903
+ const executed = Array.isArray(result?.tools_executed) ? result.tools_executed : [];
904
+ // Only count a delivery from THIS run, so a stale/prior trace.outbound can't leak in.
905
+ const hasDelivered = executed.some(t => t?.tool_name === 'DeliverPatientMessage' && this._toolSucceeded(t));
906
+ if (!hasDelivered) return '';
907
+ // trace.outbound is the decoded/rendered outbound the handler wrote; message_text (raw tool arg) may be PHI-tokenized, so it is not used.
908
+ const traceOutbound = config?.assistant?.toolRuntimeContext?.trace?.outbound;
909
+ return (typeof traceOutbound === 'string' && traceOutbound.trim()) ? traceOutbound : '';
910
+ }
911
+
304
912
  _normalizeThread(thread) {
305
913
  return {
306
914
  conversationId: thread.conversation_id || thread.getConversationId?.(),
@@ -308,6 +916,11 @@ class BaseLLMProvider {
308
916
  };
309
917
  }
310
918
 
919
+ // Providers that pin runtime messages around the tail-placed block override this.
920
+ _orderRuntimeMessages(input) {
921
+ return input;
922
+ }
923
+
311
924
  _sanitizeInput(input) {
312
925
  const isMessage = (item) => !item.type || item.type === 'message';
313
926
  const items = (input || []).filter(item => isMessage(item) ? this._hasTextContent(item.content) : true);
@@ -341,11 +954,13 @@ class BaseLLMProvider {
341
954
  if (type === 'function_call' || type === 'function_call_output') {
342
955
  return { ...item, type };
343
956
  }
344
- return {
957
+ const converted = {
345
958
  role: item.role || 'user',
346
959
  type,
347
960
  content: this._normalizeContent(item.content)
348
961
  };
962
+ if (item[CURRENT_TURN]) converted[CURRENT_TURN] = true;
963
+ return converted;
349
964
  });
350
965
  }
351
966
 
@@ -362,10 +977,23 @@ class BaseLLMProvider {
362
977
  return typeof part.text === 'string' ? part.text : (typeof part.text?.value === 'string' ? part.text.value : '');
363
978
  }
364
979
 
980
+ _aggregatedPatientText(context) {
981
+ if (!Array.isArray(context)) return null;
982
+ for (let i = context.length - 1; i >= 0; i -= 1) {
983
+ const block = extractPatientMessage(this._messageItemToText(context[i]));
984
+ if (block) return block;
985
+ }
986
+ return null;
987
+ }
988
+
365
989
  _messageItemToText(item) {
366
990
  if (!item) return '';
367
991
  if (Array.isArray(item.content)) {
368
- return item.content.map(c => this._contentPartToText(c)).filter(Boolean).join('').trim();
992
+ return item.content
993
+ .map(part => (typeof part === 'string' ? part : this._contentPartToText(part)))
994
+ .filter(Boolean)
995
+ .join('')
996
+ .trim();
369
997
  }
370
998
  if (typeof item.content === 'string') return item.content.trim();
371
999
  return '';
@@ -437,4 +1065,13 @@ class BaseLLMProvider {
437
1065
  module.exports = {
438
1066
  BaseLLMProvider,
439
1067
  CONVERSATION_CONTINUATION,
1068
+ TAIL_PLACEMENT,
1069
+ DELIVERY_NUDGE,
1070
+ MAX_DELIVERY_NUDGES,
1071
+ DELIVERY_FALLBACK_MESSAGES,
1072
+ TERMINAL_DELIVERY_TOOLS,
1073
+ OUTREACH_DECISION_TOOL,
1074
+ OUTREACH_NUDGE,
1075
+ BRIDGE_TOOL,
1076
+ isSuperseded,
440
1077
  };