@peopl-health/nexus 5.51.0-dev.7607 → 5.51.0-dev.7627
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 +21 -0
- package/lib/clinical/AssistantProcessor.js +156 -12
- package/lib/clinical/context/ToolRuntimeContext.js +39 -1
- package/lib/clinical/context/turnContext.js +10 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +29 -0
- package/lib/clinical/providers/BaseLLMProvider.js +45 -5
- package/lib/clinical/services/clinicalAirtableService.js +8 -5
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/divergenceService.js +9 -2
- package/lib/clinical/services/supportActionService.js +129 -0
- package/lib/clinical/services/supportCandidateService.js +470 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/triageRecommendationService.js +456 -251
- package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
- package/lib/clinical/tools/registerClinicalTools.js +2 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +121 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/core/BatchingManager.js +20 -9
- package/lib/core/NexusMessaging.js +25 -6
- package/lib/core/ProcessingPipeline.js +32 -3
- package/lib/index.d.ts +325 -6
- package/lib/index.js +22 -0
- package/lib/services/airtableService.js +8 -1
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +30 -3
- package/lib/services/escalationReviewService.js +7 -7
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ const { describeThrown } = require('../utils/errorUtils');
|
|
|
3
3
|
const { logger } = require('../utils/logger');
|
|
4
4
|
|
|
5
5
|
const VALID_HOOKS = ['preProcess', 'postProcess'];
|
|
6
|
+
const MAX_ADDITIONAL_TOOL_IDS = 8;
|
|
6
7
|
|
|
7
8
|
class ProcessingPipeline {
|
|
8
9
|
constructor(hooks = {}) {
|
|
@@ -33,7 +34,7 @@ class ProcessingPipeline {
|
|
|
33
34
|
return this;
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
async run(context, executeFn, shouldContinue = () => true) {
|
|
37
|
+
async run(context, executeFn, shouldContinue = () => true, discardResult = null) {
|
|
37
38
|
const ctx = { metadata: {}, ...context };
|
|
38
39
|
const preProcessCount = this._hooks.preProcess.length;
|
|
39
40
|
const postProcessCount = this._hooks.postProcess.length;
|
|
@@ -49,6 +50,7 @@ class ProcessingPipeline {
|
|
|
49
50
|
skip: preProcessResult.skip,
|
|
50
51
|
hasAdditionalInstructions: !!preProcessResult.additionalInstructions,
|
|
51
52
|
additionalMessagesCount: preProcessResult.additionalMessages.length,
|
|
53
|
+
additionalToolIdsCount: preProcessResult.additionalToolIds?.length || 0,
|
|
52
54
|
hasToolChoice: preProcessResult.toolChoice != null,
|
|
53
55
|
});
|
|
54
56
|
|
|
@@ -62,7 +64,21 @@ class ProcessingPipeline {
|
|
|
62
64
|
|
|
63
65
|
const result = await executeFn(preProcessResult, shouldContinue, ctx.runId);
|
|
64
66
|
|
|
65
|
-
if (!shouldContinue())
|
|
67
|
+
if (!shouldContinue()) {
|
|
68
|
+
if (result && typeof discardResult === 'function') {
|
|
69
|
+
try {
|
|
70
|
+
await discardResult(result);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
logger.warn('[ProcessingPipeline] result discard failed', {
|
|
73
|
+
chatId: ctx.chatId,
|
|
74
|
+
type: ctx.type,
|
|
75
|
+
reason: 'result_discard_failed',
|
|
76
|
+
errorType: error?.constructor?.name || typeof error,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
66
82
|
|
|
67
83
|
this._runPostProcessHooks(ctx, result, null);
|
|
68
84
|
return result;
|
|
@@ -116,6 +132,15 @@ class ProcessingPipeline {
|
|
|
116
132
|
if (result.toolChoice) {
|
|
117
133
|
merged.toolChoice = result.toolChoice;
|
|
118
134
|
}
|
|
135
|
+
if (Array.isArray(result.additionalToolIds)) {
|
|
136
|
+
const existing = new Set(merged.additionalToolIds || []);
|
|
137
|
+
for (const toolId of result.additionalToolIds) {
|
|
138
|
+
if (existing.size >= MAX_ADDITIONAL_TOOL_IDS) break;
|
|
139
|
+
if (typeof toolId !== 'string' || !toolId.trim()) continue;
|
|
140
|
+
existing.add(toolId.trim());
|
|
141
|
+
}
|
|
142
|
+
if (existing.size > 0) merged.additionalToolIds = [...existing];
|
|
143
|
+
}
|
|
119
144
|
if (isPlainObject(result.signals)) {
|
|
120
145
|
Object.assign(merged.signals, result.signals);
|
|
121
146
|
}
|
|
@@ -133,7 +158,11 @@ class ProcessingPipeline {
|
|
|
133
158
|
if (hooks.length === 0) return;
|
|
134
159
|
|
|
135
160
|
setImmediate(() => {
|
|
136
|
-
const postContext = {
|
|
161
|
+
const postContext = {
|
|
162
|
+
chatId: context.chatId,
|
|
163
|
+
type: context.type,
|
|
164
|
+
...(Object.keys(context.metadata || {}).length > 0 && { metadata: context.metadata }),
|
|
165
|
+
};
|
|
137
166
|
if (result) postContext.result = result;
|
|
138
167
|
if (error) postContext.error = error;
|
|
139
168
|
|
package/lib/index.d.ts
CHANGED
|
@@ -2,9 +2,14 @@ declare module '@peopl-health/nexus' {
|
|
|
2
2
|
// Core Types
|
|
3
3
|
export interface MessageData {
|
|
4
4
|
id?: string;
|
|
5
|
+
messageId?: string;
|
|
6
|
+
message_id?: string;
|
|
5
7
|
from: string;
|
|
6
8
|
code?: string;
|
|
9
|
+
body?: string;
|
|
7
10
|
message?: string;
|
|
11
|
+
timestamp?: string | Date;
|
|
12
|
+
createdAt?: string | Date;
|
|
8
13
|
fileUrl?: string;
|
|
9
14
|
fileType?: 'text' | 'image' | 'document' | 'audio' | 'video';
|
|
10
15
|
contentSid?: string;
|
|
@@ -230,7 +235,7 @@ declare module '@peopl-health/nexus' {
|
|
|
230
235
|
}
|
|
231
236
|
|
|
232
237
|
export class NexusMessaging {
|
|
233
|
-
constructor(config?:
|
|
238
|
+
constructor(config?: NexusMessagingConfig);
|
|
234
239
|
initializeProvider(providerType: 'twilio' | 'baileys', providerConfig: TwilioConfig | BaileysConfig): Promise<void>;
|
|
235
240
|
setMessageStorage(storage: any): void;
|
|
236
241
|
setHandlers(handlers: MessageHandlers): void;
|
|
@@ -301,7 +306,7 @@ declare module '@peopl-health/nexus' {
|
|
|
301
306
|
|
|
302
307
|
// Main Nexus Class
|
|
303
308
|
export interface NexusConfig {
|
|
304
|
-
messaging?:
|
|
309
|
+
messaging?: NexusMessagingConfig;
|
|
305
310
|
}
|
|
306
311
|
|
|
307
312
|
export interface NerOptions {
|
|
@@ -660,6 +665,199 @@ declare module '@peopl-health/nexus' {
|
|
|
660
665
|
export function getPatientMemory(): any;
|
|
661
666
|
export function getConversationSummary(): any;
|
|
662
667
|
|
|
668
|
+
export type SupportService = 'nutrition' | 'psychology';
|
|
669
|
+
export type SupportDisposition = 'group' | 'individual' | 'escalated' | 'reviewRequired' | 'none';
|
|
670
|
+
export type SupportPriority = 'routine' | 'soon' | 'urgent';
|
|
671
|
+
export type SupportInvitationClass = 'first' | 'followup';
|
|
672
|
+
export type SupportDeliveryStatus = 'sent' | 'delivered' | 'read' | 'failed' | 'unknown';
|
|
673
|
+
export type SupportEngagementState = 'notInvited' | 'invited' | 'registered' | 'attended' | 'declined';
|
|
674
|
+
|
|
675
|
+
export interface SupportEvidenceInput {
|
|
676
|
+
source: 'triage' | 'chat' | 'fhir' | 'airtable';
|
|
677
|
+
sourceId: string;
|
|
678
|
+
code: string;
|
|
679
|
+
summary?: string | null;
|
|
680
|
+
confidence?: number | null;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export interface SupportEvidence extends SupportEvidenceInput {
|
|
684
|
+
key?: string;
|
|
685
|
+
summary: string | null;
|
|
686
|
+
confidence: number | null;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
export interface SupportSafety {
|
|
690
|
+
suicidalIdeation?: boolean;
|
|
691
|
+
immediateRisk?: boolean;
|
|
692
|
+
urgentMedicalRisk?: boolean;
|
|
693
|
+
needsHumanConfirmation?: boolean;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
export interface SupportRoutingDecisionBaseInput {
|
|
697
|
+
disposition: SupportDisposition;
|
|
698
|
+
groupEligible: boolean;
|
|
699
|
+
priority?: SupportPriority;
|
|
700
|
+
confidence: number;
|
|
701
|
+
reasonCodes?: string[];
|
|
702
|
+
evidence: SupportEvidenceInput[];
|
|
703
|
+
safety: SupportSafety;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export type SupportRoutingDecisionInput = SupportRoutingDecisionBaseInput & ({
|
|
707
|
+
service: 'nutrition';
|
|
708
|
+
nutritionRisk: 'green' | 'yellow' | 'red' | 'unknown';
|
|
709
|
+
urgentIntakeEligible: boolean;
|
|
710
|
+
} | {
|
|
711
|
+
service: 'psychology';
|
|
712
|
+
psychologyRisk: 'green' | 'orange' | 'red' | 'unknown';
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
export interface SupportRoutingRecommendationInput {
|
|
716
|
+
schemaVersion?: string;
|
|
717
|
+
decisionVersion?: string;
|
|
718
|
+
patientId: string;
|
|
719
|
+
origin: 'triage' | 'chat' | 'fhir';
|
|
720
|
+
sourceId: string;
|
|
721
|
+
createdAt: string;
|
|
722
|
+
decisions: SupportRoutingDecisionInput[];
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
export interface SupportCandidateRecord {
|
|
726
|
+
candidateId: string;
|
|
727
|
+
patientId: string;
|
|
728
|
+
service: SupportService;
|
|
729
|
+
disposition: SupportDisposition;
|
|
730
|
+
groupEligible: boolean;
|
|
731
|
+
urgentIntakeEligible: boolean;
|
|
732
|
+
priority: SupportPriority;
|
|
733
|
+
confidence?: number;
|
|
734
|
+
nutritionRisk?: 'green' | 'yellow' | 'red' | 'unknown' | null;
|
|
735
|
+
psychologyRisk?: 'green' | 'orange' | 'red' | 'unknown' | null;
|
|
736
|
+
reasonCodes?: string[];
|
|
737
|
+
evidence?: SupportEvidence[];
|
|
738
|
+
sourceEventIds?: string[];
|
|
739
|
+
activeInvitationKey?: string | null;
|
|
740
|
+
cooldownInvitationKey?: string | null;
|
|
741
|
+
revision?: number;
|
|
742
|
+
[key: string]: unknown;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
export interface SupportActionRecord {
|
|
746
|
+
candidateId: string;
|
|
747
|
+
service: SupportService;
|
|
748
|
+
type: 'group_registration' | 'urgent_nutrition_intake';
|
|
749
|
+
invitationClass: SupportInvitationClass | null;
|
|
750
|
+
idempotencyKey?: string | null;
|
|
751
|
+
targetKey: string;
|
|
752
|
+
priority: SupportPriority;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export interface SupportActionResult {
|
|
756
|
+
schemaVersion: '1';
|
|
757
|
+
patientId: string;
|
|
758
|
+
sourceId: string;
|
|
759
|
+
actions: SupportActionRecord[];
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
export interface SupportDeliveryContext {
|
|
763
|
+
invitationClassByService?: Partial<Record<SupportService, SupportInvitationClass>>;
|
|
764
|
+
targetKeyByService?: Partial<Record<SupportService, string>>;
|
|
765
|
+
attendanceEvidenceByService?: Partial<Record<SupportService, {
|
|
766
|
+
patientId: string;
|
|
767
|
+
service: SupportService;
|
|
768
|
+
evidenceId: string;
|
|
769
|
+
}>>;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
export interface SupportDashboardMetric {
|
|
773
|
+
records: Array<Record<string, unknown>>;
|
|
774
|
+
indicator: number;
|
|
775
|
+
sample: number;
|
|
776
|
+
total: number;
|
|
777
|
+
struct: string[];
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export interface SupportDashboardSnapshot {
|
|
781
|
+
generatedAt: string;
|
|
782
|
+
metrics: { exceptions: SupportDashboardMetric };
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
export type SupportDashboardCandidateRecord = Pick<SupportCandidateRecord,
|
|
786
|
+
'candidateId' | 'patientId' | 'service' | 'disposition'
|
|
787
|
+
> & Partial<SupportCandidateRecord>;
|
|
788
|
+
|
|
789
|
+
export function registerDashboardProvider(
|
|
790
|
+
source: 'auna.support.v1',
|
|
791
|
+
provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
|
|
792
|
+
): void;
|
|
793
|
+
|
|
794
|
+
export const supportCandidateService: {
|
|
795
|
+
updateSupportOperationalReview(request: {
|
|
796
|
+
patientId: string;
|
|
797
|
+
service: SupportService;
|
|
798
|
+
reasonCode: 'classification_failed' | 'attendance_unavailable' | 'safety_unconfirmed' | 'classification_safety_unconfirmed' | 'invitation_claim_failed';
|
|
799
|
+
sourceId: string;
|
|
800
|
+
resolved?: boolean;
|
|
801
|
+
noClinicalDecision?: boolean;
|
|
802
|
+
now?: Date;
|
|
803
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
804
|
+
readSupportDashboardCandidates(): Promise<SupportDashboardCandidateRecord[]>;
|
|
805
|
+
approveCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
806
|
+
candidatePatch(existing: SupportCandidateRecord | null | undefined, recommendation: SupportRoutingRecommendationInput, decision: SupportRoutingDecisionInput): Partial<SupportCandidateRecord>;
|
|
807
|
+
claimInvitation(request: {
|
|
808
|
+
candidateId: string;
|
|
809
|
+
invitationClass: SupportInvitationClass;
|
|
810
|
+
invitationCycle: string;
|
|
811
|
+
templateVersion: string;
|
|
812
|
+
now?: Date;
|
|
813
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
814
|
+
clearCandidateEscalation(candidateId: string, options: { reviewedRevision: number; approvedForGroup?: boolean; Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
815
|
+
evidenceKey(item: Pick<SupportEvidence, 'source' | 'sourceId' | 'code'>): string;
|
|
816
|
+
initialState(decision: SupportRoutingDecisionInput): SupportDisposition;
|
|
817
|
+
markCandidateAccepted(request: { patientId: string; service: SupportService; sessionId?: string | null }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
818
|
+
markCandidateDeclined(request: { patientId: string; service: SupportService; preference?: 'another_date' | 'not_now' | 'never' }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
819
|
+
nextState(existing: SupportCandidateRecord | null | undefined, decision: SupportRoutingDecisionInput): SupportDisposition;
|
|
820
|
+
normalizeEvidence(items?: SupportEvidenceInput[]): Array<SupportEvidence & { key: string }>;
|
|
821
|
+
recordEngagement(request: {
|
|
822
|
+
patientId: string;
|
|
823
|
+
service: SupportService;
|
|
824
|
+
state: SupportEngagementState;
|
|
825
|
+
evidenceId?: string | null;
|
|
826
|
+
occurredAt?: string | Date | null;
|
|
827
|
+
preference?: 'another_date' | 'not_now' | 'never' | null;
|
|
828
|
+
}, options?: { Model?: unknown; historicalAttendance?: boolean }): Promise<SupportCandidateRecord | null>;
|
|
829
|
+
recordLegacyInvitationResponse(request: {
|
|
830
|
+
patientId: string;
|
|
831
|
+
service: SupportService;
|
|
832
|
+
outcome: 'accepted' | 'declined';
|
|
833
|
+
sessionId?: string | null;
|
|
834
|
+
preference?: 'another_date' | 'not_now' | 'never';
|
|
835
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
836
|
+
recordSupportRoutingRecommendation(recommendation: SupportRoutingRecommendationInput, options?: { Model?: unknown }): Promise<SupportCandidateRecord[]>;
|
|
837
|
+
rescheduleDeclinedCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
838
|
+
settleInvitation(request: {
|
|
839
|
+
candidateId: string;
|
|
840
|
+
idempotencyKey: string;
|
|
841
|
+
status: SupportDeliveryStatus;
|
|
842
|
+
providerMessageId?: string | null;
|
|
843
|
+
error?: string | null;
|
|
844
|
+
now?: Date;
|
|
845
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
846
|
+
};
|
|
847
|
+
|
|
848
|
+
export const supportActionService: {
|
|
849
|
+
prepareSupportAction(request: {
|
|
850
|
+
patientId: string;
|
|
851
|
+
sourceId: string;
|
|
852
|
+
candidates?: SupportCandidateRecord[];
|
|
853
|
+
resolveDeliveryContext?: (context: {
|
|
854
|
+
patientId: string;
|
|
855
|
+
candidates: SupportCandidateRecord[];
|
|
856
|
+
}) => SupportDeliveryContext | Promise<SupportDeliveryContext>;
|
|
857
|
+
now?: Date;
|
|
858
|
+
}, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
|
|
859
|
+
};
|
|
860
|
+
|
|
663
861
|
// BatchingManager — per-chatId concurrency control
|
|
664
862
|
export interface BatchingConfig {
|
|
665
863
|
enabled?: boolean;
|
|
@@ -669,6 +867,118 @@ declare module '@peopl-health/nexus' {
|
|
|
669
867
|
hooks?: Record<string, Function | Function[]>;
|
|
670
868
|
}
|
|
671
869
|
|
|
870
|
+
export type NutritionSafetyFindingCode =
|
|
871
|
+
| 'cannot_eat'
|
|
872
|
+
| 'cannot_keep_fluids'
|
|
873
|
+
| 'bleeding'
|
|
874
|
+
| 'severe_abdominal_pain';
|
|
875
|
+
export type NutritionSafetyFindingValue = 'yes' | 'no' | 'unknown';
|
|
876
|
+
export type NutritionSafetyQuestionCode =
|
|
877
|
+
| 'can_eat'
|
|
878
|
+
| 'can_keep_fluids'
|
|
879
|
+
| 'bleeding'
|
|
880
|
+
| 'severe_abdominal_pain';
|
|
881
|
+
export type NutritionSafetyEvidenceSourceType = 'chat' | 'flow' | 'historical' | 'forecast';
|
|
882
|
+
export type NutritionSafetyDisposition = 'clear' | 'clarify' | 'escalate' | 'review_required';
|
|
883
|
+
|
|
884
|
+
export interface NutritionSafetyEvidenceRefInput {
|
|
885
|
+
finding: NutritionSafetyFindingCode;
|
|
886
|
+
source_type: NutritionSafetyEvidenceSourceType;
|
|
887
|
+
source_id: string;
|
|
888
|
+
observed_at: string;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
export interface NutritionSafetyEvidenceRef {
|
|
892
|
+
finding: NutritionSafetyFindingCode;
|
|
893
|
+
sourceType: NutritionSafetyEvidenceSourceType;
|
|
894
|
+
sourceId: string;
|
|
895
|
+
observedAt: string;
|
|
896
|
+
traceId?: string;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
export interface NutritionSafetyDecisionInput {
|
|
900
|
+
submission_revision: number;
|
|
901
|
+
screen_revision: number;
|
|
902
|
+
findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
|
|
903
|
+
evidence_refs: NutritionSafetyEvidenceRefInput[];
|
|
904
|
+
questions_needed: NutritionSafetyQuestionCode[];
|
|
905
|
+
disposition: NutritionSafetyDisposition;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
export class NutritionSafetyDecision {
|
|
909
|
+
constructor(payload: NutritionSafetyDecisionInput);
|
|
910
|
+
submissionRevision: number;
|
|
911
|
+
screenRevision: number;
|
|
912
|
+
findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
|
|
913
|
+
evidenceRefs: NutritionSafetyEvidenceRef[];
|
|
914
|
+
questionsNeeded: NutritionSafetyQuestionCode[];
|
|
915
|
+
disposition: NutritionSafetyDisposition;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
export interface NutritionSafetyDeliveryDirective {
|
|
919
|
+
operationId: string;
|
|
920
|
+
body: string;
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
export interface NutritionSafetyCommitRequest {
|
|
924
|
+
decision: NutritionSafetyDecision;
|
|
925
|
+
patientCode: string;
|
|
926
|
+
turnId: string;
|
|
927
|
+
traceId: string;
|
|
928
|
+
sourceId: string;
|
|
929
|
+
observedAt: string;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
export interface NutritionSafetyCommitResult {
|
|
933
|
+
outcome: string;
|
|
934
|
+
status?: string;
|
|
935
|
+
screen?: { status: string; [key: string]: any };
|
|
936
|
+
questionsNeeded?: NutritionSafetyQuestionCode[];
|
|
937
|
+
questions_needed?: NutritionSafetyQuestionCode[];
|
|
938
|
+
deliveryDirective?: NutritionSafetyDeliveryDirective;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export interface NutritionSafetyRepository {
|
|
942
|
+
commitDecision(request: NutritionSafetyCommitRequest): Promise<NutritionSafetyCommitResult>;
|
|
943
|
+
claimDelivery?(request: {
|
|
944
|
+
operationId: string;
|
|
945
|
+
patientCode: string;
|
|
946
|
+
turnId: string;
|
|
947
|
+
traceId: string | null;
|
|
948
|
+
sourceId: string | null;
|
|
949
|
+
}): Promise<{ acquired: boolean }>;
|
|
950
|
+
settleDelivery?(request: {
|
|
951
|
+
operationId: string;
|
|
952
|
+
outcome: 'sent' | 'known_not_sent' | 'unknown';
|
|
953
|
+
providerMessageId: string | null;
|
|
954
|
+
patientCode: string;
|
|
955
|
+
turnId: string | null;
|
|
956
|
+
traceId: string | null;
|
|
957
|
+
}): Promise<boolean | void>;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
export interface ToolRuntimeRepositories {
|
|
961
|
+
nutritionSafety?: NutritionSafetyRepository;
|
|
962
|
+
[key: string]: any;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
export const FINDING_CODES: readonly NutritionSafetyFindingCode[];
|
|
966
|
+
export const FINDING_VALUES: readonly NutritionSafetyFindingValue[];
|
|
967
|
+
export const FINDING_TO_QUESTION: Readonly<Record<NutritionSafetyFindingCode, NutritionSafetyQuestionCode>>;
|
|
968
|
+
export const QUESTION_CODES: readonly NutritionSafetyQuestionCode[];
|
|
969
|
+
export const EVIDENCE_SOURCE_TYPES: readonly NutritionSafetyEvidenceSourceType[];
|
|
970
|
+
export const DISPOSITIONS: readonly NutritionSafetyDisposition[];
|
|
971
|
+
|
|
972
|
+
export interface NexusMessagingConfig {
|
|
973
|
+
messageBatching?: BatchingConfig;
|
|
974
|
+
assistant?: {
|
|
975
|
+
mode?: 'local' | 'queue';
|
|
976
|
+
toolRuntimeRepos?: ToolRuntimeRepositories;
|
|
977
|
+
[key: string]: any;
|
|
978
|
+
};
|
|
979
|
+
[key: string]: any;
|
|
980
|
+
}
|
|
981
|
+
|
|
672
982
|
export interface DrainResult {
|
|
673
983
|
drained: boolean;
|
|
674
984
|
waitedMs: number;
|
|
@@ -705,12 +1015,14 @@ declare module '@peopl-health/nexus' {
|
|
|
705
1015
|
handleBatchedProcessing(
|
|
706
1016
|
chatId: string,
|
|
707
1017
|
processingFn: (runId: string) => Promise<any>,
|
|
708
|
-
sendResponseFn: (result: any) => Promise<void
|
|
1018
|
+
sendResponseFn: (result: any) => Promise<void>,
|
|
1019
|
+
discardResponseFn?: (result: any) => Promise<void>
|
|
709
1020
|
): Promise<TurnAdmission>;
|
|
710
1021
|
enqueueProcessing(
|
|
711
1022
|
chatId: string,
|
|
712
1023
|
processingFn: (runId: string) => Promise<any>,
|
|
713
|
-
sendResponseFn: (result: any) => Promise<void
|
|
1024
|
+
sendResponseFn: (result: any) => Promise<void>,
|
|
1025
|
+
discardResponseFn?: (result: any) => Promise<void>
|
|
714
1026
|
): Promise<TurnAdmission>;
|
|
715
1027
|
}
|
|
716
1028
|
|
|
@@ -719,7 +1031,9 @@ declare module '@peopl-health/nexus' {
|
|
|
719
1031
|
skip?: boolean;
|
|
720
1032
|
additionalInstructions?: string;
|
|
721
1033
|
additionalMessages?: Array<Record<string, any>>;
|
|
722
|
-
toolChoice?: Record<string, any> | null;
|
|
1034
|
+
toolChoice?: string | Record<string, any> | null;
|
|
1035
|
+
/** Registered tool ids to add for this turn only. Invalid ids are ignored and the list is capped at eight. */
|
|
1036
|
+
additionalToolIds?: string[];
|
|
723
1037
|
/** Recorded on the turn trace under `signals.consumer`; cannot collide with nexus-owned keys. */
|
|
724
1038
|
signals?: Record<string, any>;
|
|
725
1039
|
metadata?: Record<string, any>;
|
|
@@ -738,7 +1052,8 @@ declare module '@peopl-health/nexus' {
|
|
|
738
1052
|
run(
|
|
739
1053
|
context: ProcessingContext,
|
|
740
1054
|
executeFn: (preProcessResult: PreProcessResult, shouldContinue: () => boolean) => Promise<any>,
|
|
741
|
-
shouldContinue?: () => boolean
|
|
1055
|
+
shouldContinue?: () => boolean,
|
|
1056
|
+
discardResult?: (result: any) => Promise<void>
|
|
742
1057
|
): Promise<any>;
|
|
743
1058
|
}
|
|
744
1059
|
|
|
@@ -756,6 +1071,7 @@ declare module '@peopl-health/nexus' {
|
|
|
756
1071
|
sendMessage?: (messageData: MessageData) => Promise<any>;
|
|
757
1072
|
storeRunMetrics?: (code: string, thread: any, result: any, timings?: Record<string, any>) => Promise<void>;
|
|
758
1073
|
llmMonitor?: { enqueueTurn(turnId: string): Promise<string | null> } | null;
|
|
1074
|
+
toolRuntimeRepos?: ToolRuntimeRepositories;
|
|
759
1075
|
}
|
|
760
1076
|
|
|
761
1077
|
export interface ProcessInput {
|
|
@@ -776,6 +1092,8 @@ declare module '@peopl-health/nexus' {
|
|
|
776
1092
|
predictionTimeMs?: number;
|
|
777
1093
|
retries?: number;
|
|
778
1094
|
completed?: boolean;
|
|
1095
|
+
/** Internal delivery ownership receipt; never contains the directive body. */
|
|
1096
|
+
deliveryDirective?: { operationId: string; claimed: boolean; settled: boolean };
|
|
779
1097
|
}
|
|
780
1098
|
|
|
781
1099
|
export class AssistantProcessor {
|
|
@@ -785,6 +1103,7 @@ declare module '@peopl-health/nexus' {
|
|
|
785
1103
|
executeLLM(thread: any, assistant: any, runOptions?: AssistantRunOptions, message?: any): Promise<LLMResult>;
|
|
786
1104
|
process(input: ProcessInput): Promise<LLMResult | null>;
|
|
787
1105
|
sendResponse(code: string, result: any): Promise<string | null>;
|
|
1106
|
+
discardResponse(code: string, result: any): Promise<boolean>;
|
|
788
1107
|
}
|
|
789
1108
|
|
|
790
1109
|
}
|
package/lib/index.js
CHANGED
|
@@ -40,6 +40,18 @@ const { syncClinicalContext } = require('./clinical/services/contextSyncRunner')
|
|
|
40
40
|
const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
|
|
41
41
|
const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
|
|
42
42
|
const { MapCache } = require('./utils/MapCache');
|
|
43
|
+
const supportCandidateService = require('./clinical/services/supportCandidateService');
|
|
44
|
+
const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
|
|
45
|
+
const supportActionService = require('./clinical/services/supportActionService');
|
|
46
|
+
const {
|
|
47
|
+
NutritionSafetyDecision,
|
|
48
|
+
FINDING_CODES,
|
|
49
|
+
FINDING_VALUES,
|
|
50
|
+
FINDING_TO_QUESTION,
|
|
51
|
+
QUESTION_CODES,
|
|
52
|
+
EVIDENCE_SOURCE_TYPES,
|
|
53
|
+
DISPOSITIONS,
|
|
54
|
+
} = require('./shared/dtos/NutritionSafetyDecision');
|
|
43
55
|
|
|
44
56
|
class Nexus {
|
|
45
57
|
constructor(config = {}) {
|
|
@@ -298,4 +310,14 @@ module.exports = {
|
|
|
298
310
|
DefaultMemoryManager,
|
|
299
311
|
EnhancedMemoryManager,
|
|
300
312
|
MapCache,
|
|
313
|
+
supportCandidateService,
|
|
314
|
+
registerDashboardProvider,
|
|
315
|
+
supportActionService,
|
|
316
|
+
NutritionSafetyDecision,
|
|
317
|
+
FINDING_CODES,
|
|
318
|
+
FINDING_VALUES,
|
|
319
|
+
FINDING_TO_QUESTION,
|
|
320
|
+
QUESTION_CODES,
|
|
321
|
+
EVIDENCE_SOURCE_TYPES,
|
|
322
|
+
DISPOSITIONS,
|
|
301
323
|
};
|
|
@@ -195,10 +195,16 @@ async function patchUpsert(baseID, tableName, fields, mergeOn, apiKey) {
|
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
async function upsertRecord(baseID, tableName, fields,
|
|
198
|
+
async function upsertRecord(baseID, tableName, fields, options = {}, context = null) {
|
|
199
|
+
const { mergeOn, retryNetworkErrors = true } = options;
|
|
200
|
+
|
|
199
201
|
if (!Array.isArray(mergeOn) || mergeOn.length === 0) {
|
|
200
202
|
throw new Error('[upsertRecord] mergeOn must name the fields Airtable matches on');
|
|
201
203
|
}
|
|
204
|
+
if (Object.prototype.hasOwnProperty.call(options, 'retryNetworkErrors')
|
|
205
|
+
&& typeof options.retryNetworkErrors !== 'boolean') {
|
|
206
|
+
throw new Error('[upsertRecord] retryNetworkErrors must be a boolean');
|
|
207
|
+
}
|
|
202
208
|
|
|
203
209
|
if (isShadowRun() || isBenchMode(context)) {
|
|
204
210
|
logger.info(`[upsertRecord:${isShadowRun() ? 'shadow' : 'bench'}] Suppressed`, { tableName, code: context });
|
|
@@ -216,6 +222,7 @@ async function upsertRecord(baseID, tableName, fields, { mergeOn } = {}, context
|
|
|
216
222
|
const data = await withAirtableRetry(
|
|
217
223
|
() => patchUpsert(baseID, tableName, fields, mergeOn, apiKey),
|
|
218
224
|
'upsertRecord',
|
|
225
|
+
{ retryNetworkErrors },
|
|
219
226
|
);
|
|
220
227
|
const record = data.records[0];
|
|
221
228
|
const created = (data.createdRecords || []).includes(record.id);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
2
|
+
|
|
3
|
+
const providers = new Map();
|
|
4
|
+
const SOURCE = 'auna.support.v1';
|
|
5
|
+
|
|
6
|
+
function registerDashboardProvider(source, provider) {
|
|
7
|
+
if (source !== SOURCE || typeof provider !== 'function' || providers.has(source)) {
|
|
8
|
+
throw new Error('Invalid or duplicate dashboard provider');
|
|
9
|
+
}
|
|
10
|
+
providers.set(source, provider);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function validateDashboardSource(config) {
|
|
14
|
+
if (config?.source !== SOURCE || config.metric !== 'exceptions' || !providers.has(config.source)) {
|
|
15
|
+
throw new Error('Dashboard provider unavailable');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function readDashboardProvider(config, now) {
|
|
20
|
+
validateDashboardSource(config);
|
|
21
|
+
try {
|
|
22
|
+
const snapshot = await withTimeout(Promise.resolve().then(() => providers.get(config.source)({ now })), 15000, 'Dashboard provider');
|
|
23
|
+
const metric = snapshot?.metrics?.exceptions;
|
|
24
|
+
if (snapshot?.generatedAt !== now.toISOString() || Object.keys(snapshot.metrics).length !== 1
|
|
25
|
+
|| !Array.isArray(metric?.records) || metric.records.length > 2000 || !Array.isArray(metric.struct)
|
|
26
|
+
|| metric.records.some(row => !row || typeof row !== 'object' || Array.isArray(row))
|
|
27
|
+
|| metric.struct.some(column => typeof column !== 'string')
|
|
28
|
+
|| !['indicator', 'sample', 'total'].every(key => metric[key] === metric.records.length)) {
|
|
29
|
+
throw new Error('Invalid dashboard snapshot');
|
|
30
|
+
}
|
|
31
|
+
const { indicator, sample, total, struct, records } = metric;
|
|
32
|
+
return { generatedAt: snapshot.generatedAt, indicator, sample, total, struct, records };
|
|
33
|
+
} catch {
|
|
34
|
+
throw new Error('Dashboard provider unavailable');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { registerDashboardProvider, validateDashboardSource, readDashboardProvider };
|
|
@@ -5,6 +5,7 @@ const { fetchBoxesFromAirtable, fetchDetailsFromAirtable, attachPreview } = requ
|
|
|
5
5
|
const { getMexicoDateRange, buildPatientMessagesPipeline, buildToolDistributionPipeline, mergeTrendData } = require('../helpers/trendHelper');
|
|
6
6
|
|
|
7
7
|
const { aggregateMessages } = require('./messageService');
|
|
8
|
+
const { validateDashboardSource, readDashboardProvider } = require('./dashboard-provider-registry');
|
|
8
9
|
|
|
9
10
|
const boxCache = new MapCache({ maxSize: 100 });
|
|
10
11
|
const detailCache = new MapCache({ maxSize: 100 });
|
|
@@ -16,7 +17,7 @@ async function seedCaches() {
|
|
|
16
17
|
const boxes = await fetchBoxesFromAirtable();
|
|
17
18
|
boxes.forEach(box => boxCache.set(box.id, box));
|
|
18
19
|
|
|
19
|
-
const details = await fetchDetailsFromAirtable(boxes);
|
|
20
|
+
const details = await fetchDetailsFromAirtable(boxes.filter(box => box.config?.source === undefined));
|
|
20
21
|
details.forEach(({ id, records }) => {
|
|
21
22
|
detailCache.set(id, records);
|
|
22
23
|
const box = boxCache.get(id);
|
|
@@ -40,10 +41,23 @@ async function ensureSeeded(force) {
|
|
|
40
41
|
|
|
41
42
|
async function getAllBoxes(force) {
|
|
42
43
|
await ensureSeeded(force);
|
|
43
|
-
|
|
44
|
+
const snapshots = new Map();
|
|
45
|
+
const now = new Date();
|
|
46
|
+
return Promise.all(Array.from(boxCache.entries()).map(async ([id, { config, ...data }]) => {
|
|
47
|
+
if (config?.source === undefined) return { id, ...data };
|
|
48
|
+
validateDashboardSource(config);
|
|
49
|
+
if (!snapshots.has(config.source)) snapshots.set(config.source, readDashboardProvider(config, now));
|
|
50
|
+
const { records, struct: _struct, ...metric } = await snapshots.get(config.source);
|
|
51
|
+
const box = { id, ...data, ...metric };
|
|
52
|
+
attachPreview(box, records);
|
|
53
|
+
return box;
|
|
54
|
+
}));
|
|
44
55
|
}
|
|
45
56
|
|
|
46
57
|
async function getStatsById(cacheId) {
|
|
58
|
+
await ensureSeeded(false);
|
|
59
|
+
const config = boxCache.get(cacheId)?.config;
|
|
60
|
+
if (config?.source !== undefined) return { id: cacheId, ...await readDashboardProvider(config, new Date()) };
|
|
47
61
|
const detail = detailCache.get(cacheId);
|
|
48
62
|
if (!detail) return null;
|
|
49
63
|
const struct = boxCache.get(cacheId)?.config?.columns || [];
|
|
@@ -51,11 +65,24 @@ async function getStatsById(cacheId) {
|
|
|
51
65
|
}
|
|
52
66
|
|
|
53
67
|
async function updateBox(id, data) {
|
|
68
|
+
if (!data.config || Object.keys(data.config).length === 0) {
|
|
69
|
+
await ensureSeeded(false);
|
|
70
|
+
data = { ...data, config: boxCache.get(id)?.config };
|
|
71
|
+
}
|
|
72
|
+
if (data.config?.source !== undefined) {
|
|
73
|
+
validateDashboardSource(data.config);
|
|
74
|
+
data = Object.fromEntries(Object.entries(data).filter(([key]) => ['id', 'title', 'type', 'metadata', 'config'].includes(key)));
|
|
75
|
+
if (data.metadata) {
|
|
76
|
+
const { preview: _preview, ...metadata } = data.metadata;
|
|
77
|
+
data.metadata = metadata;
|
|
78
|
+
}
|
|
79
|
+
detailCache.delete(id);
|
|
80
|
+
}
|
|
54
81
|
boxCache.set(id, data);
|
|
55
82
|
logger.info('[DashboardService] Box cache updated', { id });
|
|
56
83
|
|
|
57
84
|
const box = boxCache.get(id);
|
|
58
|
-
if (box?.config?.table) {
|
|
85
|
+
if (box?.config?.source === undefined && box?.config?.table) {
|
|
59
86
|
const [detail] = await fetchDetailsFromAirtable([box]);
|
|
60
87
|
if (detail) {
|
|
61
88
|
detailCache.set(detail.id, detail.records);
|