@peopl-health/nexus 5.51.0-dev.7633 → 5.51.0-dev.7635
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 +28 -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 +453 -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 +142 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/controllers/escalationReviewController.js +0 -12
- 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/models/escalationReviewModel.js +0 -4
- package/lib/routes/index.js +0 -2
- 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 +4 -36
- 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
|
@@ -146,6 +146,7 @@ class NexusMessaging {
|
|
|
146
146
|
phiProcessor: this.phiProcessor,
|
|
147
147
|
storeRunMetrics,
|
|
148
148
|
llmMonitor: this.llmMonitor,
|
|
149
|
+
toolRuntimeRepos: config.assistant?.toolRuntimeRepos || {},
|
|
149
150
|
});
|
|
150
151
|
|
|
151
152
|
this.scheduledMessageJob = new ScheduledMessageJob({
|
|
@@ -635,24 +636,33 @@ class NexusMessaging {
|
|
|
635
636
|
|
|
636
637
|
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
|
|
637
638
|
let capturedResult = null;
|
|
639
|
+
const discardResponseFn = async (result) => {
|
|
640
|
+
await this.assistantProcessor.discardResponse(chatId, result);
|
|
641
|
+
};
|
|
638
642
|
|
|
639
643
|
const processingFn = async (runId) => {
|
|
640
644
|
const shouldContinue = () => this.batchingManager.isActiveRun(chatId, runId);
|
|
641
645
|
capturedResult = await this.pipeline.run(
|
|
642
646
|
{ chatId, runId, type },
|
|
643
647
|
executeFn,
|
|
644
|
-
shouldContinue
|
|
648
|
+
shouldContinue,
|
|
649
|
+
discardResponseFn,
|
|
645
650
|
);
|
|
646
651
|
return capturedResult;
|
|
647
652
|
};
|
|
648
653
|
|
|
649
654
|
const sendResponseFn = async (result) => {
|
|
650
|
-
if (sendResponse)
|
|
655
|
+
if (!sendResponse) return;
|
|
656
|
+
if (result?.turnId && !this.batchingManager.isActiveRun(chatId, result.turnId)) {
|
|
657
|
+
await discardResponseFn(result);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
await this.assistantProcessor.sendResponse(chatId, result);
|
|
651
661
|
};
|
|
652
662
|
|
|
653
663
|
const admission = mode === 'queue'
|
|
654
|
-
? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn)
|
|
655
|
-
: await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
|
|
664
|
+
? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn)
|
|
665
|
+
: await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn);
|
|
656
666
|
|
|
657
667
|
if (admission?.accepted === false) return { deferred: true, reason: admission.reason };
|
|
658
668
|
|
|
@@ -691,7 +701,14 @@ class NexusMessaging {
|
|
|
691
701
|
preProcessed.messages[0]
|
|
692
702
|
);
|
|
693
703
|
|
|
694
|
-
|
|
704
|
+
try {
|
|
705
|
+
if (storeRunMetrics) {
|
|
706
|
+
await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
|
|
707
|
+
}
|
|
708
|
+
} catch (error) {
|
|
709
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
695
712
|
return { ...result, timings: preProcessed.timings };
|
|
696
713
|
}, shouldContinue, runId);
|
|
697
714
|
}
|
|
@@ -1012,9 +1029,10 @@ class NexusMessaging {
|
|
|
1012
1029
|
async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
|
|
1013
1030
|
const query = { numero: chatId, from_me: false, processed: false };
|
|
1014
1031
|
const unprocessed = await getMessages(query, { select: '_id' });
|
|
1032
|
+
let result = null;
|
|
1015
1033
|
|
|
1016
1034
|
try {
|
|
1017
|
-
|
|
1035
|
+
result = await processingFn();
|
|
1018
1036
|
if (unprocessed.length > 0 && shouldFinalize()) {
|
|
1019
1037
|
const marks = runId ? { processed: true, processedByTurnId: runId } : { processed: true };
|
|
1020
1038
|
await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: marks });
|
|
@@ -1022,6 +1040,7 @@ class NexusMessaging {
|
|
|
1022
1040
|
}
|
|
1023
1041
|
return result;
|
|
1024
1042
|
} catch (error) {
|
|
1043
|
+
if (result) await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
1025
1044
|
logger.debug('[_processMessages] Processing failed', { chatId });
|
|
1026
1045
|
throw error;
|
|
1027
1046
|
}
|
|
@@ -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
|
};
|
|
@@ -7,7 +7,6 @@ const { logger } = require('../utils/logger');
|
|
|
7
7
|
const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
|
|
8
8
|
const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
9
9
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
10
|
-
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready'];
|
|
11
10
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
|
|
12
11
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
|
|
13
12
|
|
|
@@ -84,7 +83,6 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
84
83
|
'indications_queued',
|
|
85
84
|
'indications_sent',
|
|
86
85
|
'closed',
|
|
87
|
-
'cancelled',
|
|
88
86
|
],
|
|
89
87
|
default: 'open',
|
|
90
88
|
},
|
|
@@ -102,7 +100,6 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
102
100
|
|
|
103
101
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
104
102
|
escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
|
|
105
|
-
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
106
103
|
|
|
107
104
|
const getEscalationReview = () => {
|
|
108
105
|
const dbName = getModelDatabase('EscalationReview');
|
|
@@ -113,7 +110,6 @@ const getEscalationReview = () => {
|
|
|
113
110
|
|
|
114
111
|
module.exports = {
|
|
115
112
|
CALL_OUTCOMES,
|
|
116
|
-
CANCELLABLE_STATUSES,
|
|
117
113
|
DECISION_SOURCES,
|
|
118
114
|
DOCTOR_DECISIONS,
|
|
119
115
|
HANDOFF_MODES,
|
package/lib/routes/index.js
CHANGED
|
@@ -126,7 +126,6 @@ const escalationReviewRouteDefinitions = {
|
|
|
126
126
|
'POST /:id/decisions': 'recordEscalationReviewDecisionController',
|
|
127
127
|
'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
|
|
128
128
|
'POST /:id/close': 'closeEscalationReviewController',
|
|
129
|
-
'POST /:id/cancel': 'cancelEscalationReviewController',
|
|
130
129
|
'POST /:id/case-sync': 'syncEscalationReviewCaseController'
|
|
131
130
|
};
|
|
132
131
|
|
|
@@ -286,7 +285,6 @@ const builtInControllers = {
|
|
|
286
285
|
recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
|
|
287
286
|
sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
|
|
288
287
|
closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
|
|
289
|
-
cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
|
|
290
288
|
syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
|
|
291
289
|
};
|
|
292
290
|
|
|
@@ -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);
|