@peopl-health/nexus 5.51.0-dev.7608 → 5.51.0-dev.7630
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 +532 -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 +141 -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/core/runtimeToolPolicy.js +3 -0
- package/lib/index.d.ts +334 -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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { isPlainObject } = require('../utils/jsonUtils');
|
|
2
2
|
const { describeThrown } = require('../utils/errorUtils');
|
|
3
3
|
const { logger } = require('../utils/logger');
|
|
4
|
+
const { MAX_ADDITIONAL_TOOL_IDS } = require('./runtimeToolPolicy');
|
|
4
5
|
|
|
5
6
|
const VALID_HOOKS = ['preProcess', 'postProcess'];
|
|
6
7
|
|
|
@@ -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,208 @@ 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: {
|
|
806
|
+
reviewedRevision: number;
|
|
807
|
+
reviewedRisk: 'green' | 'yellow';
|
|
808
|
+
Model?: unknown;
|
|
809
|
+
}): Promise<SupportCandidateRecord | null>;
|
|
810
|
+
candidatePatch(existing: SupportCandidateRecord | null | undefined, recommendation: SupportRoutingRecommendationInput, decision: SupportRoutingDecisionInput): Partial<SupportCandidateRecord>;
|
|
811
|
+
claimInvitation(request: {
|
|
812
|
+
candidateId: string;
|
|
813
|
+
invitationClass: SupportInvitationClass;
|
|
814
|
+
invitationCycle: string;
|
|
815
|
+
templateVersion: string;
|
|
816
|
+
now?: Date;
|
|
817
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
818
|
+
clearCandidateEscalation(candidateId: string, options: {
|
|
819
|
+
reviewedRevision: number;
|
|
820
|
+
approvedForGroup?: boolean;
|
|
821
|
+
reviewedRisk?: 'green' | 'yellow';
|
|
822
|
+
Model?: unknown;
|
|
823
|
+
}): Promise<SupportCandidateRecord | null>;
|
|
824
|
+
evidenceKey(item: Pick<SupportEvidence, 'source' | 'sourceId' | 'code'>): string;
|
|
825
|
+
initialState(decision: SupportRoutingDecisionInput): SupportDisposition;
|
|
826
|
+
markCandidateAccepted(request: { patientId: string; service: SupportService; sessionId?: string | null }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
827
|
+
markCandidateDeclined(request: { patientId: string; service: SupportService; preference?: 'another_date' | 'not_now' | 'never' }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
828
|
+
nextState(existing: SupportCandidateRecord | null | undefined, decision: SupportRoutingDecisionInput): SupportDisposition;
|
|
829
|
+
normalizeEvidence(items?: SupportEvidenceInput[]): Array<SupportEvidence & { key: string }>;
|
|
830
|
+
recordEngagement(request: {
|
|
831
|
+
patientId: string;
|
|
832
|
+
service: SupportService;
|
|
833
|
+
state: SupportEngagementState;
|
|
834
|
+
evidenceId?: string | null;
|
|
835
|
+
occurredAt?: string | Date | null;
|
|
836
|
+
preference?: 'another_date' | 'not_now' | 'never' | null;
|
|
837
|
+
}, options?: { Model?: unknown; historicalAttendance?: boolean }): Promise<SupportCandidateRecord | null>;
|
|
838
|
+
recordLegacyInvitationResponse(request: {
|
|
839
|
+
patientId: string;
|
|
840
|
+
service: SupportService;
|
|
841
|
+
outcome: 'accepted' | 'declined';
|
|
842
|
+
sessionId?: string | null;
|
|
843
|
+
preference?: 'another_date' | 'not_now' | 'never';
|
|
844
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
845
|
+
recordSupportRoutingRecommendation(recommendation: SupportRoutingRecommendationInput, options?: { Model?: unknown }): Promise<SupportCandidateRecord[]>;
|
|
846
|
+
rescheduleDeclinedCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
847
|
+
settleInvitation(request: {
|
|
848
|
+
candidateId: string;
|
|
849
|
+
idempotencyKey: string;
|
|
850
|
+
status: SupportDeliveryStatus;
|
|
851
|
+
providerMessageId?: string | null;
|
|
852
|
+
error?: string | null;
|
|
853
|
+
now?: Date;
|
|
854
|
+
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
855
|
+
};
|
|
856
|
+
|
|
857
|
+
export const supportActionService: {
|
|
858
|
+
prepareSupportAction(request: {
|
|
859
|
+
patientId: string;
|
|
860
|
+
sourceId: string;
|
|
861
|
+
candidates?: SupportCandidateRecord[];
|
|
862
|
+
resolveDeliveryContext?: (context: {
|
|
863
|
+
patientId: string;
|
|
864
|
+
candidates: SupportCandidateRecord[];
|
|
865
|
+
}) => SupportDeliveryContext | Promise<SupportDeliveryContext>;
|
|
866
|
+
now?: Date;
|
|
867
|
+
}, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
|
|
868
|
+
};
|
|
869
|
+
|
|
663
870
|
// BatchingManager — per-chatId concurrency control
|
|
664
871
|
export interface BatchingConfig {
|
|
665
872
|
enabled?: boolean;
|
|
@@ -669,6 +876,118 @@ declare module '@peopl-health/nexus' {
|
|
|
669
876
|
hooks?: Record<string, Function | Function[]>;
|
|
670
877
|
}
|
|
671
878
|
|
|
879
|
+
export type NutritionSafetyFindingCode =
|
|
880
|
+
| 'cannot_eat'
|
|
881
|
+
| 'cannot_keep_fluids'
|
|
882
|
+
| 'bleeding'
|
|
883
|
+
| 'severe_abdominal_pain';
|
|
884
|
+
export type NutritionSafetyFindingValue = 'yes' | 'no' | 'unknown';
|
|
885
|
+
export type NutritionSafetyQuestionCode =
|
|
886
|
+
| 'can_eat'
|
|
887
|
+
| 'can_keep_fluids'
|
|
888
|
+
| 'bleeding'
|
|
889
|
+
| 'severe_abdominal_pain';
|
|
890
|
+
export type NutritionSafetyEvidenceSourceType = 'chat' | 'flow' | 'historical' | 'forecast';
|
|
891
|
+
export type NutritionSafetyDisposition = 'clear' | 'clarify' | 'escalate' | 'review_required';
|
|
892
|
+
|
|
893
|
+
export interface NutritionSafetyEvidenceRefInput {
|
|
894
|
+
finding: NutritionSafetyFindingCode;
|
|
895
|
+
source_type: NutritionSafetyEvidenceSourceType;
|
|
896
|
+
source_id: string;
|
|
897
|
+
observed_at: string;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
export interface NutritionSafetyEvidenceRef {
|
|
901
|
+
finding: NutritionSafetyFindingCode;
|
|
902
|
+
sourceType: NutritionSafetyEvidenceSourceType;
|
|
903
|
+
sourceId: string;
|
|
904
|
+
observedAt: string;
|
|
905
|
+
traceId?: string;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
export interface NutritionSafetyDecisionInput {
|
|
909
|
+
submission_revision: number;
|
|
910
|
+
screen_revision: number;
|
|
911
|
+
findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
|
|
912
|
+
evidence_refs: NutritionSafetyEvidenceRefInput[];
|
|
913
|
+
questions_needed: NutritionSafetyQuestionCode[];
|
|
914
|
+
disposition: NutritionSafetyDisposition;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
export class NutritionSafetyDecision {
|
|
918
|
+
constructor(payload: NutritionSafetyDecisionInput);
|
|
919
|
+
submissionRevision: number;
|
|
920
|
+
screenRevision: number;
|
|
921
|
+
findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
|
|
922
|
+
evidenceRefs: NutritionSafetyEvidenceRef[];
|
|
923
|
+
questionsNeeded: NutritionSafetyQuestionCode[];
|
|
924
|
+
disposition: NutritionSafetyDisposition;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
export interface NutritionSafetyDeliveryDirective {
|
|
928
|
+
operationId: string;
|
|
929
|
+
body: string;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
export interface NutritionSafetyCommitRequest {
|
|
933
|
+
decision: NutritionSafetyDecision;
|
|
934
|
+
patientCode: string;
|
|
935
|
+
turnId: string;
|
|
936
|
+
traceId: string;
|
|
937
|
+
sourceId: string;
|
|
938
|
+
observedAt: string;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export interface NutritionSafetyCommitResult {
|
|
942
|
+
outcome: string;
|
|
943
|
+
status?: string;
|
|
944
|
+
screen?: { status: string; [key: string]: any };
|
|
945
|
+
questionsNeeded?: NutritionSafetyQuestionCode[];
|
|
946
|
+
questions_needed?: NutritionSafetyQuestionCode[];
|
|
947
|
+
deliveryDirective?: NutritionSafetyDeliveryDirective;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
export interface NutritionSafetyRepository {
|
|
951
|
+
commitDecision(request: NutritionSafetyCommitRequest): Promise<NutritionSafetyCommitResult>;
|
|
952
|
+
claimDelivery?(request: {
|
|
953
|
+
operationId: string;
|
|
954
|
+
patientCode: string;
|
|
955
|
+
turnId: string;
|
|
956
|
+
traceId: string | null;
|
|
957
|
+
sourceId: string | null;
|
|
958
|
+
}): Promise<{ acquired: boolean }>;
|
|
959
|
+
settleDelivery?(request: {
|
|
960
|
+
operationId: string;
|
|
961
|
+
outcome: 'sent' | 'known_not_sent' | 'unknown';
|
|
962
|
+
providerMessageId: string | null;
|
|
963
|
+
patientCode: string;
|
|
964
|
+
turnId: string | null;
|
|
965
|
+
traceId: string | null;
|
|
966
|
+
}): Promise<boolean | void>;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
export interface ToolRuntimeRepositories {
|
|
970
|
+
nutritionSafety?: NutritionSafetyRepository;
|
|
971
|
+
[key: string]: any;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
export const FINDING_CODES: readonly NutritionSafetyFindingCode[];
|
|
975
|
+
export const FINDING_VALUES: readonly NutritionSafetyFindingValue[];
|
|
976
|
+
export const FINDING_TO_QUESTION: Readonly<Record<NutritionSafetyFindingCode, NutritionSafetyQuestionCode>>;
|
|
977
|
+
export const QUESTION_CODES: readonly NutritionSafetyQuestionCode[];
|
|
978
|
+
export const EVIDENCE_SOURCE_TYPES: readonly NutritionSafetyEvidenceSourceType[];
|
|
979
|
+
export const DISPOSITIONS: readonly NutritionSafetyDisposition[];
|
|
980
|
+
|
|
981
|
+
export interface NexusMessagingConfig {
|
|
982
|
+
messageBatching?: BatchingConfig;
|
|
983
|
+
assistant?: {
|
|
984
|
+
mode?: 'local' | 'queue';
|
|
985
|
+
toolRuntimeRepos?: ToolRuntimeRepositories;
|
|
986
|
+
[key: string]: any;
|
|
987
|
+
};
|
|
988
|
+
[key: string]: any;
|
|
989
|
+
}
|
|
990
|
+
|
|
672
991
|
export interface DrainResult {
|
|
673
992
|
drained: boolean;
|
|
674
993
|
waitedMs: number;
|
|
@@ -705,12 +1024,14 @@ declare module '@peopl-health/nexus' {
|
|
|
705
1024
|
handleBatchedProcessing(
|
|
706
1025
|
chatId: string,
|
|
707
1026
|
processingFn: (runId: string) => Promise<any>,
|
|
708
|
-
sendResponseFn: (result: any) => Promise<void
|
|
1027
|
+
sendResponseFn: (result: any) => Promise<void>,
|
|
1028
|
+
discardResponseFn?: (result: any) => Promise<void>
|
|
709
1029
|
): Promise<TurnAdmission>;
|
|
710
1030
|
enqueueProcessing(
|
|
711
1031
|
chatId: string,
|
|
712
1032
|
processingFn: (runId: string) => Promise<any>,
|
|
713
|
-
sendResponseFn: (result: any) => Promise<void
|
|
1033
|
+
sendResponseFn: (result: any) => Promise<void>,
|
|
1034
|
+
discardResponseFn?: (result: any) => Promise<void>
|
|
714
1035
|
): Promise<TurnAdmission>;
|
|
715
1036
|
}
|
|
716
1037
|
|
|
@@ -719,7 +1040,9 @@ declare module '@peopl-health/nexus' {
|
|
|
719
1040
|
skip?: boolean;
|
|
720
1041
|
additionalInstructions?: string;
|
|
721
1042
|
additionalMessages?: Array<Record<string, any>>;
|
|
722
|
-
toolChoice?: Record<string, any> | null;
|
|
1043
|
+
toolChoice?: string | Record<string, any> | null;
|
|
1044
|
+
/** Registered tool ids to add for this turn only. Invalid ids are ignored and the list is capped at eight. */
|
|
1045
|
+
additionalToolIds?: string[];
|
|
723
1046
|
/** Recorded on the turn trace under `signals.consumer`; cannot collide with nexus-owned keys. */
|
|
724
1047
|
signals?: Record<string, any>;
|
|
725
1048
|
metadata?: Record<string, any>;
|
|
@@ -738,7 +1061,8 @@ declare module '@peopl-health/nexus' {
|
|
|
738
1061
|
run(
|
|
739
1062
|
context: ProcessingContext,
|
|
740
1063
|
executeFn: (preProcessResult: PreProcessResult, shouldContinue: () => boolean) => Promise<any>,
|
|
741
|
-
shouldContinue?: () => boolean
|
|
1064
|
+
shouldContinue?: () => boolean,
|
|
1065
|
+
discardResult?: (result: any) => Promise<void>
|
|
742
1066
|
): Promise<any>;
|
|
743
1067
|
}
|
|
744
1068
|
|
|
@@ -756,6 +1080,7 @@ declare module '@peopl-health/nexus' {
|
|
|
756
1080
|
sendMessage?: (messageData: MessageData) => Promise<any>;
|
|
757
1081
|
storeRunMetrics?: (code: string, thread: any, result: any, timings?: Record<string, any>) => Promise<void>;
|
|
758
1082
|
llmMonitor?: { enqueueTurn(turnId: string): Promise<string | null> } | null;
|
|
1083
|
+
toolRuntimeRepos?: ToolRuntimeRepositories;
|
|
759
1084
|
}
|
|
760
1085
|
|
|
761
1086
|
export interface ProcessInput {
|
|
@@ -776,6 +1101,8 @@ declare module '@peopl-health/nexus' {
|
|
|
776
1101
|
predictionTimeMs?: number;
|
|
777
1102
|
retries?: number;
|
|
778
1103
|
completed?: boolean;
|
|
1104
|
+
/** Internal delivery ownership receipt; never contains the directive body. */
|
|
1105
|
+
deliveryDirective?: { operationId: string; claimed: boolean; settled: boolean };
|
|
779
1106
|
}
|
|
780
1107
|
|
|
781
1108
|
export class AssistantProcessor {
|
|
@@ -785,6 +1112,7 @@ declare module '@peopl-health/nexus' {
|
|
|
785
1112
|
executeLLM(thread: any, assistant: any, runOptions?: AssistantRunOptions, message?: any): Promise<LLMResult>;
|
|
786
1113
|
process(input: ProcessInput): Promise<LLMResult | null>;
|
|
787
1114
|
sendResponse(code: string, result: any): Promise<string | null>;
|
|
1115
|
+
discardResponse(code: string, result: any): Promise<boolean>;
|
|
788
1116
|
}
|
|
789
1117
|
|
|
790
1118
|
}
|
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);
|