@peopl-health/nexus 6.0.0-dev.718 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -1,30 +1,92 @@
|
|
|
1
1
|
const { Anthropic } = require('@anthropic-ai/sdk');
|
|
2
2
|
|
|
3
|
+
const { OPERATOR_TURN_PREFIX } = require('../memory/DefaultMemoryManager');
|
|
4
|
+
const { ROUTING_SKILL } = require('../helpers/clinicalWorkflowGuard');
|
|
5
|
+
const { appendCall } = require('../services/llmAuditService');
|
|
6
|
+
const { composePrompt } = require('../services/promptComposerService');
|
|
7
|
+
const { RISK_HEADLINE_MARKER, RISK_HEADLINE_DISCLAIMER } = require('../services/riskHeadlineService');
|
|
8
|
+
const { isConversationalDraftReuseLive } = require('../flags/turnEfficiencyFlags');
|
|
3
9
|
const { retryWithBackoff } = require('../../utils/retryUtils');
|
|
4
10
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
11
|
+
const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
|
|
5
12
|
|
|
6
13
|
const { logger } = require('../../utils/logger');
|
|
7
14
|
|
|
8
15
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
9
16
|
|
|
10
|
-
const {
|
|
17
|
+
const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
|
|
18
|
+
const { BaseLLMProvider, CONVERSATION_CONTINUATION, DELIVERY_NUDGE, MAX_DELIVERY_NUDGES, TERMINAL_DELIVERY_TOOLS, OUTREACH_DECISION_TOOL, OUTREACH_NUDGE, isSuperseded } = require('./BaseLLMProvider');
|
|
11
19
|
const { handleFunctionCalls } = require('./OpenAIResponsesProviderTools');
|
|
12
20
|
|
|
13
|
-
|
|
21
|
+
function markHistoryBreakpoint(messages, historyEnd) {
|
|
22
|
+
if (historyEnd < 0 || historyEnd >= messages.length - 1) return;
|
|
23
|
+
const target = messages[historyEnd];
|
|
24
|
+
if (typeof target.content === 'string') {
|
|
25
|
+
target.content = [{ type: 'text', text: target.content, cache_control: { type: 'ephemeral', ttl: '5m' } }];
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (Array.isArray(target.content) && target.content.length) {
|
|
29
|
+
const last = target.content.length - 1;
|
|
30
|
+
target.content = target.content.map((block, i) => (
|
|
31
|
+
i === last ? { ...block, cache_control: { type: 'ephemeral', ttl: '5m' } } : block
|
|
32
|
+
));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const DEFAULT_MAX_FUNCTION_ROUNDS = 12;
|
|
37
|
+
|
|
38
|
+
function resolveMaxFunctionRounds(explicit) {
|
|
39
|
+
if (Number.isInteger(explicit) && explicit > 0) return explicit;
|
|
40
|
+
const raw = runtimeConfig.get('MAX_FUNCTION_ROUNDS');
|
|
41
|
+
const n = parseInt(raw, 10);
|
|
42
|
+
if (n > 0) return n;
|
|
43
|
+
if (raw !== undefined) {
|
|
44
|
+
logger.warn('[AnthropicProvider] Invalid MAX_FUNCTION_ROUNDS, falling back to default', { value: raw, default: DEFAULT_MAX_FUNCTION_ROUNDS });
|
|
45
|
+
}
|
|
46
|
+
return DEFAULT_MAX_FUNCTION_ROUNDS;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 120000;
|
|
50
|
+
const REQUEST_MAX_RETRIES = 0;
|
|
51
|
+
const STRUCTURED_TIMEOUT_BASE_MS = 30000;
|
|
52
|
+
const STRUCTURED_MS_PER_OUTPUT_TOKEN = 25;
|
|
53
|
+
|
|
54
|
+
function resolveRequestTimeoutMs() {
|
|
55
|
+
const raw = runtimeConfig.get('ANTHROPIC_TIMEOUT_MS');
|
|
56
|
+
const timeoutMs = parseInt(raw, 10);
|
|
57
|
+
if (timeoutMs > 0) return timeoutMs;
|
|
58
|
+
if (raw !== undefined) {
|
|
59
|
+
logger.warn('[AnthropicProvider] Invalid ANTHROPIC_TIMEOUT_MS, falling back to default', { value: raw, default: DEFAULT_REQUEST_TIMEOUT_MS });
|
|
60
|
+
}
|
|
61
|
+
return DEFAULT_REQUEST_TIMEOUT_MS;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function structuredTimeoutMs(maxTokens, requestTimeoutMs) {
|
|
65
|
+
return Math.max(requestTimeoutMs, STRUCTURED_TIMEOUT_BASE_MS + maxTokens * STRUCTURED_MS_PER_OUTPUT_TOKEN);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Iterations that don't count against the tool budget: terminal-only delivery rounds (exempt at the toolRounds check) plus the loop's own end/break passes. Bounds the loop against a misbehaving model.
|
|
69
|
+
const LOOP_ITERATION_HEADROOM = 3;
|
|
14
70
|
const CACHE_TTLS = ['5m', '1h'];
|
|
15
71
|
const DEFAULT_CACHE_TTL = '1h';
|
|
72
|
+
// Toggling thinking mid-turn invalidates the message cache, so the next call rewrites the whole history.
|
|
73
|
+
const DEFAULT_THINKING_MODE = 'always';
|
|
74
|
+
// Turns that end the model's clinical reasoning for the turn; after one, until_commit stops thinking.
|
|
75
|
+
const TERMINAL_COMMIT_TOOLS = new Set(['submitRoutingDecision', 'reportMedicalEscalation', 'reportCrisis', 'reportUnresolvedRequestv2']);
|
|
76
|
+
const ROUTING_TOOL = 'submitRoutingDecision';
|
|
16
77
|
|
|
17
78
|
class AnthropicProvider extends BaseLLMProvider {
|
|
18
79
|
constructor(options = {}) {
|
|
19
80
|
super(options);
|
|
20
|
-
const { apiKey, client, maxFunctionRounds
|
|
81
|
+
const { apiKey, client, maxFunctionRounds, defaultModels = {} } = options;
|
|
21
82
|
|
|
22
83
|
if (!client && !apiKey) {
|
|
23
84
|
throw new Error('AnthropicProvider requires an API key or a preconfigured client');
|
|
24
85
|
}
|
|
25
86
|
|
|
26
|
-
this.
|
|
27
|
-
this.
|
|
87
|
+
this.requestTimeoutMs = resolveRequestTimeoutMs();
|
|
88
|
+
this.client = client || new Anthropic({ apiKey, timeout: this.requestTimeoutMs, maxRetries: REQUEST_MAX_RETRIES });
|
|
89
|
+
this.maxFunctionRounds = resolveMaxFunctionRounds(maxFunctionRounds);
|
|
28
90
|
const cacheTtl = runtimeConfig.get('ANTHROPIC_CACHE_TTL', DEFAULT_CACHE_TTL);
|
|
29
91
|
if (!CACHE_TTLS.includes(cacheTtl)) {
|
|
30
92
|
logger.warn('[AnthropicProvider] Invalid ANTHROPIC_CACHE_TTL, falling back to default', { cacheTtl, default: DEFAULT_CACHE_TTL });
|
|
@@ -32,6 +94,8 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
32
94
|
this.cacheTtl = CACHE_TTLS.includes(cacheTtl) ? cacheTtl : DEFAULT_CACHE_TTL;
|
|
33
95
|
this.defaults = {
|
|
34
96
|
maxOutputTokens: 400,
|
|
97
|
+
structuredModel: 'claude-haiku-4-5',
|
|
98
|
+
structuredMaxTokens: 2048,
|
|
35
99
|
...defaultModels,
|
|
36
100
|
};
|
|
37
101
|
|
|
@@ -41,7 +105,9 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
41
105
|
|
|
42
106
|
async _invokeModel({
|
|
43
107
|
instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
|
|
44
|
-
modelConfig, assistant, phiProcessor = null, trace = null
|
|
108
|
+
modelConfig, assistant, phiProcessor = null, trace = null, onFirstIteration = null,
|
|
109
|
+
resolvedPromptId = null, resolvedPresetId = null, shouldContinue = null, signal = null,
|
|
110
|
+
isOutreach = false
|
|
45
111
|
}, options = {}) {
|
|
46
112
|
const executeTools = options.toolExecutor || handleFunctionCalls;
|
|
47
113
|
let totalRetries = 0;
|
|
@@ -58,30 +124,163 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
58
124
|
|
|
59
125
|
const { system, messages } = this._toAnthropicMessages(instructions, input);
|
|
60
126
|
const apiCallConfig = { ...this._mapModelConfig(modelConfig) };
|
|
127
|
+
// Captured before prepThinking() starts toggling apiCallConfig.thinking per call, so both the per-iteration gate and the
|
|
128
|
+
// tool_choice coercion read the same preset value rather than whichever iteration's state happens to be current.
|
|
129
|
+
const baseThinking = apiCallConfig.thinking;
|
|
130
|
+
const isThinkingEnabled = baseThinking?.type === 'enabled';
|
|
131
|
+
const initialChoice = this._mapToolChoice(toolChoice);
|
|
132
|
+
// Only a request that actually carried the forced choice was coerced; with zero tools tool_choice was never sent.
|
|
133
|
+
const isToolChoiceCoerced = toolSchemas.length > 0 && isThinkingEnabled && (initialChoice.type === 'tool' || initialChoice.type === 'any');
|
|
61
134
|
if (system) apiCallConfig.system = system;
|
|
135
|
+
// Second breakpoint, auto-placed on the newest turn. 5m and not ANTHROPIC_CACHE_TTL, which tunes the system block: history is turn-scoped, so a 1h write costs 2x for reuse that never comes.
|
|
136
|
+
apiCallConfig.cache_control = { type: 'ephemeral', ttl: '5m' };
|
|
62
137
|
if (toolSchemas.length > 0) {
|
|
63
138
|
apiCallConfig.tools = this._mapTools(toolSchemas);
|
|
64
|
-
apiCallConfig.tool_choice = this.
|
|
139
|
+
apiCallConfig.tool_choice = this._resolveToolChoice(toolChoice, isThinkingEnabled);
|
|
65
140
|
}
|
|
66
141
|
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
)
|
|
142
|
+
const thinkingMode = modelConfig?.thinking_mode || DEFAULT_THINKING_MODE;
|
|
143
|
+
let modelCallNum = 0;
|
|
144
|
+
let hasSeenTerminalCommit = false;
|
|
145
|
+
const prepThinking = () => {
|
|
146
|
+
modelCallNum += 1;
|
|
147
|
+
if (baseThinking && this._thinkingForIter(modelCallNum, thinkingMode, hasSeenTerminalCommit)) apiCallConfig.thinking = baseThinking;
|
|
148
|
+
else delete apiCallConfig.thinking;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const betas = Array.isArray(modelConfig?.betas) ? modelConfig.betas.filter(b => typeof b === 'string' && b.length) : [];
|
|
152
|
+
// interleaved-thinking requires thinking enabled on the call; drop it on iters the gate turned thinking off.
|
|
153
|
+
const activeBetas = () => (apiCallConfig.thinking ? betas : betas.filter(b => !b.startsWith('interleaved-thinking')));
|
|
154
|
+
const makeAPICall = (msgs) => {
|
|
155
|
+
const active = activeBetas();
|
|
156
|
+
const requestOptions = (active.length || signal)
|
|
157
|
+
? {
|
|
158
|
+
...(active.length ? { headers: { 'anthropic-beta': active.join(',') } } : {}),
|
|
159
|
+
...(signal ? { signal } : {}),
|
|
160
|
+
}
|
|
161
|
+
: undefined;
|
|
162
|
+
return retryWithBackoff(
|
|
163
|
+
() => this.client.messages.create({ messages: msgs, ...apiCallConfig }, requestOptions),
|
|
164
|
+
{ providerName: this.constructor.name }
|
|
165
|
+
);
|
|
166
|
+
};
|
|
167
|
+
const auditCall = (response, msgs, durationMs) => void appendCall({
|
|
168
|
+
metadata: {
|
|
169
|
+
source: 'conversation',
|
|
170
|
+
turnId: assistant?.toolRuntimeContext?.turnId,
|
|
171
|
+
code: assistant?.toolRuntimeContext?.patientCode,
|
|
172
|
+
iterationIndex: modelCallNum - 1,
|
|
173
|
+
resolvedPromptId,
|
|
174
|
+
resolvedPresetId,
|
|
175
|
+
},
|
|
176
|
+
request: { messages: msgs, config: { ...apiCallConfig, betas: activeBetas() } },
|
|
177
|
+
response,
|
|
178
|
+
durationMs,
|
|
179
|
+
});
|
|
71
180
|
|
|
181
|
+
prepThinking();
|
|
72
182
|
const { result: { result: response, retries }, durationMs } = await withTiming(() => makeAPICall(messages));
|
|
73
183
|
totalRetries += retries;
|
|
74
184
|
addUsage(response.usage);
|
|
75
185
|
let producingIteration = trace?.addIteration({ response, durationMs, apiCallConfig }) || null;
|
|
186
|
+
auditCall(response, messages, durationMs);
|
|
76
187
|
let finalResponse = response;
|
|
77
188
|
const currentMessages = [...messages];
|
|
78
189
|
|
|
190
|
+
// Coercion is silent-by-default; the event that matters is the model then *declining* the forced tool under 'auto'.
|
|
191
|
+
if (isToolChoiceCoerced) {
|
|
192
|
+
const toolUses = (response.content || []).filter(block => block.type === 'tool_use');
|
|
193
|
+
// A named force ('tool') is satisfied only by THAT tool; 'any'/'required' by any tool_use. Partial compliance
|
|
194
|
+
// (e.g. DeliverPatientMessage fires but the forced reportUnresolvedRequestv2 does not) must count as skipped.
|
|
195
|
+
const hasFiredTool = initialChoice.type === 'tool'
|
|
196
|
+
? toolUses.some(block => block.name === initialChoice.name)
|
|
197
|
+
: toolUses.length > 0;
|
|
198
|
+
trace?.setSignals?.({ toolChoiceCoerced: true, forcedToolSkipped: !hasFiredTool });
|
|
199
|
+
if (!hasFiredTool) {
|
|
200
|
+
logger.warn('[AnthropicProvider] Forced tool skipped after coercion to auto under thinking', { requested: initialChoice.type, tool: initialChoice.name || null });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let bridgeNote = null;
|
|
205
|
+
if (onFirstIteration) {
|
|
206
|
+
const narrationText = (response.content || [])
|
|
207
|
+
.filter(block => block.type === 'text')
|
|
208
|
+
.map(block => block.text || '')
|
|
209
|
+
.join(' ')
|
|
210
|
+
.trim();
|
|
211
|
+
const iterationToolUses = (response.content || []).filter(block => block.type === 'tool_use');
|
|
212
|
+
const iterationToolNames = iterationToolUses.map(block => block.name);
|
|
213
|
+
const hasToolCalls = Boolean(assistant) && toolSchemas.length > 0
|
|
214
|
+
&& response.stop_reason === 'tool_use'
|
|
215
|
+
&& iterationToolNames.length > 0;
|
|
216
|
+
const { text: bridgeText, reasoning: bridgeReasoning } = this._bridgeFrom(iterationToolUses);
|
|
217
|
+
try {
|
|
218
|
+
const decision = onFirstIteration({ narrationText, bridgeText, bridgeReasoning, hasToolCalls, deliveryOnly: this._isTerminalOnly(iterationToolNames) });
|
|
219
|
+
if (decision?.dedupNote) bridgeNote = decision.dedupNote;
|
|
220
|
+
} catch (err) {
|
|
221
|
+
logger.warn('[AnthropicProvider] bridge callback failed', { error: err.message });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
79
225
|
if (assistant && toolSchemas.length > 0) {
|
|
80
|
-
|
|
226
|
+
// Defensive: followUpToolChoice is the run-level value (already 'auto'/'none' on the classifier path); a forced value only
|
|
227
|
+
// reaches here from a caller that sets one at run level (e.g. EvalProvider).
|
|
228
|
+
apiCallConfig.tool_choice = this._resolveToolChoice(followUpToolChoice, isThinkingEnabled);
|
|
229
|
+
const canDeliver = toolSchemas.some(s => TERMINAL_DELIVERY_TOOLS.has(s.function?.name));
|
|
230
|
+
// On a proactive turn the terminal act is the DECISION, not the message: holding is a valid ending,
|
|
231
|
+
// so nudging toward delivery would coerce a send nobody asked for.
|
|
232
|
+
const canDecide = isOutreach && toolSchemas.some(s => s.function?.name === OUTREACH_DECISION_TOOL);
|
|
233
|
+
const nudgeText = canDecide ? OUTREACH_NUDGE : DELIVERY_NUDGE;
|
|
234
|
+
const turnCommitted = () => (canDecide
|
|
235
|
+
? this._outreachCommitted(allToolsExecuted, assistant?.toolRuntimeContext?.outreachReminderType)
|
|
236
|
+
: this._deliveryCommitted(allToolsExecuted));
|
|
237
|
+
const nudgeGateOpen = canDecide || canDeliver;
|
|
238
|
+
|
|
239
|
+
let toolRounds = 0;
|
|
240
|
+
let previousRoundTools = [];
|
|
241
|
+
let deliveryNudges = 0;
|
|
242
|
+
let shouldBreakForDelivery = false;
|
|
243
|
+
let shouldBreakForUnavailableRecovery = false;
|
|
244
|
+
const maxIterations = this.maxFunctionRounds + MAX_DELIVERY_NUDGES + LOOP_ITERATION_HEADROOM;
|
|
245
|
+
for (let iteration = 1; iteration <= maxIterations; iteration++) {
|
|
246
|
+
if (isSuperseded(shouldContinue)) {
|
|
247
|
+
logger.info('[AnthropicProvider] turn superseded — aborting tool loop', { iteration });
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
const content = finalResponse.content || [];
|
|
251
|
+
const toolUses = content.filter(block => block.type === 'tool_use');
|
|
252
|
+
const hasEnded = finalResponse.stop_reason !== 'tool_use' || !toolUses.length;
|
|
253
|
+
const terminalOnly = this._isTerminalOnly(toolUses.map(block => block.name));
|
|
254
|
+
const isBudgetSpent = toolRounds >= this.maxFunctionRounds && !terminalOnly;
|
|
255
|
+
|
|
256
|
+
// Nudge on an actual delivery, not narration: a text block is not a patient message, so a turn ending in
|
|
257
|
+
// narration without DeliverPatientMessage still nudges. Rides on the last user turn (empty completions carry no content to echo).
|
|
258
|
+
if ((hasEnded || isBudgetSpent) && nudgeGateOpen && !turnCommitted() && deliveryNudges < MAX_DELIVERY_NUDGES) {
|
|
259
|
+
const lastUserTurn = currentMessages[currentMessages.length - 1];
|
|
260
|
+
if (lastUserTurn?.role === 'user') {
|
|
261
|
+
deliveryNudges++;
|
|
262
|
+
previousRoundTools = [];
|
|
263
|
+
trace?.setSignals?.({ deliveryNudges, nudgeKind: canDecide ? 'outreach' : 'delivery' });
|
|
264
|
+
logger.warn('[AnthropicProvider] Turn will not close — nudging', { tool: canDecide ? OUTREACH_DECISION_TOOL : 'DeliverPatientMessage', deliveryNudges, hasEnded, isBudgetSpent });
|
|
265
|
+
const turnContent = Array.isArray(lastUserTurn.content)
|
|
266
|
+
? lastUserTurn.content
|
|
267
|
+
: [{ type: 'text', text: String(lastUserTurn.content ?? '') }];
|
|
268
|
+
const hasAlreadyNudged = turnContent.some(part => part?.type === 'text' && part.text === nudgeText);
|
|
269
|
+
if (!hasAlreadyNudged) lastUserTurn.content = [...turnContent, { type: 'text', text: nudgeText }];
|
|
270
|
+
// The nudge is a model call like any other: gate thinking on it so the per-iteration counter stays honest.
|
|
271
|
+
prepThinking();
|
|
272
|
+
const { result: { result: nudged, retries: nudgeRetries }, durationMs: nudgeDurationMs } = await withTiming(() => makeAPICall(currentMessages));
|
|
273
|
+
totalRetries += nudgeRetries;
|
|
274
|
+
addUsage(nudged.usage);
|
|
275
|
+
producingIteration = trace?.addIteration({ response: nudged, durationMs: nudgeDurationMs, apiCallConfig }) || null;
|
|
276
|
+
auditCall(nudged, currentMessages, nudgeDurationMs);
|
|
277
|
+
finalResponse = nudged;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
81
281
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if (finalResponse.stop_reason !== 'tool_use' || !toolUses.length) break;
|
|
282
|
+
if (hasEnded || isBudgetSpent) break;
|
|
283
|
+
if (!terminalOnly) toolRounds++;
|
|
85
284
|
|
|
86
285
|
const functionCalls = toolUses.map(block => ({
|
|
87
286
|
name: block.name,
|
|
@@ -91,47 +290,232 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
91
290
|
allToolCalls.push(...toolUses.map(block => ({ name: block.name, arguments: block.input ?? {}, call_id: block.id })));
|
|
92
291
|
const { outputs, toolsExecuted } = await executeTools(functionCalls, assistant, phiProcessor, producingIteration);
|
|
93
292
|
|
|
293
|
+
const userContent = outputs.map(o => ({ type: 'tool_result', tool_use_id: o.call_id, content: o.output }));
|
|
294
|
+
if (bridgeNote) {
|
|
295
|
+
userContent.push({ type: 'text', text: bridgeNote });
|
|
296
|
+
bridgeNote = null;
|
|
297
|
+
}
|
|
94
298
|
currentMessages.push(
|
|
95
299
|
{ role: 'assistant', content: finalResponse.content },
|
|
96
|
-
{ role: 'user', content:
|
|
300
|
+
{ role: 'user', content: userContent }
|
|
97
301
|
);
|
|
98
302
|
allToolsExecuted.push(...toolsExecuted);
|
|
303
|
+
const draft = !isOutreach && isConversationalDraftReuseLive() && !isSuperseded(shouldContinue)
|
|
304
|
+
? this._conversationalDraftToReuse(toolsExecuted, previousRoundTools)
|
|
305
|
+
: null;
|
|
306
|
+
previousRoundTools = toolsExecuted;
|
|
307
|
+
if (draft) {
|
|
308
|
+
const reuseCall = { name: draft.tool_name, arguments: JSON.stringify(draft.tool_arguments ?? {}), call_id: `${draft.call_id}:reuse` };
|
|
309
|
+
allToolCalls.push({ name: reuseCall.name, arguments: draft.tool_arguments ?? {}, call_id: reuseCall.call_id });
|
|
310
|
+
const { toolsExecuted: reused } = await executeTools([reuseCall], assistant, phiProcessor, producingIteration);
|
|
311
|
+
allToolsExecuted.push(...reused);
|
|
312
|
+
if (this._deliveryCommitted(reused)) {
|
|
313
|
+
trace?.setSignals?.({ conversationalDraftReused: true });
|
|
314
|
+
shouldBreakForDelivery = true;
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (toolsExecuted.some(t => this._endsClinicalReasoning(t?.tool_name, assistant?.toolRuntimeContext) && this._toolSucceeded(t))) hasSeenTerminalCommit = true;
|
|
319
|
+
if (terminalOnly && (isOutreach
|
|
320
|
+
? this._outreachCommitted(allToolsExecuted, assistant?.toolRuntimeContext?.outreachReminderType)
|
|
321
|
+
: this._deliveryCommitted(toolsExecuted))) { shouldBreakForDelivery = true; break; }
|
|
322
|
+
const unavailableRecovery = terminalOnly
|
|
323
|
+
? this._unavailableToolRecovery(toolsExecuted, toolSchemas)
|
|
324
|
+
: null;
|
|
325
|
+
if (unavailableRecovery) {
|
|
326
|
+
shouldBreakForUnavailableRecovery = true;
|
|
327
|
+
trace?.setSignals?.({ deliveryRecoveryUnavailable: unavailableRecovery });
|
|
328
|
+
logger.warn('[AnthropicProvider] Delivery recovery tool unavailable — stopping terminal retry loop', unavailableRecovery);
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
99
331
|
|
|
332
|
+
prepThinking();
|
|
100
333
|
const { result: { result: followUp, retries: followUpRetries }, durationMs: followUpDurationMs } = await withTiming(() => makeAPICall(currentMessages));
|
|
101
334
|
totalRetries += followUpRetries;
|
|
102
335
|
addUsage(followUp.usage);
|
|
103
336
|
producingIteration = trace?.addIteration({ response: followUp, durationMs: followUpDurationMs, apiCallConfig }) || null;
|
|
337
|
+
auditCall(followUp, currentMessages, followUpDurationMs);
|
|
104
338
|
finalResponse = followUp;
|
|
105
339
|
}
|
|
340
|
+
|
|
341
|
+
// Budget exhausted mid-work: the loop stopped while the model still wanted tools, so the reply may be empty. Make it
|
|
342
|
+
// visible — but not on a supersede or delivery break, which also exit with pending calls and are not exhaustion.
|
|
343
|
+
const pendingTools = (finalResponse.content || []).filter(block => block.type === 'tool_use');
|
|
344
|
+
if (finalResponse.stop_reason === 'tool_use' && pendingTools.length
|
|
345
|
+
&& !shouldBreakForDelivery && !shouldBreakForUnavailableRecovery && !isSuperseded(shouldContinue)) {
|
|
346
|
+
logger.warn('[AnthropicProvider] Tool-iteration budget exhausted with pending tool calls', { maxFunctionRounds: this.maxFunctionRounds, pending: pendingTools.map(b => b.name) });
|
|
347
|
+
trace?.setSignals?.({ toolBudgetExhausted: true });
|
|
348
|
+
}
|
|
106
349
|
}
|
|
107
350
|
|
|
108
351
|
return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
|
|
109
352
|
}
|
|
110
353
|
|
|
354
|
+
async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
|
|
355
|
+
let modelConfig = {};
|
|
356
|
+
let resolvedInstructions = instructions;
|
|
357
|
+
if (promptId || presetId) {
|
|
358
|
+
const composed = await composePrompt({ promptId, presetId, variables });
|
|
359
|
+
modelConfig = composed.modelConfig || {};
|
|
360
|
+
if (!resolvedInstructions) resolvedInstructions = composed.resolvedPrompt;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const { system, messages } = this._toAnthropicMessages(resolvedInstructions, input);
|
|
364
|
+
|
|
365
|
+
const apiConfig = {
|
|
366
|
+
model: model || (modelConfig.model && modelConfig.model.replace(/^anthropic\//, '')) || this.defaults.structuredModel,
|
|
367
|
+
max_tokens: maxOutputTokens || modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
|
|
368
|
+
};
|
|
369
|
+
if (system) apiConfig.system = system;
|
|
370
|
+
|
|
371
|
+
// Always-thinking models (Opus/Sonnet 5.5) reject a forced tool_choice; presets opt into output_config.format instead.
|
|
372
|
+
const nativeFormat = modelConfig.structured_mode === 'output_format';
|
|
373
|
+
if (nativeFormat) {
|
|
374
|
+
const effort = modelConfig.reasoning?.effort;
|
|
375
|
+
if (effort) apiConfig.output_config = { effort: effort === 'minimal' ? 'low' : effort };
|
|
376
|
+
if (modelConfig.thinking) apiConfig.thinking = modelConfig.thinking;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const spec = text || modelConfig.text;
|
|
380
|
+
let tool = null;
|
|
381
|
+
if (spec) {
|
|
382
|
+
const format = spec.format ? spec.format : spec;
|
|
383
|
+
if (!format.schema) throw new Error('runStructured: format spec has no schema');
|
|
384
|
+
if (nativeFormat) {
|
|
385
|
+
apiConfig.output_config = { ...apiConfig.output_config, format: { type: 'json_schema', schema: format.schema } };
|
|
386
|
+
} else {
|
|
387
|
+
tool = { name: format.name || 'structuredOutput', input_schema: format.schema };
|
|
388
|
+
if (format.strict !== undefined) tool.strict = format.strict;
|
|
389
|
+
apiConfig.tools = [tool];
|
|
390
|
+
apiConfig.tool_choice = { type: 'tool', name: tool.name };
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const { result: { result }, durationMs } = await withTiming(() =>
|
|
395
|
+
retryWithBackoff(
|
|
396
|
+
() => this.client.messages.create({ messages, ...apiConfig }, { timeout: structuredTimeoutMs(apiConfig.max_tokens, this.requestTimeoutMs) }),
|
|
397
|
+
{ providerName: this.constructor.name },
|
|
398
|
+
)
|
|
399
|
+
);
|
|
400
|
+
// The Messages API takes no free-form metadata, so the caller's correlation keys can only live
|
|
401
|
+
// in the call audit. Dropping them silently is what leaves a generated call unattributable.
|
|
402
|
+
const callerMetadata = Object.fromEntries(Object.entries(metadata || {}).filter(([, value]) => value != null));
|
|
403
|
+
void appendCall({
|
|
404
|
+
metadata: { source: 'structured', iterationIndex: 0, resolvedPromptId: promptId, resolvedPresetId: presetId, ...callerMetadata },
|
|
405
|
+
request: { messages, config: apiConfig },
|
|
406
|
+
response: result,
|
|
407
|
+
durationMs,
|
|
408
|
+
});
|
|
409
|
+
return tool ? this._normalizeStructured(result, tool) : this._normalizeResponse(result);
|
|
410
|
+
}
|
|
411
|
+
|
|
111
412
|
_toAnthropicMessages(instructions, input) {
|
|
112
|
-
|
|
113
|
-
|
|
413
|
+
// Caching is a prefix match, so one block would let any per-turn byte invalidate the prompt and
|
|
414
|
+
// the tool schemas ahead of it. Split them: stable content is cached, runtime content is not.
|
|
415
|
+
const stableParts = [];
|
|
416
|
+
if (instructions) stableParts.push(instructions);
|
|
417
|
+
const runtimeParts = [];
|
|
418
|
+
|
|
419
|
+
const outputsByCallId = new Map();
|
|
420
|
+
for (const item of input || []) {
|
|
421
|
+
if (item.type === 'function_call_output') outputsByCallId.set(item.call_id, item.output);
|
|
422
|
+
}
|
|
114
423
|
|
|
115
424
|
const messages = [];
|
|
425
|
+
// Tracks the conversation only: a tail item is placement, not a turn, so it must not decide
|
|
426
|
+
// whether the continuation signal is needed.
|
|
427
|
+
let lastTurnRole = null;
|
|
428
|
+
let historyEnd = -1;
|
|
429
|
+
let sawCurrentTurn = false;
|
|
430
|
+
let pendingUses = [];
|
|
431
|
+
let pendingResults = [];
|
|
432
|
+
const flushTools = () => {
|
|
433
|
+
if (!pendingUses.length) return;
|
|
434
|
+
messages.push({ role: 'assistant', content: pendingUses });
|
|
435
|
+
messages.push({ role: 'user', content: pendingResults });
|
|
436
|
+
lastTurnRole = 'user';
|
|
437
|
+
if (!sawCurrentTurn) historyEnd = messages.length - 1;
|
|
438
|
+
pendingUses = [];
|
|
439
|
+
pendingResults = [];
|
|
440
|
+
};
|
|
441
|
+
|
|
116
442
|
for (const item of input || []) {
|
|
117
443
|
const type = item.type || 'message';
|
|
118
|
-
if (type
|
|
119
|
-
|
|
444
|
+
if (type === 'function_call') {
|
|
445
|
+
if (!outputsByCallId.has(item.call_id)) continue;
|
|
446
|
+
pendingUses.push({ type: 'tool_use', id: item.call_id, name: item.name, input: this._toToolInput(item.arguments) });
|
|
447
|
+
pendingResults.push({ type: 'tool_result', tool_use_id: item.call_id, content: this._toToolContent(outputsByCallId.get(item.call_id)) });
|
|
120
448
|
continue;
|
|
121
449
|
}
|
|
450
|
+
if (type === 'function_call_output') continue;
|
|
451
|
+
flushTools();
|
|
122
452
|
const content = item.content;
|
|
123
|
-
|
|
124
|
-
|
|
453
|
+
// The role picks the side: 'system' is stable (composerService ships skill prompts this way),
|
|
454
|
+
// 'developer' is per-turn.
|
|
455
|
+
if (item.role === 'system') {
|
|
456
|
+
if (content) stableParts.push(content);
|
|
125
457
|
continue;
|
|
126
458
|
}
|
|
127
|
-
|
|
459
|
+
if (item.role === 'developer') {
|
|
460
|
+
// Behind the history, so a value that changes every request cannot invalidate it.
|
|
461
|
+
if (content && item[TAIL_PLACEMENT]) messages.push({ role: 'user', content });
|
|
462
|
+
else if (content) runtimeParts.push(content);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
const role = item.role === 'assistant' ? 'assistant' : 'user';
|
|
466
|
+
messages.push({ role, content });
|
|
467
|
+
lastTurnRole = role;
|
|
468
|
+
if (item[CURRENT_TURN]) sawCurrentTurn = true;
|
|
469
|
+
else if (!sawCurrentTurn) historyEnd = messages.length - 1;
|
|
128
470
|
}
|
|
471
|
+
flushTools();
|
|
472
|
+
|
|
473
|
+
if (!messages.length || lastTurnRole === 'assistant') {
|
|
474
|
+
messages.push({ role: 'user', content: CONVERSATION_CONTINUATION });
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (sawCurrentTurn) markHistoryBreakpoint(messages, historyEnd);
|
|
129
478
|
|
|
130
|
-
const system =
|
|
131
|
-
|
|
132
|
-
|
|
479
|
+
const system = [];
|
|
480
|
+
if (stableParts.length) {
|
|
481
|
+
system.push({
|
|
482
|
+
type: 'text',
|
|
483
|
+
text: stableParts.join('\n\n'),
|
|
484
|
+
cache_control: { type: 'ephemeral', ttl: this.cacheTtl },
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
// Deliberately no cache_control: caching a prefix that changes every turn only pays write costs.
|
|
488
|
+
if (runtimeParts.length) {
|
|
489
|
+
system.push({ type: 'text', text: runtimeParts.join('\n\n') });
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
return { system: system.length ? system : null, messages };
|
|
493
|
+
}
|
|
133
494
|
|
|
134
|
-
|
|
495
|
+
_toToolInput(args) {
|
|
496
|
+
if (isPlainObject(args)) return args;
|
|
497
|
+
const parsed = safeParse(args, null);
|
|
498
|
+
if (isPlainObject(parsed)) return parsed;
|
|
499
|
+
logger.warn('[AnthropicProvider] Unusable tool arguments in history, sending empty input');
|
|
500
|
+
return {};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
_toToolContent(output) {
|
|
504
|
+
return typeof output === 'string' ? output : JSON.stringify(output ?? '');
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// Split placement: the inline copy carries recency on single-round turns, the hoisted developer
|
|
508
|
+
// turn persists once tool results are appended after it on multi-round turns.
|
|
509
|
+
_buildInput({ additionalInstructions, ...rest }) {
|
|
510
|
+
const ordered = this._orderRuntimeMessages(super._buildInput({ additionalInstructions, ...rest }));
|
|
511
|
+
if (!additionalInstructions) return ordered;
|
|
512
|
+
const { content } = this._operatorInstructionTurn(additionalInstructions);
|
|
513
|
+
return [...ordered, { role: 'user', content: `${OPERATOR_TURN_PREFIX} ${content}`, type: 'message' }];
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
_orderRuntimeMessages(input) {
|
|
517
|
+
const pinned = { role: 'developer', content: `${RISK_HEADLINE_MARKER}\n${RISK_HEADLINE_DISCLAIMER}` };
|
|
518
|
+
return [...input.filter(i => !i[TAIL_PLACEMENT]), pinned, ...input.filter(i => i[TAIL_PLACEMENT])];
|
|
135
519
|
}
|
|
136
520
|
|
|
137
521
|
_mapModelConfig(modelConfig) {
|
|
@@ -143,6 +527,8 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
143
527
|
delete mapped.text;
|
|
144
528
|
delete mapped.reasoning;
|
|
145
529
|
delete mapped.max_output_tokens;
|
|
530
|
+
delete mapped.betas;
|
|
531
|
+
delete mapped.thinking_mode;
|
|
146
532
|
if (mapped.max_tokens == null) mapped.max_tokens = this.defaults.maxOutputTokens;
|
|
147
533
|
return mapped;
|
|
148
534
|
}
|
|
@@ -150,16 +536,42 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
150
536
|
_mapTools(toolSchemas) {
|
|
151
537
|
return toolSchemas.map(schema => {
|
|
152
538
|
const fn = schema.function || schema;
|
|
153
|
-
|
|
539
|
+
// The clinical tool set compiles as one grammar per request; strict on all of them
|
|
540
|
+
// exceeds Anthropic's complexity limit. runStructured keeps strict — single schema.
|
|
541
|
+
return {
|
|
154
542
|
name: fn.name,
|
|
155
543
|
description: fn.description,
|
|
156
544
|
input_schema: fn.parameters || { type: 'object', properties: {} },
|
|
157
545
|
};
|
|
158
|
-
if (fn.strict !== undefined) tool.strict = fn.strict;
|
|
159
|
-
return tool;
|
|
160
546
|
});
|
|
161
547
|
}
|
|
162
548
|
|
|
549
|
+
_endsClinicalReasoning(toolName, runtime) {
|
|
550
|
+
if (!TERMINAL_COMMIT_TOOLS.has(toolName)) return false;
|
|
551
|
+
if (toolName !== ROUTING_TOOL) return true;
|
|
552
|
+
const specialised = [...(runtime?.activatedSkills || [])].filter(s => s !== ROUTING_SKILL);
|
|
553
|
+
return specialised.length === 0;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
_thinkingForIter(iterationNum, mode, hasSeenTerminalCommit) {
|
|
557
|
+
if (mode === 'always') return true;
|
|
558
|
+
if (mode === 'first_iter') return iterationNum === 1;
|
|
559
|
+
return iterationNum === 1 || !hasSeenTerminalCommit;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// Anthropic rejects a forced tool_choice ('tool'/'any') while extended thinking is enabled, so under thinking a forced
|
|
563
|
+
// choice is coerced to 'auto'. This deliberately prefers thinking over the tool guarantee: the model is already strongly
|
|
564
|
+
// prompted to call the tool. Adaptive thinking ({type:'adaptive'}) is intentionally NOT coerced — it is accepted with a
|
|
565
|
+
// forced choice on the first-party API (only Bedrock requires thinking off), so the guard fires on 'enabled' only.
|
|
566
|
+
_resolveToolChoice(toolChoice, isThinkingEnabled) {
|
|
567
|
+
const mapped = this._mapToolChoice(toolChoice);
|
|
568
|
+
if (isThinkingEnabled && (mapped.type === 'tool' || mapped.type === 'any')) {
|
|
569
|
+
logger.debug('[AnthropicProvider] Forced tool_choice coerced to auto under extended thinking', { requested: mapped.type, tool: mapped.name || null });
|
|
570
|
+
return { type: 'auto' };
|
|
571
|
+
}
|
|
572
|
+
return mapped;
|
|
573
|
+
}
|
|
574
|
+
|
|
163
575
|
_mapToolChoice(toolChoice) {
|
|
164
576
|
if (!toolChoice || toolChoice === 'auto') return { type: 'auto' };
|
|
165
577
|
if (toolChoice === 'none') return { type: 'none' };
|
|
@@ -175,6 +587,16 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
175
587
|
.map(block => block.text || '')
|
|
176
588
|
.join('')
|
|
177
589
|
.trim();
|
|
590
|
+
return this._envelope(response, outputText);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
_normalizeStructured(response, tool) {
|
|
594
|
+
const toolUse = (response.content || []).find(block => block.type === 'tool_use' && block.name === tool.name);
|
|
595
|
+
const outputText = toolUse ? JSON.stringify(toolUse.input ?? {}) : '';
|
|
596
|
+
return this._envelope(response, outputText);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
_envelope(response, outputText) {
|
|
178
600
|
const output = outputText
|
|
179
601
|
? [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: outputText }] }]
|
|
180
602
|
: [];
|
|
@@ -183,14 +605,17 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
183
605
|
input_tokens: response.usage.input_tokens || 0,
|
|
184
606
|
output_tokens: response.usage.output_tokens || 0,
|
|
185
607
|
total_tokens: (response.usage.input_tokens || 0) + (response.usage.output_tokens || 0),
|
|
608
|
+
cache_creation_input_tokens: response.usage.cache_creation_input_tokens || 0,
|
|
609
|
+
cache_read_input_tokens: response.usage.cache_read_input_tokens || 0,
|
|
186
610
|
}
|
|
187
611
|
: undefined;
|
|
188
612
|
|
|
613
|
+
const statusByStopReason = { refusal: 'refused', max_tokens: 'incomplete' };
|
|
189
614
|
return {
|
|
190
615
|
id: response.id,
|
|
191
616
|
object: 'response',
|
|
192
617
|
model: response.model,
|
|
193
|
-
status: response.stop_reason
|
|
618
|
+
status: statusByStopReason[response.stop_reason] || 'completed',
|
|
194
619
|
stop_reason: response.stop_reason,
|
|
195
620
|
output,
|
|
196
621
|
output_text: outputText,
|
|
@@ -202,4 +627,7 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
202
627
|
|
|
203
628
|
module.exports = {
|
|
204
629
|
AnthropicProvider,
|
|
630
|
+
REQUEST_MAX_RETRIES,
|
|
631
|
+
resolveRequestTimeoutMs,
|
|
632
|
+
structuredTimeoutMs,
|
|
205
633
|
};
|