@peopl-health/nexus 5.61.0-dev.11181 → 5.61.0-dev.11186
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/lib/adapters/messageAdapters/TwilioMessageAdapter.js +0 -1
- package/lib/clinical/AssistantProcessor.js +16 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +74 -0
- package/lib/clinical/services/escalationDraftService.js +17 -3
- package/lib/clinical/services/treatmentProposalService.js +7 -2
- package/lib/clinical/tools/reportMedicalEscalationTool.js +3 -0
- package/lib/config/lifecycle.js +4 -1
- package/lib/controllers/escalationReviewController.js +15 -0
- package/lib/controllers/messageController.js +21 -1
- package/lib/index.d.ts +14 -5
- package/lib/index.js +20 -1
- package/lib/models/escalationReviewModel.js +64 -2
- package/lib/routes/index.js +2 -0
- package/lib/services/escalationReviewService.js +614 -45
- package/lib/services/messageService.js +1 -4
- package/lib/services/patientTaskService.js +1 -0
- package/lib/services/reviewAlertSweepService.js +88 -0
- package/lib/services/reviewDraftSweepService.js +79 -0
- package/lib/storage/MongoStorage.js +2 -14
- package/package.json +1 -1
- package/lib/clinical/models/clinicalSourceEventModel.js +0 -32
- package/lib/clinical/services/clinicalCaptureConfigService.js +0 -22
- package/lib/clinical/services/clinicalEventService.js +0 -132
- package/lib/clinical/services/clinicalMessageCaptureService.js +0 -72
|
@@ -26,7 +26,6 @@ class TwilioMessageAdapter extends MessageAdapter {
|
|
|
26
26
|
processed: false,
|
|
27
27
|
pushName: rawMessage.ProfileName || null,
|
|
28
28
|
body,
|
|
29
|
-
normalizedContent: contactBody ? { type: 'extracted_contact', text: contactBody } : null,
|
|
30
29
|
media,
|
|
31
30
|
interactive,
|
|
32
31
|
quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
|
|
@@ -15,6 +15,7 @@ const { isContingencyCancelOnReplyLive } = require('./flags/contingencyFlags');
|
|
|
15
15
|
const { maybeWarmPatientRisk } = require('./services/riskAssessmentService');
|
|
16
16
|
const { settleClaimedDelivery } = require('./services/deliverySettlementService');
|
|
17
17
|
const { ToolRuntimeContext } = require('./context/ToolRuntimeContext');
|
|
18
|
+
const { reviewUpdateOf } = require('./helpers/reviewUpdateHelper');
|
|
18
19
|
const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
|
|
19
20
|
|
|
20
21
|
const traceContingency = (net) => ({
|
|
@@ -256,6 +257,21 @@ class AssistantProcessor {
|
|
|
256
257
|
});
|
|
257
258
|
}
|
|
258
259
|
|
|
260
|
+
if (traceStored && !runOptions.shadow) {
|
|
261
|
+
const update = reviewUpdateOf({
|
|
262
|
+
turnId: ctx.turnId,
|
|
263
|
+
toolHistory: ctx.toolHistory,
|
|
264
|
+
signals: ctx.trace?.signals,
|
|
265
|
+
patientText: ctx.patientInput?.text,
|
|
266
|
+
});
|
|
267
|
+
if (update) {
|
|
268
|
+
// Required here: escalationReviewService reaches this module through NexusMessaging.
|
|
269
|
+
const { recordReviewUpdate } = require('../services/escalationReviewService');
|
|
270
|
+
// Awaited so it lands before the turn returns; it never throws and never fails the reply.
|
|
271
|
+
await recordReviewUpdate({ code: thread.code, update });
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
259
275
|
const run = runResult?.run;
|
|
260
276
|
|
|
261
277
|
return {
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
const { objectArg } = require('../../utils/jsonUtils');
|
|
2
|
+
const { isToolFailure } = require('./toolResultHelper');
|
|
3
|
+
|
|
4
|
+
const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
|
|
5
|
+
const CHARACTERIZATION_TOOLS = ['extractClinicalInfo', ...IMPRESSION_TOOLS, 'reportMedicalEscalation'];
|
|
6
|
+
const MAX_PATIENT_TEXT = 500;
|
|
7
|
+
|
|
8
|
+
const textOf = (value) => {
|
|
9
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
10
|
+
return text && text.toLowerCase() !== 'none' ? text : null;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const gradeOf = (gradeEstimate) => {
|
|
14
|
+
const grade = objectArg(gradeEstimate)?.best_estimate;
|
|
15
|
+
return Number.isInteger(grade) ? grade : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const impressionOf = (call) => {
|
|
19
|
+
const args = objectArg(call.tool_arguments) || {};
|
|
20
|
+
const result = objectArg(call.tool_output)?.data;
|
|
21
|
+
return {
|
|
22
|
+
caseId: textOf(args.case_id) || textOf(result?.case_id),
|
|
23
|
+
ctcaeTerm: textOf(args.ctcae_term),
|
|
24
|
+
event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
|
|
25
|
+
// A carried-forward grade is resolved by the tool, so its result holds the grade the call omitted.
|
|
26
|
+
grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
|
|
27
|
+
trajectory: textOf(args.trajectory_direction),
|
|
28
|
+
missingForHigherGrade: textOf(args.missing_for_higher_grade),
|
|
29
|
+
checkInQuestion: textOf(args.check_in_question),
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
|
|
34
|
+
|
|
35
|
+
// What the agent characterized this turn, or null when it did not characterize anything:
|
|
36
|
+
// a courtesy reply runs the extractor too, but leaves no mention, impression or escalation behind.
|
|
37
|
+
function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
|
|
38
|
+
const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
|
|
39
|
+
const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
|
|
40
|
+
const safetyFlags = (Array.isArray(signals?.safetyFlags) ? signals.safetyFlags : []).map(flagNameOf).filter(Boolean);
|
|
41
|
+
const assessed = calls.some((call) => call.tool_name !== 'extractClinicalInfo');
|
|
42
|
+
if (!turnId || (!assessed && mentionCount === 0 && !safetyFlags.length)) return null;
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
turnId,
|
|
46
|
+
tools: [...new Set(calls.map((call) => call.tool_name))],
|
|
47
|
+
patientText: textOf(patientText)?.slice(0, MAX_PATIENT_TEXT) || null,
|
|
48
|
+
impressions: calls.filter((call) => IMPRESSION_TOOLS.includes(call.tool_name)).map(impressionOf),
|
|
49
|
+
safetyFlags,
|
|
50
|
+
at,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// The agent's own reading of each case since the escalation, handed to the draft so it builds on it
|
|
55
|
+
// instead of re-deriving it: the latest impression per case, the safety flags and what the patient said.
|
|
56
|
+
function characterizationSeedOf(updates = []) {
|
|
57
|
+
if (!Array.isArray(updates) || !updates.length) return null;
|
|
58
|
+
// Clinical order is the turn time, not the order the writes landed in.
|
|
59
|
+
const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
|
|
60
|
+
const latestByCase = new Map();
|
|
61
|
+
byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
|
|
62
|
+
const key = impression.caseId || impression.ctcaeTerm;
|
|
63
|
+
if (key) latestByCase.set(key, { ...impression, at: update.at });
|
|
64
|
+
}));
|
|
65
|
+
return {
|
|
66
|
+
cases: [...latestByCase.values()],
|
|
67
|
+
safetyFlags: [...new Set(updates.flatMap((update) => update.safetyFlags || []))],
|
|
68
|
+
newSinceEscalation: byTime
|
|
69
|
+
.filter((update) => update.patientText)
|
|
70
|
+
.map((update) => ({ at: update.at, patientText: update.patientText })),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
module.exports = { characterizationSeedOf, reviewUpdateOf };
|
|
@@ -45,7 +45,14 @@ function settleProposal(parsed) {
|
|
|
45
45
|
return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
const textList = (value) => (Array.isArray(value) ? value.map(trimmed).filter(Boolean) : []);
|
|
49
|
+
|
|
50
|
+
function suggestCallOf(value) {
|
|
51
|
+
if (typeof value?.value !== 'boolean') return null;
|
|
52
|
+
return { value: value.value, reason: trimmed(value.reason) || null };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
|
|
49
56
|
const conversation = Array.isArray(context?.conversation)
|
|
50
57
|
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
51
58
|
: context?.conversation ?? null;
|
|
@@ -58,6 +65,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
|
|
|
58
65
|
protocolVersion: FORMULARY_VERSION,
|
|
59
66
|
protocol,
|
|
60
67
|
alarms,
|
|
68
|
+
agentCharacterization,
|
|
61
69
|
patient: {
|
|
62
70
|
clinicalContext: context?.agentContext ?? null,
|
|
63
71
|
conversation,
|
|
@@ -83,7 +91,9 @@ function draftProvider() {
|
|
|
83
91
|
}
|
|
84
92
|
}
|
|
85
93
|
|
|
86
|
-
async function generateEscalationDraft({
|
|
94
|
+
async function generateEscalationDraft({
|
|
95
|
+
code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
|
|
96
|
+
} = {}) {
|
|
87
97
|
const { presetId } = await getEscalationDraft();
|
|
88
98
|
const llm = provider ?? draftProvider();
|
|
89
99
|
|
|
@@ -92,7 +102,7 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
92
102
|
}
|
|
93
103
|
|
|
94
104
|
const context = await getEscalationContext({ code, now });
|
|
95
|
-
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
|
|
105
|
+
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms, agentCharacterization });
|
|
96
106
|
|
|
97
107
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
98
108
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -165,6 +175,10 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
165
175
|
doctorText,
|
|
166
176
|
patientMessage,
|
|
167
177
|
protocolVersion: FORMULARY_VERSION,
|
|
178
|
+
keyQuestions: textList(parsed?.keyQuestions),
|
|
179
|
+
unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
|
|
180
|
+
missingCharacterization: textList(parsed?.missingCharacterization),
|
|
181
|
+
suggestCall: suggestCallOf(parsed?.suggestCall),
|
|
168
182
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
169
183
|
};
|
|
170
184
|
}
|
|
@@ -102,10 +102,14 @@ function resolvedDrugs(proposals) {
|
|
|
102
102
|
});
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
function drugsNamedIn(text) {
|
|
106
|
+
const padded = ` ${key(text)} `;
|
|
107
|
+
return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
|
|
108
|
+
}
|
|
109
|
+
|
|
105
110
|
function unproposedDrugsIn(text, proposals) {
|
|
106
111
|
const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
|
|
107
|
-
|
|
108
|
-
return DRUG_NAMES.filter((name) => !proposed.has(name) && padded.includes(` ${name} `));
|
|
112
|
+
return drugsNamedIn(text).filter((name) => !proposed.has(name));
|
|
109
113
|
}
|
|
110
114
|
|
|
111
115
|
function crossSymptomIssues(proposals) {
|
|
@@ -127,5 +131,6 @@ function crossSymptomIssues(proposals) {
|
|
|
127
131
|
module.exports = {
|
|
128
132
|
validateProposal,
|
|
129
133
|
unproposedDrugsIn,
|
|
134
|
+
drugsNamedIn,
|
|
130
135
|
crossSymptomIssues,
|
|
131
136
|
};
|
|
@@ -241,6 +241,9 @@ async function handler(args, context = {}) {
|
|
|
241
241
|
suspectedCondition: details.suspected_condition || null,
|
|
242
242
|
recommendedAction: details.recommended_action || null,
|
|
243
243
|
justification: args?.urgency_justification || null,
|
|
244
|
+
indicators: (Array.isArray(details.indicators) ? details.indicators : [])
|
|
245
|
+
.filter((indicator) => typeof indicator === 'string' && indicator.trim()),
|
|
246
|
+
turnId: runtime.turnId || null,
|
|
244
247
|
},
|
|
245
248
|
});
|
|
246
249
|
queued = await recordEmergency({
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -6,6 +6,7 @@ const { _clearClinicalContextCache } = require('../helpers/patientInformationHel
|
|
|
6
6
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
7
7
|
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
8
8
|
const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
|
|
9
|
+
const { stopReviewDraftSweep } = require('../services/reviewDraftSweepService');
|
|
9
10
|
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
10
11
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
11
12
|
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
@@ -20,7 +21,9 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
|
20
21
|
const SWEEP_STOP_MS = 2000;
|
|
21
22
|
|
|
22
23
|
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
23
|
-
const stopped = Promise.allSettled([
|
|
24
|
+
const stopped = Promise.allSettled([
|
|
25
|
+
stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(),
|
|
26
|
+
]);
|
|
24
27
|
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
25
28
|
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
26
29
|
}
|
|
@@ -7,6 +7,7 @@ const {
|
|
|
7
7
|
cancelEscalationReview,
|
|
8
8
|
closeEscalationReview,
|
|
9
9
|
getEscalationReviewById,
|
|
10
|
+
getReviewTimeline,
|
|
10
11
|
handOffToDoctor,
|
|
11
12
|
listEscalationReviews,
|
|
12
13
|
openEscalationReview,
|
|
@@ -53,6 +54,15 @@ const getEscalationReviewController = async (req, res) => {
|
|
|
53
54
|
}
|
|
54
55
|
};
|
|
55
56
|
|
|
57
|
+
const getReviewTimelineController = async (req, res) => {
|
|
58
|
+
try {
|
|
59
|
+
const timeline = await getReviewTimeline({ id: req.params.id });
|
|
60
|
+
res.status(200).json({ success: true, timeline });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
respondWithError(res, error, 'reading the escalation review timeline', { reviewId: req.params?.id });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
56
66
|
const listEscalationReviewsController = async (req, res) => {
|
|
57
67
|
try {
|
|
58
68
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
@@ -143,6 +153,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
143
153
|
comment = null,
|
|
144
154
|
doctorName = null,
|
|
145
155
|
doctorReply = null,
|
|
156
|
+
reason = null,
|
|
157
|
+
draftNumber = null,
|
|
146
158
|
triggeredBy,
|
|
147
159
|
} = req.body || {};
|
|
148
160
|
const review = await recordDoctorDecision({
|
|
@@ -153,6 +165,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
153
165
|
comment,
|
|
154
166
|
doctorName,
|
|
155
167
|
doctorReply,
|
|
168
|
+
reason,
|
|
169
|
+
draftNumber,
|
|
156
170
|
recordedBy: triggeredBy,
|
|
157
171
|
requestId: req.requestId,
|
|
158
172
|
});
|
|
@@ -224,6 +238,7 @@ module.exports = {
|
|
|
224
238
|
cancelEscalationReviewController,
|
|
225
239
|
closeEscalationReviewController,
|
|
226
240
|
getEscalationReviewController,
|
|
241
|
+
getReviewTimelineController,
|
|
227
242
|
handOffEscalationReviewController,
|
|
228
243
|
listEscalationReviewsController,
|
|
229
244
|
openEscalationReviewController,
|
|
@@ -2,6 +2,7 @@ const moment = require('moment-timezone');
|
|
|
2
2
|
const mongoose = require('mongoose');
|
|
3
3
|
|
|
4
4
|
const { logger } = require('../utils/logger');
|
|
5
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
5
6
|
|
|
6
7
|
const { ScheduledMessage } = require('../models/agendaMessageModel.js');
|
|
7
8
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
|
|
@@ -13,6 +14,9 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
|
|
|
13
14
|
|
|
14
15
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
15
16
|
const { getMessages } = require('../services/messageService');
|
|
17
|
+
const { recordDirectIndication } = require('../services/escalationReviewService');
|
|
18
|
+
|
|
19
|
+
const INDICATION_WAIT_MS = 5000;
|
|
16
20
|
|
|
17
21
|
const { sendMessage, sendScheduledMessage, getDefaultInstance } = require('../core/NexusMessaging');
|
|
18
22
|
|
|
@@ -69,7 +73,8 @@ const sendMessageController = async (req, res) => {
|
|
|
69
73
|
frontendId = null,
|
|
70
74
|
triggeredBy = null,
|
|
71
75
|
idempotencyKey = null,
|
|
72
|
-
contactCode = null
|
|
76
|
+
contactCode = null,
|
|
77
|
+
asIndication = false
|
|
73
78
|
} = req.body || {};
|
|
74
79
|
|
|
75
80
|
const formattedCode = ensureWhatsAppFormat(code);
|
|
@@ -100,6 +105,21 @@ const sendMessageController = async (req, res) => {
|
|
|
100
105
|
variables: finalVariables, code: formattedCode,
|
|
101
106
|
frontendId, triggeredBy, idempotencyKey, ...contact
|
|
102
107
|
});
|
|
108
|
+
// Only a message the approver explicitly sent as the indication resolves the clinical review.
|
|
109
|
+
if (asIndication === true && result?.success && triggeredBy && message && !contentSid && !contact.contactCode) {
|
|
110
|
+
// Awaited so the review is usually settled before the reply returns, but never for long: the
|
|
111
|
+
// message already went out, and a slow lookup finishes in the background. It never throws.
|
|
112
|
+
await withTimeout(recordDirectIndication({
|
|
113
|
+
code: formattedCode,
|
|
114
|
+
triggeredBy,
|
|
115
|
+
body: message,
|
|
116
|
+
messageId: _pickMessageId(result, null),
|
|
117
|
+
status: result?.status ?? null,
|
|
118
|
+
deferred: result?.deferred === true || result?.preemptive === true,
|
|
119
|
+
}), INDICATION_WAIT_MS, 'clinical review resolution').catch((error) => {
|
|
120
|
+
logger.warn('[sendMessageController] The clinical review is still resolving in the background', { error: error.message });
|
|
121
|
+
});
|
|
122
|
+
}
|
|
103
123
|
return res.status(200).json({
|
|
104
124
|
success: result?.success ?? true,
|
|
105
125
|
messageId: _pickMessageId(result, null),
|
package/lib/index.d.ts
CHANGED
|
@@ -11,8 +11,6 @@ declare module '@peopl-health/nexus' {
|
|
|
11
11
|
contactName?: string | null;
|
|
12
12
|
contactLabel?: string | null;
|
|
13
13
|
body?: string;
|
|
14
|
-
/** Derived first-capture contact evidence; never canonical patient identity. */
|
|
15
|
-
normalizedContent?: { type: 'extracted_contact'; text: string } | null;
|
|
16
14
|
message?: string;
|
|
17
15
|
timestamp?: string | Date;
|
|
18
16
|
createdAt?: string | Date;
|
|
@@ -88,8 +86,6 @@ declare module '@peopl-health/nexus' {
|
|
|
88
86
|
}
|
|
89
87
|
|
|
90
88
|
export interface StorageConfig {
|
|
91
|
-
/** Explicit prospective journal configuration. Enabled capture requires tenantId and a Clinical mapping set before Nexus.initialize(). */
|
|
92
|
-
clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
|
|
93
89
|
mongoUri: string;
|
|
94
90
|
dbName: string;
|
|
95
91
|
collections?: {
|
|
@@ -359,6 +355,8 @@ declare module '@peopl-health/nexus' {
|
|
|
359
355
|
ner?: NerOptions;
|
|
360
356
|
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
361
357
|
inboundRecovery?: InboundRecoveryOptions;
|
|
358
|
+
reviewDrafts?: ReviewDraftsOptions;
|
|
359
|
+
reviewAlerts?: ReviewAlertsOptions;
|
|
362
360
|
}
|
|
363
361
|
|
|
364
362
|
export interface RecommendationRecoveryOptions {
|
|
@@ -366,6 +364,18 @@ declare module '@peopl-health/nexus' {
|
|
|
366
364
|
intervalMs?: number;
|
|
367
365
|
}
|
|
368
366
|
|
|
367
|
+
export interface ReviewDraftsOptions {
|
|
368
|
+
/** Writes the clinical review draft automatically after each alarm or agent update. */
|
|
369
|
+
enabled?: boolean;
|
|
370
|
+
intervalMs?: number;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export interface ReviewAlertsOptions {
|
|
374
|
+
/** WhatsApps the approver on stat/asap reviews and re-alerts an unanswered stat review. */
|
|
375
|
+
enabled?: boolean;
|
|
376
|
+
intervalMs?: number;
|
|
377
|
+
}
|
|
378
|
+
|
|
369
379
|
export interface InboundRecoveryOptions {
|
|
370
380
|
enabled: boolean;
|
|
371
381
|
intervalMs?: number;
|
|
@@ -411,7 +421,6 @@ declare module '@peopl-health/nexus' {
|
|
|
411
421
|
export function requestIdMiddleware(req: any, res: any, next: () => void): void;
|
|
412
422
|
export function getRequestId(): string | null;
|
|
413
423
|
|
|
414
|
-
/** Set the Clinical mapping before initializing MongoStorage with enabled clinicalEventCapture. */
|
|
415
424
|
export function setModelDatabases(mapping: Record<string, string>): void;
|
|
416
425
|
export function setModelDatabase(modelName: string, dbName: string): void;
|
|
417
426
|
export function getModelDatabase(modelName: string): string | null;
|
package/lib/index.js
CHANGED
|
@@ -32,6 +32,8 @@ const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNet
|
|
|
32
32
|
const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
33
|
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
34
|
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
35
|
+
const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
|
|
36
|
+
const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
|
|
35
37
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
36
38
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
37
39
|
const { DrainingError } = require('./core/BatchingManager');
|
|
@@ -119,7 +121,6 @@ class Nexus {
|
|
|
119
121
|
}
|
|
120
122
|
this.messaging.setMessageStorage(this.storage);
|
|
121
123
|
} catch (e) {
|
|
122
|
-
if (e?.code === 'CLINICAL_SOURCE_CONFIG') throw e;
|
|
123
124
|
logger.warn('Warning: storage initialization failed:', e?.message || e);
|
|
124
125
|
}
|
|
125
126
|
}
|
|
@@ -204,6 +205,24 @@ class Nexus {
|
|
|
204
205
|
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
205
206
|
}
|
|
206
207
|
|
|
208
|
+
try {
|
|
209
|
+
if (options.reviewDrafts?.enabled === true) {
|
|
210
|
+
startReviewDraftSweep({ intervalMs: options.reviewDrafts.intervalMs });
|
|
211
|
+
logger.info('[Nexus] clinical review draft sweep armed');
|
|
212
|
+
}
|
|
213
|
+
} catch (e) {
|
|
214
|
+
logger.warn('Warning: failed to arm the clinical review draft sweep:', e?.message || e);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
if (options.reviewAlerts?.enabled === true) {
|
|
219
|
+
startReviewAlertSweep({ intervalMs: options.reviewAlerts.intervalMs });
|
|
220
|
+
logger.info('[Nexus] clinical review doctor alert sweep armed');
|
|
221
|
+
}
|
|
222
|
+
} catch (e) {
|
|
223
|
+
logger.warn('Warning: failed to arm the clinical review doctor alert sweep:', e?.message || e);
|
|
224
|
+
}
|
|
225
|
+
|
|
207
226
|
try {
|
|
208
227
|
if (options.inboundRecovery?.enabled === true) {
|
|
209
228
|
startInboundRecoverySweep({
|
|
@@ -10,8 +10,9 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
|
10
10
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
11
11
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
12
12
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
13
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
|
|
14
|
-
const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
|
|
13
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'direct_chat'];
|
|
14
|
+
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
15
|
+
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
15
16
|
|
|
16
17
|
const alarmSchema = new mongoose.Schema({
|
|
17
18
|
urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
|
|
@@ -21,9 +22,41 @@ const alarmSchema = new mongoose.Schema({
|
|
|
21
22
|
suspectedCondition: { type: String, default: null },
|
|
22
23
|
recommendedAction: { type: String, default: null },
|
|
23
24
|
justification: { type: String, default: null },
|
|
25
|
+
indicators: { type: [String], default: undefined },
|
|
26
|
+
turnId: { type: String, default: null },
|
|
24
27
|
raisedAt: { type: Date, required: true },
|
|
25
28
|
}, { _id: false });
|
|
26
29
|
|
|
30
|
+
const impressionUpdateSchema = new mongoose.Schema({
|
|
31
|
+
caseId: { type: String, default: null },
|
|
32
|
+
ctcaeTerm: { type: String, default: null },
|
|
33
|
+
event: { type: String, default: null },
|
|
34
|
+
grade: { type: Number, default: null },
|
|
35
|
+
trajectory: { type: String, default: null },
|
|
36
|
+
missingForHigherGrade: { type: String, default: null },
|
|
37
|
+
checkInQuestion: { type: String, default: null },
|
|
38
|
+
}, { _id: false });
|
|
39
|
+
|
|
40
|
+
const doctorAlertSchema = new mongoose.Schema({
|
|
41
|
+
kind: { type: String, enum: ['initial', 'realert'], required: true },
|
|
42
|
+
urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
|
|
43
|
+
physicianEmail: { type: String, default: null },
|
|
44
|
+
transport: { type: String, default: null },
|
|
45
|
+
messageId: { type: String, default: null },
|
|
46
|
+
error: { type: String, default: null },
|
|
47
|
+
teamAlerted: { type: Boolean, default: false },
|
|
48
|
+
sentAt: { type: Date, required: true },
|
|
49
|
+
}, { _id: false });
|
|
50
|
+
|
|
51
|
+
const reviewUpdateSchema = new mongoose.Schema({
|
|
52
|
+
turnId: { type: String, required: true },
|
|
53
|
+
tools: { type: [String], default: [] },
|
|
54
|
+
patientText: { type: String, default: null },
|
|
55
|
+
impressions: { type: [impressionUpdateSchema], default: [] },
|
|
56
|
+
safetyFlags: { type: [String], default: [] },
|
|
57
|
+
at: { type: Date, required: true },
|
|
58
|
+
}, { _id: false });
|
|
59
|
+
|
|
27
60
|
const noteFactSchema = new mongoose.Schema({
|
|
28
61
|
variableId: { type: String, required: true },
|
|
29
62
|
concept: { type: String, default: null },
|
|
@@ -44,10 +77,21 @@ const callLogSchema = new mongoose.Schema({
|
|
|
44
77
|
loggedBy: { type: String, required: true },
|
|
45
78
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
46
79
|
|
|
80
|
+
const suggestCallSchema = new mongoose.Schema({
|
|
81
|
+
value: { type: Boolean, required: true },
|
|
82
|
+
reason: { type: String, default: null },
|
|
83
|
+
}, { _id: false });
|
|
84
|
+
|
|
47
85
|
const draftSchema = new mongoose.Schema({
|
|
48
86
|
doctorText: { type: String, required: true },
|
|
49
87
|
patientMessage: { type: String, required: true },
|
|
50
88
|
writtenBy: { type: String, required: true },
|
|
89
|
+
protocolVersion: { type: String, default: null },
|
|
90
|
+
keyQuestions: { type: [String], default: undefined },
|
|
91
|
+
unassessedRedFlags: { type: [String], default: undefined },
|
|
92
|
+
missingCharacterization: { type: [String], default: undefined },
|
|
93
|
+
suggestCall: { type: suggestCallSchema, default: undefined },
|
|
94
|
+
sectionsUnavailable: { type: [String], default: undefined },
|
|
51
95
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
52
96
|
|
|
53
97
|
const doctorHandoffSchema = new mongoose.Schema({
|
|
@@ -68,6 +112,8 @@ const decisionSchema = new mongoose.Schema({
|
|
|
68
112
|
finalText: { type: String, default: null },
|
|
69
113
|
comment: { type: String, default: null },
|
|
70
114
|
doctorReply: { type: String, default: null },
|
|
115
|
+
returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
|
|
116
|
+
warnings: { type: [String], default: undefined },
|
|
71
117
|
decidedBy: { type: String, required: true },
|
|
72
118
|
recordedBy: { type: String, required: true },
|
|
73
119
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
@@ -126,6 +172,19 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
126
172
|
openedBy: { type: String, required: true },
|
|
127
173
|
assistantPausedByReview: { type: Boolean, default: false },
|
|
128
174
|
alarms: { type: [alarmSchema], default: [] },
|
|
175
|
+
updates: { type: [reviewUpdateSchema], default: [] },
|
|
176
|
+
updatedSinceSeen: { type: Boolean, default: false },
|
|
177
|
+
followUpCases: { type: [String], default: undefined },
|
|
178
|
+
// The decision the follow-up cases were fixed for; a later indication extends them.
|
|
179
|
+
followUpDecision: { type: Number, default: null },
|
|
180
|
+
draftDueAt: { type: Date, default: null },
|
|
181
|
+
draftAttempts: { type: Number, default: 0 },
|
|
182
|
+
doctorAlerts: { type: [doctorAlertSchema], default: [] },
|
|
183
|
+
doctorAlertDueAt: { type: Date, default: null },
|
|
184
|
+
doctorAlertKind: { type: String, enum: ['initial', 'realert', null], default: null },
|
|
185
|
+
doctorAlertAttempts: { type: Number, default: 0 },
|
|
186
|
+
approverViewedAt: { type: Date, default: null },
|
|
187
|
+
previousReviewId: { type: String, default: null },
|
|
129
188
|
callLogs: { type: [callLogSchema], default: [] },
|
|
130
189
|
noteFacts: { type: [noteFactSchema], default: [] },
|
|
131
190
|
drafts: { type: [draftSchema], default: [] },
|
|
@@ -141,6 +200,8 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
141
200
|
}, { timestamps: true });
|
|
142
201
|
|
|
143
202
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
203
|
+
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
204
|
+
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
144
205
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
145
206
|
|
|
146
207
|
const getEscalationReview = () => {
|
|
@@ -158,6 +219,7 @@ module.exports = {
|
|
|
158
219
|
DOCTOR_DECISIONS,
|
|
159
220
|
HANDOFF_MODES,
|
|
160
221
|
INTERRUPTED_STATUSES,
|
|
222
|
+
RETURN_REASONS,
|
|
161
223
|
getEscalationReview,
|
|
162
224
|
escalationReviewSchema,
|
|
163
225
|
};
|
package/lib/routes/index.js
CHANGED
|
@@ -122,6 +122,7 @@ const escalationReviewRouteDefinitions = {
|
|
|
122
122
|
'POST /': 'openEscalationReviewController',
|
|
123
123
|
'GET /by-patient/:code': 'listEscalationReviewsController',
|
|
124
124
|
'GET /:id': 'getEscalationReviewController',
|
|
125
|
+
'GET /:id/timeline': 'getReviewTimelineController',
|
|
125
126
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
126
127
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
127
128
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
@@ -295,6 +296,7 @@ const builtInControllers = {
|
|
|
295
296
|
openEscalationReviewController: escalationReviewController.openEscalationReviewController,
|
|
296
297
|
listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
|
|
297
298
|
getEscalationReviewController: escalationReviewController.getEscalationReviewController,
|
|
299
|
+
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
298
300
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
299
301
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
300
302
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|