@peopl-health/nexus 5.75.6 → 6.0.0-dev.15740
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/flags/escalationFlags.js +5 -0
- package/lib/clinical/providers/BaseLLMProvider.js +5 -7
- package/lib/clinical/services/checkInDueService.js +1 -4
- package/lib/clinical/tools/reportMedicalEscalationTool.js +5 -1
- package/lib/clinical/tools/setContingencyPlanTool.js +1 -1
- package/lib/models/escalationReviewModel.js +1 -1
- package/lib/services/escalationReviewService.js +51 -11
- package/lib/services/reviewAlertSweepService.js +1 -1
- package/package.json +1 -1
|
@@ -14,11 +14,16 @@ function feverPatientTimerLive() {
|
|
|
14
14
|
return flagOn('FEVER_PATIENT_TIMER_LIVE');
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
function escalationApproverAlertLive() {
|
|
18
|
+
return flagOn('ESCALATION_APPROVER_ALERT_LIVE');
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
function escalationPatientTimerLive() {
|
|
18
22
|
return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
module.exports = {
|
|
26
|
+
escalationApproverAlertLive,
|
|
22
27
|
escalationAssessmentLive,
|
|
23
28
|
escalationPatientTimerLive,
|
|
24
29
|
escalationUpdateModeLive,
|
|
@@ -418,7 +418,7 @@ class BaseLLMProvider {
|
|
|
418
418
|
const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
|
|
419
419
|
const parts = [
|
|
420
420
|
'[CHECK-IN QUE VENCE (prioritario) para este turno]',
|
|
421
|
-
'Venció el plazo para retomar algo pendiente con
|
|
421
|
+
'Venció el plazo para retomar algo pendiente con ella. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a buscarla o si ya no hace falta.',
|
|
422
422
|
'', '## Qué quedó pendiente', ...pending,
|
|
423
423
|
];
|
|
424
424
|
if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
|
|
@@ -428,15 +428,13 @@ class BaseLLMProvider {
|
|
|
428
428
|
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
|
|
429
429
|
'- Este check-in es el seguimiento que está venciendo ahora, aunque lo veas programado unos minutos más tarde: ya no está pendiente y no se puede actualizar. Si decides esperar, programa uno nuevo.',
|
|
430
430
|
'- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
|
|
431
|
-
'- Si tu último mensaje ya le hace esta pregunta o la cubre, y
|
|
431
|
+
'- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
|
|
432
432
|
'- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
|
|
433
|
-
'- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
|
|
433
|
+
'- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ella ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
|
|
434
434
|
'- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
|
|
435
435
|
'- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
|
|
436
|
-
'- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
|
|
437
|
-
'Si escribes
|
|
438
|
-
'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
|
|
439
|
-
'Breve, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
|
|
436
|
+
'- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que ella contó o acordó.',
|
|
437
|
+
'Si escribes: breve, sin saludar ni escribir su nombre, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
|
|
440
438
|
);
|
|
441
439
|
return [{ role: 'developer', content: parts.join('\n') }];
|
|
442
440
|
}
|
|
@@ -43,12 +43,9 @@ async function recentCheckIns(code, now) {
|
|
|
43
43
|
|
|
44
44
|
const originFilter = (fromMe) => (fromMe ? { $in: OWN_ORIGINS } : { $ne: 'instruction' });
|
|
45
45
|
|
|
46
|
-
// Templates (cards, forms) and automations (the triage ack) would hide the question the agent last asked.
|
|
47
|
-
const OWN_CONVERSATION = { $or: [{ origin: 'assistant' }, { origin: 'whatsapp_platform', content_sid: null, triggeredBy: null }] };
|
|
48
|
-
|
|
49
46
|
async function lastMessage(code, now, fromMe) {
|
|
50
47
|
const rows = await getMessages(
|
|
51
|
-
{ numero: code, from_me: fromMe,
|
|
48
|
+
{ numero: code, from_me: fromMe, origin: originFilter(fromMe), createdAt: { $lt: now } },
|
|
52
49
|
{ sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
|
|
53
50
|
) || [];
|
|
54
51
|
const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
|
|
@@ -8,7 +8,7 @@ const { dispatcherService } = require('../services/dispatcherService');
|
|
|
8
8
|
const { armEscalationNet } = require('../services/contingencyDispatchService');
|
|
9
9
|
const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
10
10
|
const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
|
|
11
|
-
const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
|
|
11
|
+
const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
|
|
12
12
|
const { URGENCY_RANK } = require('../../models/escalationReviewModel');
|
|
13
13
|
const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
14
14
|
const { logger } = require('../../utils/logger');
|
|
@@ -401,6 +401,10 @@ async function handler(args, context = {}) {
|
|
|
401
401
|
onRecorded: (recordId) => { emergencyRecordId = recordId; },
|
|
402
402
|
});
|
|
403
403
|
if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
|
|
404
|
+
// A merge into an existing row never alerts, so only a row that had to be created falls back.
|
|
405
|
+
if (review && !queued && (raisesOpen || !anchor?.emergencyRecordId)) {
|
|
406
|
+
alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
|
|
407
|
+
}
|
|
404
408
|
if (urgencyLevel !== 'routine') {
|
|
405
409
|
try {
|
|
406
410
|
const net = queued ? await armEscalationNet({
|
|
@@ -58,7 +58,7 @@ const definition = {
|
|
|
58
58
|
},
|
|
59
59
|
patient_followup_reminder: {
|
|
60
60
|
type: 'object',
|
|
61
|
-
description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string,
|
|
61
|
+
description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, in the patient's voice and language, about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
|
|
62
62
|
},
|
|
63
63
|
},
|
|
64
64
|
required: ['action'],
|
|
@@ -44,7 +44,7 @@ const impressionUpdateSchema = new mongoose.Schema({
|
|
|
44
44
|
}, { _id: false });
|
|
45
45
|
|
|
46
46
|
const doctorAlertSchema = new mongoose.Schema({
|
|
47
|
-
kind: { type: String, enum: ['initial', 'realert', 'patient_prompt'], required: true },
|
|
47
|
+
kind: { type: String, enum: ['initial', 'realert', 'patient_prompt', 'fallback'], required: true },
|
|
48
48
|
urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
|
|
49
49
|
physicianEmail: { type: String, default: null },
|
|
50
50
|
transport: { type: String, default: null },
|
|
@@ -37,6 +37,7 @@ const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
|
|
|
37
37
|
const {
|
|
38
38
|
feverPatientTimerLive: feverTimerLive,
|
|
39
39
|
escalationPatientTimerLive: escalationTimerLive,
|
|
40
|
+
escalationApproverAlertLive,
|
|
40
41
|
} = require('../clinical/flags/escalationFlags');
|
|
41
42
|
const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
|
|
42
43
|
const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
|
|
@@ -77,7 +78,7 @@ const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
|
|
|
77
78
|
const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
|
|
78
79
|
const SETTLED_TRAJECTORIES = ['improving', 'stable'];
|
|
79
80
|
const ALERTED_URGENCIES = ['stat', 'asap'];
|
|
80
|
-
const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
|
|
81
|
+
const ALERT_MARKS = { stat: '🔴', asap: '🟠', urgent: '🟡' };
|
|
81
82
|
const DEFAULT_FEVER_TIMER_MINUTES = 15;
|
|
82
83
|
const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
|
|
83
84
|
const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
|
|
@@ -88,6 +89,7 @@ const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
|
|
|
88
89
|
const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
|
|
89
90
|
const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
|
|
90
91
|
const ALERT_OPERATOR = 'bot:escalationAlert';
|
|
92
|
+
const AIRTABLE_TRANSPORT = 'airtable';
|
|
91
93
|
const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
|
|
92
94
|
const SAME_URGENCY = 'The review is already at that urgency';
|
|
93
95
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
@@ -1029,13 +1031,14 @@ async function armPatientTimerOnJoin(review, alarm, now) {
|
|
|
1029
1031
|
}
|
|
1030
1032
|
}
|
|
1031
1033
|
|
|
1032
|
-
async function prepareDoctorAlert(review, urgencyLevel) {
|
|
1034
|
+
async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
|
|
1033
1035
|
const identity = await readDoctorIdentity(review);
|
|
1034
1036
|
if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
|
|
1035
|
-
const approver = await soleApprover();
|
|
1037
|
+
const approver = recipient ?? await soleApprover();
|
|
1036
1038
|
const link = conversationLink(review.patientCode);
|
|
1037
1039
|
if (!link) throw new Error('missing the interface URL for the chat link');
|
|
1038
|
-
const alarm = (review.alarms
|
|
1040
|
+
const alarm = (alarmId && review.alarms?.find((raised) => raised.alarmId === alarmId))
|
|
1041
|
+
?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
|
|
1039
1042
|
const symptom = inlineOf(alarm?.symptom);
|
|
1040
1043
|
const urgency = urgencyLevel.toUpperCase();
|
|
1041
1044
|
const patient = `${identity.patientName} (${identity.treatingDoctor})`;
|
|
@@ -1184,13 +1187,18 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
|
|
|
1184
1187
|
|
|
1185
1188
|
let delivery;
|
|
1186
1189
|
try {
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1190
|
+
if (escalationApproverAlertLive()) {
|
|
1191
|
+
const { approver, message } = await prepareDoctorAlert(review, urgencyLevel);
|
|
1192
|
+
const fresh = await loadReview(review._id);
|
|
1193
|
+
if (fresh.closedAt || !PRE_DECISION_STATUSES.includes(fresh.status)) {
|
|
1194
|
+
await release();
|
|
1195
|
+
return null;
|
|
1196
|
+
}
|
|
1197
|
+
delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
|
|
1198
|
+
} else {
|
|
1199
|
+
// Airtable's notifyEmergency alerts the team; the entry still starts this level's patient timer.
|
|
1200
|
+
delivery = { transport: AIRTABLE_TRANSPORT };
|
|
1192
1201
|
}
|
|
1193
|
-
delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
|
|
1194
1202
|
} catch (error) {
|
|
1195
1203
|
delivery = { error: redactedError(error) };
|
|
1196
1204
|
logger.error('[EscalationReview] The doctor alert was not sent', { escalationReviewId: String(review._id), kind, error: delivery.error });
|
|
@@ -1228,12 +1236,43 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
|
|
|
1228
1236
|
}
|
|
1229
1237
|
}
|
|
1230
1238
|
await audit(updated ?? review, ALERT_OPERATOR, null, {
|
|
1231
|
-
action: 'doctor_alerted', urgencyLevel, delivered: !sent.error,
|
|
1239
|
+
action: 'doctor_alerted', urgencyLevel, delivered: sent.transport === AIRTABLE_TRANSPORT ? null : !sent.error, transport: sent.transport,
|
|
1232
1240
|
});
|
|
1233
1241
|
if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
|
|
1234
1242
|
return updated;
|
|
1235
1243
|
}
|
|
1236
1244
|
|
|
1245
|
+
async function fallbackRecipient() {
|
|
1246
|
+
const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
|
|
1247
|
+
return phone ? { name: null, email: null, phone } : soleApprover();
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// Airtable alerts the team only once its emergencies row exists; when that write failed, nexus alerts instead.
|
|
1251
|
+
async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
|
|
1252
|
+
if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
|
|
1253
|
+
let review;
|
|
1254
|
+
let delivery;
|
|
1255
|
+
try {
|
|
1256
|
+
review = await loadReview(reviewIdOf(reviewId));
|
|
1257
|
+
const recipient = await fallbackRecipient();
|
|
1258
|
+
const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
|
|
1259
|
+
delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
delivery = { error: redactedError(error) };
|
|
1262
|
+
logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
|
|
1263
|
+
}
|
|
1264
|
+
if (!review) return null;
|
|
1265
|
+
const sent = { kind: 'fallback', urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
|
|
1266
|
+
try {
|
|
1267
|
+
const updated = await getEscalationReview().findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
|
|
1268
|
+
await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'emergency_row_fallback_alerted', urgencyLevel, delivered: !sent.error, transport: sent.transport });
|
|
1269
|
+
return updated;
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
logger.error('[EscalationReview] The fallback alert was not recorded', { escalationReviewId: String(reviewId), error: redactedError(error) });
|
|
1272
|
+
return null;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1237
1276
|
async function reopenFromFollowUp(review, reason) {
|
|
1238
1277
|
const reopened = await getEscalationReview()
|
|
1239
1278
|
.findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
|
|
@@ -2062,6 +2101,7 @@ module.exports = {
|
|
|
2062
2101
|
_resetEscalationReviewIndexes,
|
|
2063
2102
|
addCallLog,
|
|
2064
2103
|
addDraft,
|
|
2104
|
+
alertWithoutEmergencyRow,
|
|
2065
2105
|
attachEmergencyRow,
|
|
2066
2106
|
cancelEscalationReview,
|
|
2067
2107
|
closeEscalationReview,
|
|
@@ -19,7 +19,7 @@ const dueQuery = (now) => ({
|
|
|
19
19
|
{
|
|
20
20
|
doctorAlertDueAt: null,
|
|
21
21
|
status: { $in: PRE_DECISION_STATUSES },
|
|
22
|
-
|
|
22
|
+
doctorAlerts: { $not: { $elemMatch: { kind: 'initial' } } },
|
|
23
23
|
alarms: { $elemMatch: { urgencyLevel: { $in: ALERTED_URGENCIES }, raisedAt: { $gte: new Date(now.getTime() - SELF_HEAL_WINDOW_MS) } } },
|
|
24
24
|
},
|
|
25
25
|
],
|