@peopl-health/nexus 5.61.0-dev.11231 → 5.61.0-dev.11232
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/clinical/AssistantProcessor.js +16 -0
- package/lib/clinical/config/subAgentsConfig.js +1 -7
- package/lib/clinical/helpers/reviewUpdateHelper.js +74 -0
- package/lib/clinical/models/supportLightModel.js +1 -19
- 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 +5 -1
- package/lib/controllers/conversationController.js +2 -2
- package/lib/controllers/escalationReviewController.js +26 -0
- package/lib/controllers/messageController.js +21 -1
- package/lib/index.d.ts +14 -33
- package/lib/index.js +20 -2
- package/lib/models/escalationReviewModel.js +65 -2
- package/lib/routes/index.js +4 -0
- package/lib/services/conversationService.js +40 -13
- package/lib/services/escalationReviewService.js +633 -45
- package/lib/services/patientTaskService.js +1 -0
- package/lib/services/reviewAlertSweepService.js +90 -0
- package/lib/services/reviewBoardService.js +78 -0
- package/lib/services/reviewDraftSweepService.js +80 -0
- package/package.json +1 -1
- package/lib/clinical/services/supportLightEvaluationService.js +0 -159
|
@@ -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 {
|
|
@@ -17,7 +17,6 @@ const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
|
|
|
17
17
|
const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
|
|
18
18
|
const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
|
|
19
19
|
const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
|
|
20
|
-
const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
|
|
21
20
|
|
|
22
21
|
const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
|
|
23
22
|
|
|
@@ -67,11 +66,7 @@ async function load() {
|
|
|
67
66
|
if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
|
|
68
67
|
const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
|
|
69
68
|
|
|
70
|
-
const
|
|
71
|
-
if (byKey.SUPPORT_LIGHT && !isPlainObject(parsedSupportLight)) throw new Error('subAgents config SUPPORT_LIGHT is not a JSON object');
|
|
72
|
-
const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(parsedSupportLight || {}) };
|
|
73
|
-
|
|
74
|
-
const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
|
|
69
|
+
const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts };
|
|
75
70
|
cache.set(CACHE_KEY, config);
|
|
76
71
|
return config;
|
|
77
72
|
}
|
|
@@ -90,5 +85,4 @@ module.exports = {
|
|
|
90
85
|
getEscalationDraft: () => get('ESCALATION_DRAFT'),
|
|
91
86
|
getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
|
|
92
87
|
getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
|
|
93
|
-
getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
|
|
94
88
|
};
|
|
@@ -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 };
|
|
@@ -56,13 +56,6 @@ const supportLightEventSchema = new mongoose.Schema({
|
|
|
56
56
|
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
57
57
|
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
58
58
|
|
|
59
|
-
const supportLightSweepSchema = new mongoose.Schema({
|
|
60
|
-
patientId: { type: String, required: true, unique: true },
|
|
61
|
-
lastAttemptAt: { type: Date, required: true },
|
|
62
|
-
lastEvaluatedAt: { type: Date, default: null },
|
|
63
|
-
lastOutcome: { type: String, required: true },
|
|
64
|
-
}, { timestamps: true });
|
|
65
|
-
|
|
66
59
|
function getSupportLightModel() {
|
|
67
60
|
const conn = clinicalConnection();
|
|
68
61
|
return conn.models.SupportLight || conn.model('SupportLight', supportLightSchema, 'supportLights');
|
|
@@ -74,17 +67,6 @@ function getSupportLightEventModel() {
|
|
|
74
67
|
|| conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
|
|
75
68
|
}
|
|
76
69
|
|
|
77
|
-
function getSupportLightSweepModel() {
|
|
78
|
-
const conn = clinicalConnection();
|
|
79
|
-
return conn.models.SupportLightSweep
|
|
80
|
-
|| conn.model('SupportLightSweep', supportLightSweepSchema, 'supportLightSweeps');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
70
|
module.exports = {
|
|
84
|
-
getSupportLightModel,
|
|
85
|
-
getSupportLightEventModel,
|
|
86
|
-
getSupportLightSweepModel,
|
|
87
|
-
supportLightSchema,
|
|
88
|
-
supportLightEventSchema,
|
|
89
|
-
supportLightSweepSchema,
|
|
71
|
+
getSupportLightModel, getSupportLightEventModel, supportLightSchema, supportLightEventSchema,
|
|
90
72
|
};
|
|
@@ -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,8 @@ 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');
|
|
10
|
+
const { stopReviewAlertSweep } = require('../services/reviewAlertSweepService');
|
|
9
11
|
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
10
12
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
11
13
|
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
@@ -20,7 +22,9 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
|
20
22
|
const SWEEP_STOP_MS = 2000;
|
|
21
23
|
|
|
22
24
|
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
23
|
-
const stopped = Promise.allSettled([
|
|
25
|
+
const stopped = Promise.allSettled([
|
|
26
|
+
stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(), stopReviewAlertSweep(),
|
|
27
|
+
]);
|
|
24
28
|
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
25
29
|
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
26
30
|
}
|
|
@@ -34,7 +34,7 @@ const getConversationController = async (req, res) => {
|
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const { threads, total, airtableNameMap, openTaskMap } = await fetchConversationData(filter, skip, limit);
|
|
37
|
+
const { threads, total, airtableNameMap, openTaskMap, reviewMap } = await fetchConversationData(filter, skip, limit);
|
|
38
38
|
|
|
39
39
|
if (!threads?.length) {
|
|
40
40
|
return res.status(200).json({
|
|
@@ -44,7 +44,7 @@ const getConversationController = async (req, res) => {
|
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
const processedConversations = await processConversations(threads, airtableNameMap, openTaskMap);
|
|
47
|
+
const processedConversations = await processConversations(threads, airtableNameMap, openTaskMap, reviewMap);
|
|
48
48
|
const totalPages = Math.ceil(total / limit);
|
|
49
49
|
|
|
50
50
|
res.status(200).json({
|
|
@@ -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,
|
|
@@ -18,6 +19,7 @@ const {
|
|
|
18
19
|
confirmNoteFacts,
|
|
19
20
|
syncEscalationReviewCase,
|
|
20
21
|
} = require('../services/escalationReviewService');
|
|
22
|
+
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
21
23
|
|
|
22
24
|
const respondWithError = (res, error, action, context) => {
|
|
23
25
|
logger.error(`Error ${action}:`, {
|
|
@@ -53,6 +55,15 @@ const getEscalationReviewController = async (req, res) => {
|
|
|
53
55
|
}
|
|
54
56
|
};
|
|
55
57
|
|
|
58
|
+
const getReviewTimelineController = async (req, res) => {
|
|
59
|
+
try {
|
|
60
|
+
const timeline = await getReviewTimeline({ id: req.params.id });
|
|
61
|
+
res.status(200).json({ success: true, timeline });
|
|
62
|
+
} catch (error) {
|
|
63
|
+
respondWithError(res, error, 'reading the escalation review timeline', { reviewId: req.params?.id });
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
56
67
|
const listEscalationReviewsController = async (req, res) => {
|
|
57
68
|
try {
|
|
58
69
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
@@ -62,6 +73,15 @@ const listEscalationReviewsController = async (req, res) => {
|
|
|
62
73
|
}
|
|
63
74
|
};
|
|
64
75
|
|
|
76
|
+
const listReviewBoardController = async (req, res) => {
|
|
77
|
+
try {
|
|
78
|
+
const rows = await listReviewBoard({ bucket: req.query.bucket });
|
|
79
|
+
res.status(200).json({ success: true, rows });
|
|
80
|
+
} catch (error) {
|
|
81
|
+
respondWithError(res, error, 'listing the review board', { bucket: String(req.query?.bucket || '') });
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
65
85
|
const setEscalationReviewCasesController = async (req, res) => {
|
|
66
86
|
try {
|
|
67
87
|
const { patientCaseRecordIds, triggeredBy } = req.body || {};
|
|
@@ -143,6 +163,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
143
163
|
comment = null,
|
|
144
164
|
doctorName = null,
|
|
145
165
|
doctorReply = null,
|
|
166
|
+
reason = null,
|
|
167
|
+
draftNumber = null,
|
|
146
168
|
triggeredBy,
|
|
147
169
|
} = req.body || {};
|
|
148
170
|
const review = await recordDoctorDecision({
|
|
@@ -153,6 +175,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
153
175
|
comment,
|
|
154
176
|
doctorName,
|
|
155
177
|
doctorReply,
|
|
178
|
+
reason,
|
|
179
|
+
draftNumber,
|
|
156
180
|
recordedBy: triggeredBy,
|
|
157
181
|
requestId: req.requestId,
|
|
158
182
|
});
|
|
@@ -224,8 +248,10 @@ module.exports = {
|
|
|
224
248
|
cancelEscalationReviewController,
|
|
225
249
|
closeEscalationReviewController,
|
|
226
250
|
getEscalationReviewController,
|
|
251
|
+
getReviewTimelineController,
|
|
227
252
|
handOffEscalationReviewController,
|
|
228
253
|
listEscalationReviewsController,
|
|
254
|
+
listReviewBoardController,
|
|
229
255
|
openEscalationReviewController,
|
|
230
256
|
recordEscalationReviewDecisionController,
|
|
231
257
|
sendEscalationReviewIndicationsController,
|
|
@@ -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
|
@@ -355,6 +355,8 @@ declare module '@peopl-health/nexus' {
|
|
|
355
355
|
ner?: NerOptions;
|
|
356
356
|
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
357
357
|
inboundRecovery?: InboundRecoveryOptions;
|
|
358
|
+
reviewDrafts?: ReviewDraftsOptions;
|
|
359
|
+
reviewAlerts?: ReviewAlertsOptions;
|
|
358
360
|
}
|
|
359
361
|
|
|
360
362
|
export interface RecommendationRecoveryOptions {
|
|
@@ -362,6 +364,18 @@ declare module '@peopl-health/nexus' {
|
|
|
362
364
|
intervalMs?: number;
|
|
363
365
|
}
|
|
364
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
|
+
|
|
365
379
|
export interface InboundRecoveryOptions {
|
|
366
380
|
enabled: boolean;
|
|
367
381
|
intervalMs?: number;
|
|
@@ -1015,39 +1029,6 @@ declare module '@peopl-health/nexus' {
|
|
|
1015
1029
|
supportWeek(date: Date | string): string | null;
|
|
1016
1030
|
};
|
|
1017
1031
|
|
|
1018
|
-
export interface SupportLightSweepChange {
|
|
1019
|
-
patientId: string;
|
|
1020
|
-
service: SupportService;
|
|
1021
|
-
outcome: SupportLightOutcome;
|
|
1022
|
-
color: SupportLightColor;
|
|
1023
|
-
revision: number | null;
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
export const supportLightEvaluationService: {
|
|
1027
|
-
evaluatePatientSupport(request: {
|
|
1028
|
-
patientId: string;
|
|
1029
|
-
now?: Date;
|
|
1030
|
-
windowDays?: number;
|
|
1031
|
-
}, options?: { provider?: unknown; getConfig?: unknown; readMessages?: unknown; applyLight?: unknown }): Promise<{
|
|
1032
|
-
outcome: 'evaluated' | 'partial' | 'not_configured' | 'no_messages' | 'incomplete' | 'unparseable';
|
|
1033
|
-
changes?: Omit<SupportLightSweepChange, 'patientId'>[];
|
|
1034
|
-
}>;
|
|
1035
|
-
runSupportLightSweep(request?: {
|
|
1036
|
-
now?: Date;
|
|
1037
|
-
patientIds?: string[] | null;
|
|
1038
|
-
scope?: string[] | null;
|
|
1039
|
-
cadenceHours?: number;
|
|
1040
|
-
windowDays?: number;
|
|
1041
|
-
limit?: number;
|
|
1042
|
-
}, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
|
|
1043
|
-
outcome: 'completed' | 'not_configured';
|
|
1044
|
-
evaluated: number;
|
|
1045
|
-
skipped: number;
|
|
1046
|
-
failed: number;
|
|
1047
|
-
changes: SupportLightSweepChange[];
|
|
1048
|
-
}>;
|
|
1049
|
-
};
|
|
1050
|
-
|
|
1051
1032
|
// BatchingManager — per-chatId concurrency control
|
|
1052
1033
|
export interface BatchingConfig {
|
|
1053
1034
|
enabled?: boolean;
|
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');
|
|
@@ -50,7 +52,6 @@ const { registerDashboardProvider } = require('./services/dashboard-provider-reg
|
|
|
50
52
|
const supportActionService = require('./clinical/services/supportActionService');
|
|
51
53
|
const supportLightService = require('./clinical/services/supportLightService');
|
|
52
54
|
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
53
|
-
const supportLightEvaluationService = require('./clinical/services/supportLightEvaluationService');
|
|
54
55
|
const {
|
|
55
56
|
NutritionSafetyDecision,
|
|
56
57
|
FINDING_CODES,
|
|
@@ -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({
|
|
@@ -360,7 +379,6 @@ module.exports = {
|
|
|
360
379
|
supportActionService,
|
|
361
380
|
supportLightService,
|
|
362
381
|
supportInvitability,
|
|
363
|
-
supportLightEvaluationService,
|
|
364
382
|
NutritionSafetyDecision,
|
|
365
383
|
FINDING_CODES,
|
|
366
384
|
FINDING_VALUES,
|
|
@@ -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,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
141
200
|
}, { timestamps: true });
|
|
142
201
|
|
|
143
202
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
203
|
+
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
204
|
+
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
205
|
+
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
144
206
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
145
207
|
|
|
146
208
|
const getEscalationReview = () => {
|
|
@@ -158,6 +220,7 @@ module.exports = {
|
|
|
158
220
|
DOCTOR_DECISIONS,
|
|
159
221
|
HANDOFF_MODES,
|
|
160
222
|
INTERRUPTED_STATUSES,
|
|
223
|
+
RETURN_REASONS,
|
|
161
224
|
getEscalationReview,
|
|
162
225
|
escalationReviewSchema,
|
|
163
226
|
};
|