@peopl-health/nexus 6.0.0-dev.16228 → 6.0.0-dev.16333
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 +1 -0
- package/lib/clinical/providers/BaseLLMProvider.js +13 -7
- package/lib/clinical/services/clinicalAirtableService.js +15 -0
- package/lib/clinical/services/contingencyDispatchService.js +40 -15
- package/lib/clinical/services/outreachCarrierService.js +2 -1
- package/lib/clinical/services/outreachSweepService.js +1 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +5 -2
- package/lib/clinical/tools/schedulePatientReminderTool.js +4 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +3 -0
- package/lib/core/NexusMessaging.js +2 -0
- package/lib/index.d.ts +1 -1
- package/lib/services/escalationReviewService.js +2 -1
- package/lib/services/reviewDeadlineService.js +12 -6
- package/lib/services/teamAlertService.js +19 -15
- package/lib/services/untakenAlertService.js +33 -12
- package/package.json +1 -1
|
@@ -108,6 +108,7 @@ class AssistantProcessor {
|
|
|
108
108
|
if (ctx) {
|
|
109
109
|
ctx.outreachReminderType = runOptions.outreachCarrier?.reminderType || null;
|
|
110
110
|
ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
|
|
111
|
+
ctx.outreachAllowsFollowUp = runOptions.outreachAllowsFollowUp !== false;
|
|
111
112
|
ctx.checkInOtherPlans = runOptions.outreachBrief?.checkIn?.otherPlans ?? null;
|
|
112
113
|
}
|
|
113
114
|
if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
|
|
@@ -164,14 +164,15 @@ class BaseLLMProvider {
|
|
|
164
164
|
const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
|
|
165
165
|
const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
|
|
166
166
|
const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
|
|
167
|
+
const allowFollowUp = assistant?.toolRuntimeContext?.outreachAllowsFollowUp !== false;
|
|
167
168
|
const auditedPrompt = [
|
|
168
169
|
devContent,
|
|
169
170
|
catalogBlock,
|
|
170
171
|
additionalInstructions ? this._operatorInstructionTurn(additionalInstructions, modelConfig).content : '',
|
|
171
|
-
isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
|
|
172
|
+
isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds, allowFollowUp })[0]?.content || '') : '',
|
|
172
173
|
ruleBlock,
|
|
173
174
|
].filter(Boolean).join('\n\n');
|
|
174
|
-
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
|
|
175
|
+
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null, allowFollowUp });
|
|
175
176
|
|
|
176
177
|
if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
|
|
177
178
|
trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
|
|
@@ -306,7 +307,7 @@ class BaseLLMProvider {
|
|
|
306
307
|
return { role: 'developer', content: `[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}` };
|
|
307
308
|
}
|
|
308
309
|
|
|
309
|
-
_buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null }) {
|
|
310
|
+
_buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null, allowFollowUp = true }) {
|
|
310
311
|
let messages = this._convertItemsToApiFormat(context || []);
|
|
311
312
|
if (Array.isArray(prePromptResult?.additionalMessages) && prePromptResult.additionalMessages.length > 0) {
|
|
312
313
|
messages = [...messages, ...this._convertItemsToApiFormat(prePromptResult.additionalMessages)];
|
|
@@ -325,7 +326,7 @@ class BaseLLMProvider {
|
|
|
325
326
|
...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
|
|
326
327
|
...this._buildClockMessage(promptVariables, interpolatedVariables),
|
|
327
328
|
...messages,
|
|
328
|
-
...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
|
|
329
|
+
...this._buildOutreachBriefMessage({ outreachBrief, toolIds, allowFollowUp }),
|
|
329
330
|
...this._buildContingencyRuleMessage({ toolIds, promptVariables }),
|
|
330
331
|
]);
|
|
331
332
|
}
|
|
@@ -347,7 +348,7 @@ class BaseLLMProvider {
|
|
|
347
348
|
|
|
348
349
|
// Rides as a turn-scoped developer block, never as a stored message: a proactive brief is true for
|
|
349
350
|
// this morning only, and anything persisted into history would still read as a standing rule weeks later.
|
|
350
|
-
_buildOutreachBriefMessage({ outreachBrief = null, toolIds = [] }) {
|
|
351
|
+
_buildOutreachBriefMessage({ outreachBrief = null, toolIds = [], allowFollowUp = true }) {
|
|
351
352
|
if (!outreachBrief || typeof outreachBrief !== 'object') return [];
|
|
352
353
|
if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
|
|
353
354
|
|
|
@@ -381,8 +382,13 @@ class BaseLLMProvider {
|
|
|
381
382
|
if (since.length) parts.push('', '## Qué ha pasado desde entonces', ...since);
|
|
382
383
|
parts.push(
|
|
383
384
|
'',
|
|
384
|
-
|
|
385
|
-
|
|
385
|
+
...(allowFollowUp ? [
|
|
386
|
+
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
|
|
387
|
+
'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
|
|
388
|
+
] : [
|
|
389
|
+
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora o sostener.`,
|
|
390
|
+
'En este turno no programes seguimientos ni recordatorios, aunque otras reglas lo pidan: si te responde, la conversación decide lo que sigue. Si sostienes, deja next_check_at en null.',
|
|
391
|
+
]),
|
|
386
392
|
'',
|
|
387
393
|
'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
|
|
388
394
|
'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
|
|
@@ -212,6 +212,20 @@ async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused
|
|
|
212
212
|
return written;
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
const GROUP_MESSAGE_ID_FIELD = 'group_message_id';
|
|
216
|
+
|
|
217
|
+
// The id of the group message notifyEmergency posted for this row, so follow-ups reply to it; null when unknown.
|
|
218
|
+
async function readGroupMessageId(recordId, code) {
|
|
219
|
+
if (!/^rec[A-Za-z0-9]+$/.test(String(recordId ?? ''))) return null;
|
|
220
|
+
try {
|
|
221
|
+
const rows = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null, [GROUP_MESSAGE_ID_FIELD]);
|
|
222
|
+
return String(rows?.[0]?.[GROUP_MESSAGE_ID_FIELD] ?? '').trim() || null;
|
|
223
|
+
} catch (error) {
|
|
224
|
+
logger.warn('[clinicalAirtableService] The group message id could not be read; the follow-up goes out unthreaded', { code, recordId, error: error.message });
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
215
229
|
async function readEmergencyRow(recordId, code) {
|
|
216
230
|
try {
|
|
217
231
|
const open = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null);
|
|
@@ -716,6 +730,7 @@ module.exports = {
|
|
|
716
730
|
writeUnresolvedRequest,
|
|
717
731
|
recordPausedThreadMessage,
|
|
718
732
|
recordEmergency,
|
|
733
|
+
readGroupMessageId,
|
|
719
734
|
recordClinicalIntake,
|
|
720
735
|
recordReminder,
|
|
721
736
|
hasPendingContingencyRow,
|
|
@@ -11,12 +11,16 @@ const { isShadowRun } = require('../helpers/shadowHelper');
|
|
|
11
11
|
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
|
|
12
12
|
// Net check-ins start an hour later: 08:00–09:00 is when the daily symptom forms reach patients.
|
|
13
13
|
const CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, startHour: 9 };
|
|
14
|
+
// asap check-ins only hold 23:00–08:00: the case is still hot and someone may be awake.
|
|
15
|
+
const ASAP_CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, endHour: 23 };
|
|
14
16
|
const MS_PER_MINUTE = 60 * 1000;
|
|
15
17
|
const MS_PER_HOUR = 60 * MS_PER_MINUTE;
|
|
16
18
|
const EXPIRY_WINDOW_MULTIPLIER = 6;
|
|
17
19
|
const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
|
|
18
20
|
const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
|
|
19
|
-
const ESCALATION_SILENCE_MINUTES = { stat:
|
|
21
|
+
const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
|
|
22
|
+
// Nets armed before the change keep their level until they expire (stat 120, asap 180).
|
|
23
|
+
const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
|
|
20
24
|
const OPEN_CEILING_SILENCE_MINUTES = 720;
|
|
21
25
|
const OPEN_CEILING_ORIGIN = 'open_ceiling';
|
|
22
26
|
const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
|
|
@@ -33,14 +37,18 @@ function rawDueAt(createdAt, firesAfterSilenceMinutes) {
|
|
|
33
37
|
return new Date(new Date(createdAt).getTime() + (firesAfterSilenceMinutes * MS_PER_MINUTE));
|
|
34
38
|
}
|
|
35
39
|
|
|
36
|
-
function
|
|
40
|
+
function checkInWindowFor(urgencyLevel) {
|
|
41
|
+
return urgencyLevel === 'asap' ? ASAP_CHECK_IN_WINDOW : CHECK_IN_WINDOW;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function dueAt(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
|
|
37
45
|
const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
|
|
38
|
-
return (clampToHourWindow(raw,
|
|
46
|
+
return (clampToHourWindow(raw, window) || raw).toISOString();
|
|
39
47
|
}
|
|
40
48
|
|
|
41
|
-
function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes) {
|
|
49
|
+
function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
|
|
42
50
|
const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
|
|
43
|
-
const clamped = clampToHourWindow(raw,
|
|
51
|
+
const clamped = clampToHourWindow(raw, window);
|
|
44
52
|
if (!clamped) return 0;
|
|
45
53
|
return Math.round((clamped.getTime() - raw.getTime()) / MS_PER_MINUTE);
|
|
46
54
|
}
|
|
@@ -96,7 +104,7 @@ function computeExpiresAt(createdAt, firesAfterSilenceMinutes) {
|
|
|
96
104
|
return new Date(new Date(createdAt).getTime() + clamped).toISOString();
|
|
97
105
|
}
|
|
98
106
|
|
|
99
|
-
function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null }) {
|
|
107
|
+
function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null, checkInWindow = CHECK_IN_WINDOW }) {
|
|
100
108
|
const existing = Array.isArray(trace?.signals?.contingencyPlans) ? trace.signals.contingencyPlans : [];
|
|
101
109
|
trace?.setSignals?.({
|
|
102
110
|
contingencyPlans: [...existing, {
|
|
@@ -107,7 +115,7 @@ function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId,
|
|
|
107
115
|
awaitingCharacterization,
|
|
108
116
|
resolvesOn,
|
|
109
117
|
patientFiresAfterSilenceMinutes: firesAfterSilenceMinutes,
|
|
110
|
-
quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes),
|
|
118
|
+
quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, checkInWindow),
|
|
111
119
|
windowReasoning,
|
|
112
120
|
...(extra || {}),
|
|
113
121
|
}],
|
|
@@ -241,7 +249,7 @@ function isCeilingNet(net) {
|
|
|
241
249
|
return plan?.armedBy === ARMED_BY.OPEN_CEILING || plan?.creationReasoning === OPEN_CEILING_ORIGIN;
|
|
242
250
|
}
|
|
243
251
|
|
|
244
|
-
async function
|
|
252
|
+
async function retireNets({ patientCode, trace, isLive, select, context }) {
|
|
245
253
|
if (isShadowRun()) return [];
|
|
246
254
|
if (isLive && !isLive()) return [];
|
|
247
255
|
const targets = select(await readActiveNets(patientCode));
|
|
@@ -259,7 +267,7 @@ async function retireCeilingNets({ patientCode, trace, isLive, select, context }
|
|
|
259
267
|
});
|
|
260
268
|
retired.push(net.carePlan.planId);
|
|
261
269
|
} catch (error) {
|
|
262
|
-
logger.warn(`[contingency]
|
|
270
|
+
logger.warn(`[contingency] net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
|
|
263
271
|
}
|
|
264
272
|
}
|
|
265
273
|
return retired;
|
|
@@ -270,23 +278,39 @@ function orphanCeilingNets(active) {
|
|
|
270
278
|
return ceiling.length === active.length ? [] : ceiling;
|
|
271
279
|
}
|
|
272
280
|
|
|
273
|
-
const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) =>
|
|
281
|
+
const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireNets({
|
|
274
282
|
patientCode, trace, isLive, select: orphanCeilingNets, context: 'while sweeping an orphan',
|
|
275
283
|
});
|
|
276
284
|
|
|
277
|
-
const supersedeForEscalation = ({ patientCode, trace, isLive }) =>
|
|
285
|
+
const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireNets({
|
|
278
286
|
patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
|
|
279
287
|
});
|
|
280
288
|
|
|
289
|
+
// A patient sent to urgencias gets no later check-in, neither the ceiling one nor one left by a lower escalation.
|
|
290
|
+
const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
|
|
291
|
+
patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
|
|
292
|
+
});
|
|
293
|
+
|
|
281
294
|
function escalationUrgencyOf(net) {
|
|
282
295
|
if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
|
|
283
296
|
const silence = net?.patientReminder?.firesAfterSilenceMinutes;
|
|
284
|
-
|
|
297
|
+
const levels = Object.keys(ESCALATION_SILENCE_MINUTES);
|
|
298
|
+
return levels.find((level) => ESCALATION_SILENCE_MINUTES[level] === silence)
|
|
299
|
+
|| levels.find((level) => LEGACY_ESCALATION_SILENCE_MINUTES[level] === silence)
|
|
300
|
+
|| null;
|
|
285
301
|
}
|
|
286
302
|
|
|
287
303
|
async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
|
|
304
|
+
if (!Object.hasOwn(ESCALATION_SILENCE_MINUTES, urgencyLevel)) return { armed: false, reason: 'urgency_not_covered' };
|
|
288
305
|
const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
|
|
289
|
-
|
|
306
|
+
// stat gets no check-in of its own; it only clears the check-ins already armed.
|
|
307
|
+
if (!silence) {
|
|
308
|
+
const superseded = await supersedeForStat({ patientCode, trace, isLive }).catch((error) => {
|
|
309
|
+
logger.warn('[contingency] check-ins not retired for a stat escalation', { patientCode, error: error?.message });
|
|
310
|
+
return [];
|
|
311
|
+
});
|
|
312
|
+
return { armed: false, reason: 'level_without_check_in', superseded };
|
|
313
|
+
}
|
|
290
314
|
|
|
291
315
|
await sweepOrphanCeilingNets({ patientCode, trace, isLive });
|
|
292
316
|
const target = await escalationNetTarget(patientCode, { stepsAside: isCeilingNet, touched: casesTouchedThisTurn(trace) });
|
|
@@ -325,6 +349,7 @@ async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedC
|
|
|
325
349
|
firesAfterSilenceMinutes: silence,
|
|
326
350
|
windowReasoning: contingency.patientReminder.windowReasoning,
|
|
327
351
|
extra: { armedBy: 'escalation', escalationUrgency: urgencyLevel },
|
|
352
|
+
checkInWindow: checkInWindowFor(urgencyLevel),
|
|
328
353
|
});
|
|
329
354
|
|
|
330
355
|
const out = await commitMachineNet({ patientCode, contingency, caseId: null, trace, isLive, planId, stepsAside: isCeilingNet });
|
|
@@ -343,7 +368,7 @@ async function armContingency({ contingency, patientCode, trace = null, isLive =
|
|
|
343
368
|
isLive,
|
|
344
369
|
actionType,
|
|
345
370
|
reminderId: `${carePlan.planId}-patient`,
|
|
346
|
-
reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes),
|
|
371
|
+
reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes, checkInWindowFor(escalationUrgencyOf(contingency))),
|
|
347
372
|
reminderType: 'contingency',
|
|
348
373
|
description: patientReminder.message,
|
|
349
374
|
firesAfterSilenceMinutes: patientReminder.firesAfterSilenceMinutes,
|
|
@@ -468,4 +493,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
|
|
|
468
493
|
return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
|
|
469
494
|
}
|
|
470
495
|
|
|
471
|
-
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
496
|
+
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW, ASAP_CHECK_IN_WINDOW };
|
|
@@ -3,6 +3,7 @@ const { escapeRegExp } = require('../../utils/textMatchUtils');
|
|
|
3
3
|
|
|
4
4
|
const MAX_CARRIER_TEXT_LENGTH = 600;
|
|
5
5
|
const MAX_HYDRATED_BODY_LENGTH = 1024;
|
|
6
|
+
const GRAPHEME_SEGMENTER = new Intl.Segmenter('es', { granularity: 'grapheme' });
|
|
6
7
|
const FOLLOW_UP_TYPES = new Set(['seguimiento']);
|
|
7
8
|
const CONTINGENCY_TYPES = new Set(['contingencia']);
|
|
8
9
|
const REMINDER_TYPES = new Set(['cita', 'examen', 'medicamento', 'otros']);
|
|
@@ -50,7 +51,7 @@ function validateAgentText(messageText, firstName) {
|
|
|
50
51
|
throw new Error('OUTREACH_CARRIER_TEXT_REPEATS_NAME');
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
const emojiCount = [...text.
|
|
54
|
+
const emojiCount = [...GRAPHEME_SEGMENTER.segment(text)].filter(({ segment }) => /\p{Extended_Pictographic}/u.test(segment)).length;
|
|
54
55
|
if (emojiCount > 1) throw new Error('OUTREACH_CARRIER_TEXT_TOO_MANY_EMOJI');
|
|
55
56
|
return { text, name };
|
|
56
57
|
}
|
|
@@ -583,6 +583,7 @@ async function runOutreachSweep({
|
|
|
583
583
|
dryRun,
|
|
584
584
|
reminderType: 'seguimiento',
|
|
585
585
|
reminderPrefix: mode === 'monday_triage_recovery' ? 'recovery' : null,
|
|
586
|
+
allowFollowUp: mode === 'monday_triage_recovery',
|
|
586
587
|
triggeredBy: `seguimiento:${candidate.recordId}`,
|
|
587
588
|
});
|
|
588
589
|
counts.run++;
|
|
@@ -7,7 +7,7 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
|
|
|
7
7
|
const { dispatcherService } = require('../services/dispatcherService');
|
|
8
8
|
const { armEscalationNet } = require('../services/contingencyDispatchService');
|
|
9
9
|
const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
10
|
-
const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
|
|
10
|
+
const { escalationAssessmentLive, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
|
|
11
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');
|
|
@@ -21,7 +21,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
|
|
|
21
21
|
|
|
22
22
|
const definition = {
|
|
23
23
|
'name': 'reportMedicalEscalation',
|
|
24
|
-
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
24
|
+
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
25
25
|
'strict': true,
|
|
26
26
|
'parameters': {
|
|
27
27
|
'type': 'object',
|
|
@@ -268,6 +268,9 @@ function followUpNote(armed, reason) {
|
|
|
268
268
|
if (armed === null) {
|
|
269
269
|
return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient.';
|
|
270
270
|
}
|
|
271
|
+
if (reason === 'level_without_check_in' && escalationPatientTimerLive()) {
|
|
272
|
+
return 'This level gets no automatic check-in by design: if nobody takes the case, the patient timer sends the numbers to call. Do not add a timed fallback; keep to the instruction for this level.';
|
|
273
|
+
}
|
|
271
274
|
if (reason === 'active_net_exists') {
|
|
272
275
|
return 'No check-in was armed for THIS escalation because one is already open for this patient — it may be tracking a different concern, so do not assume the patient will be asked about this one.';
|
|
273
276
|
}
|
|
@@ -59,6 +59,7 @@ const MAX_PAUSE_DAYS = 30;
|
|
|
59
59
|
const ROUTINE_OUTREACH_START_HOUR = 11;
|
|
60
60
|
const ROUTINE_OUTREACH_END_HOUR = 21;
|
|
61
61
|
const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
|
|
62
|
+
const NO_FOLLOW_UP_ERROR = 'follow_up_not_allowed — this proactive contact cannot schedule a reminder: if she replies, the conversation decides what comes next. Close with write, or hold with next_check_at null.';
|
|
62
63
|
|
|
63
64
|
const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?$/;
|
|
64
65
|
const FIRE_AT_FORMATS = ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm'];
|
|
@@ -88,6 +89,9 @@ async function handler(args = {}, context = {}) {
|
|
|
88
89
|
const requestedAction = (args?.reminder_action_type || '').toLowerCase();
|
|
89
90
|
if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
|
|
90
91
|
if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
|
|
92
|
+
if (runtime.outreachAllowsFollowUp === false) {
|
|
93
|
+
return JSON.stringify({ success: false, error: NO_FOLLOW_UP_ERROR, data: {} });
|
|
94
|
+
}
|
|
91
95
|
|
|
92
96
|
const reminderDate = (args?.reminder_date || '').trim();
|
|
93
97
|
const description = sanitizeVariable(args?.reminder_description || '');
|
|
@@ -87,6 +87,9 @@ async function handler(args = {}, context = {}) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
|
|
90
|
+
if (rawDecision === 'hold' && nextCheckAt && runtime.outreachAllowsFollowUp === false) {
|
|
91
|
+
return JSON.stringify({ success: false, error: 'next_check_at must be null: this proactive contact cannot plan a later check. Write now, or hold with next_check_at null.', data: {} });
|
|
92
|
+
}
|
|
90
93
|
if (holdReason === 'contingency_already_armed' && !nextCheckAt && runtime.checkInOtherPlans === 0) {
|
|
91
94
|
return JSON.stringify({ success: false, error: 'contingency_already_armed needs another active net or pending seguimiento, and this check-in has none: write now, or schedule a seguimiento and hold with rescheduled_for_cadence.', data: {} });
|
|
92
95
|
}
|
|
@@ -1038,6 +1038,7 @@ class NexusMessaging {
|
|
|
1038
1038
|
reminderType = 'seguimiento',
|
|
1039
1039
|
reminderPrefix = null,
|
|
1040
1040
|
replyToContact = false,
|
|
1041
|
+
allowFollowUp = true,
|
|
1041
1042
|
dryRun = false,
|
|
1042
1043
|
} = {}) {
|
|
1043
1044
|
const outreachStartedAt = new Date().toISOString();
|
|
@@ -1069,6 +1070,7 @@ class NexusMessaging {
|
|
|
1069
1070
|
outreachBrief: brief,
|
|
1070
1071
|
preemptiveWindowRoute: true,
|
|
1071
1072
|
outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
|
|
1073
|
+
outreachAllowsFollowUp: allowFollowUp,
|
|
1072
1074
|
outreachStartedAt,
|
|
1073
1075
|
// Stamped on the outbound so a delivered message joins back to the row that surfaced her.
|
|
1074
1076
|
triggeredBy: triggeredBy || null,
|
package/lib/index.d.ts
CHANGED
|
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
|
|
|
274
274
|
getWorkflowRunner(): WorkflowRunner;
|
|
275
275
|
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
276
276
|
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
|
|
277
|
-
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean }): Promise<OutreachDecision>;
|
|
277
|
+
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
|
|
278
278
|
processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
|
|
279
279
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
280
280
|
isConnected(): boolean;
|
|
@@ -964,7 +964,7 @@ async function patientTimerOf(review, level, now, { firing = false } = {}) {
|
|
|
964
964
|
return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
|
|
965
965
|
}
|
|
966
966
|
if (levelTimer) {
|
|
967
|
-
return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes() * 60 * 1000 }, gap };
|
|
967
|
+
return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes(level) * 60 * 1000 }, gap };
|
|
968
968
|
}
|
|
969
969
|
return { timer: null, gap };
|
|
970
970
|
}
|
|
@@ -2145,6 +2145,7 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
|
|
|
2145
2145
|
module.exports = {
|
|
2146
2146
|
BOOKKEEPING,
|
|
2147
2147
|
DOCUMENTING_STATUSES,
|
|
2148
|
+
FEVER_CATEGORY,
|
|
2148
2149
|
MAX_ALERT_ATTEMPTS,
|
|
2149
2150
|
PRE_DECISION_STATUSES,
|
|
2150
2151
|
_resetEscalationReviewIndexes,
|
|
@@ -8,7 +8,9 @@ const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
|
|
|
8
8
|
const TEAM_TIMEZONE = 'America/Mexico_City';
|
|
9
9
|
const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 20 };
|
|
10
10
|
const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
|
|
11
|
-
const DEFAULT_PATIENT_TIMER_MINUTES = 15;
|
|
11
|
+
const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20 };
|
|
12
|
+
const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES' };
|
|
13
|
+
const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
|
|
12
14
|
|
|
13
15
|
const rankOf = (level) => URGENCY_RANK[level] || 0;
|
|
14
16
|
const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
|
|
@@ -64,15 +66,19 @@ function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level])
|
|
|
64
66
|
return new Date(timeOf(from) + minutes * 60 * 1000);
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
const
|
|
68
|
-
const minutes = Number(runtimeConfig.get(
|
|
69
|
-
return Number.isFinite(minutes) && minutes > 0 ? minutes :
|
|
69
|
+
const positiveMinutes = (key, fallback) => {
|
|
70
|
+
const minutes = Number(runtimeConfig.get(key, fallback));
|
|
71
|
+
return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
|
|
70
72
|
};
|
|
71
73
|
|
|
72
|
-
//
|
|
74
|
+
// asap leaves the team its early alert before the patient gets the numbers to call.
|
|
75
|
+
const patientTimerMinutes = (level) => positiveMinutes(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
|
|
76
|
+
const untakenEarlyMinutes = () => positiveMinutes('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
|
|
77
|
+
|
|
78
|
+
// Untaken alerts: asap early, asap and urgent at half the response time, and every level at the deadline.
|
|
73
79
|
function untakenStagesOf(level, since, policy) {
|
|
74
80
|
const total = policy.responseMinutes[level];
|
|
75
|
-
const minutesOf = { early:
|
|
81
|
+
const minutesOf = { early: untakenEarlyMinutes(), half: total / 2, deadline: total };
|
|
76
82
|
return (UNTAKEN_STAGES[level] ?? [])
|
|
77
83
|
.filter((stage) => stage !== 'early' || minutesOf.early < minutesOf.half)
|
|
78
84
|
.map((stage) => ({ stage, minutes: minutesOf[stage], totalMinutes: total, dueAt: dueAtFor(since, level, policy, minutesOf[stage]) }));
|
|
@@ -44,21 +44,25 @@ const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtim
|
|
|
44
44
|
|
|
45
45
|
const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
|
|
46
46
|
|
|
47
|
-
async function
|
|
47
|
+
async function postToGroup(body, quoted) {
|
|
48
|
+
const res = await axios({
|
|
49
|
+
url: WHAPI_MESSAGES_URL,
|
|
50
|
+
method: 'POST',
|
|
51
|
+
data: { to: runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'), body, ...(quoted ? { quoted } : {}) },
|
|
52
|
+
timeout: REQUEST_TIMEOUT_MS,
|
|
53
|
+
headers: { authorization: `Bearer ${runtimeConfig.get('WHAPI_TOKEN')}` },
|
|
54
|
+
validateStatus: () => true,
|
|
55
|
+
});
|
|
56
|
+
if (res.status >= 200 && res.status < 300) return { delivered: true, error: null, messageId: res.data?.message?.id || null };
|
|
57
|
+
return { delivered: false, error: `whapi responded ${res.status}` };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function sendToGroup(body, quoted = null) {
|
|
48
61
|
if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
|
|
49
|
-
const token = runtimeConfig.get('WHAPI_TOKEN');
|
|
50
|
-
const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
|
|
51
62
|
try {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
data: { to: group, body },
|
|
56
|
-
timeout: REQUEST_TIMEOUT_MS,
|
|
57
|
-
headers: { authorization: `Bearer ${token}` },
|
|
58
|
-
validateStatus: () => true,
|
|
59
|
-
});
|
|
60
|
-
if (res.status >= 200 && res.status < 300) return { delivered: true, error: null };
|
|
61
|
-
return { delivered: false, error: `whapi responded ${res.status}` };
|
|
63
|
+
const sent = await postToGroup(body, quoted);
|
|
64
|
+
// A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
|
|
65
|
+
return sent.delivered || !quoted ? sent : await postToGroup(body, null);
|
|
62
66
|
} catch (error) {
|
|
63
67
|
return { delivered: false, error: redacted(error) };
|
|
64
68
|
}
|
|
@@ -66,9 +70,9 @@ async function sendToGroup(body) {
|
|
|
66
70
|
|
|
67
71
|
// Alerts the team group and every on-call phone. One failed recipient never stops the others,
|
|
68
72
|
// and nothing throws: the caller records what reached whom.
|
|
69
|
-
async function sendTeamAlert({ message, operator, notice = false }) {
|
|
73
|
+
async function sendTeamAlert({ message, operator, notice = false, quoted = null }) {
|
|
70
74
|
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
71
|
-
const group = await sendToGroup(message.body);
|
|
75
|
+
const group = await sendToGroup(message.body, quoted);
|
|
72
76
|
const phones = [];
|
|
73
77
|
for (const code of teamPhones()) {
|
|
74
78
|
try {
|
|
@@ -2,12 +2,12 @@ const { inlineOf } = require('../utils/coercionUtils');
|
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
4
|
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
|
-
const { conversationLink } = require('../clinical/services/clinicalAirtableService');
|
|
6
|
-
const { escalationGravePendingShadow, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
5
|
+
const { conversationLink, readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
6
|
+
const { escalationGravePendingShadow, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
7
7
|
|
|
8
8
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
9
9
|
const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
|
|
10
|
-
const { BOOKKEEPING, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
|
|
10
|
+
const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
|
|
11
11
|
const { recordGraveMissing } = require('./gravePendingService');
|
|
12
12
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
13
13
|
|
|
@@ -48,8 +48,15 @@ function untakenClockOf(review, policy) {
|
|
|
48
48
|
URGENCY_RANK[appliedLevelOf(alarm)] > (URGENCY_RANK[top] || 0) ? appliedLevelOf(alarm) : top
|
|
49
49
|
), null);
|
|
50
50
|
if (!level) return null;
|
|
51
|
-
const
|
|
52
|
-
|
|
51
|
+
const atLevel = alarms.filter((alarm) => appliedLevelOf(alarm) === level);
|
|
52
|
+
const since = new Date(atLevel[0].raisedAt);
|
|
53
|
+
return {
|
|
54
|
+
level,
|
|
55
|
+
since,
|
|
56
|
+
symptom: oneLine(atLevel.at(-1).symptom),
|
|
57
|
+
emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
|
|
58
|
+
stages: untakenStagesOf(level, since, policy),
|
|
59
|
+
};
|
|
53
60
|
}
|
|
54
61
|
|
|
55
62
|
const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.since });
|
|
@@ -77,6 +84,16 @@ function pendingQuestionOf(review, clock) {
|
|
|
77
84
|
return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
|
|
78
85
|
}
|
|
79
86
|
|
|
87
|
+
// The early asap alert says when the armed prompt gives the patient the numbers; a fever prompt keeps its own wording.
|
|
88
|
+
function patientPromptNote(review, stage, now) {
|
|
89
|
+
if (stage.stage !== 'early' || !escalationPatientTimerLive()) return null;
|
|
90
|
+
if (currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY)) return null;
|
|
91
|
+
// A leased or retried slot (attempts above 0) is already being sent.
|
|
92
|
+
if (review.doctorAlertKind !== 'patient_prompt' || (review.doctorAlertAttempts ?? 0) !== 0 || !review.doctorAlertDueAt) return null;
|
|
93
|
+
const lead = Math.round((new Date(review.doctorAlertDueAt).getTime() - now.getTime()) / 60000);
|
|
94
|
+
return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
80
97
|
async function identityOf(review) {
|
|
81
98
|
try {
|
|
82
99
|
return doctorIdentity(await getPatientInformation(review.patientCode));
|
|
@@ -88,7 +105,7 @@ async function identityOf(review) {
|
|
|
88
105
|
}
|
|
89
106
|
}
|
|
90
107
|
|
|
91
|
-
async function untakenMessage(review, clock, stage) {
|
|
108
|
+
async function untakenMessage(review, clock, stage, now) {
|
|
92
109
|
const { patientName, treatingDoctor } = await identityOf(review);
|
|
93
110
|
const patient = patientName || NO_NAME;
|
|
94
111
|
const doctor = treatingDoctor || NO_DOCTOR;
|
|
@@ -97,11 +114,13 @@ async function untakenMessage(review, clock, stage) {
|
|
|
97
114
|
const level = LEVEL_LABELS[clock.level];
|
|
98
115
|
const action = ACTIONS[clock.level];
|
|
99
116
|
const question = pendingQuestionOf(review, clock);
|
|
117
|
+
const note = patientPromptNote(review, stage, now);
|
|
100
118
|
return {
|
|
101
119
|
body: [
|
|
102
120
|
`⏰ ${level} sin tomar · ${deadline}`,
|
|
103
121
|
[`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
|
|
104
122
|
question && `Falta saber: ${question}`,
|
|
123
|
+
note,
|
|
105
124
|
`Qué hacer: ${action}`,
|
|
106
125
|
link,
|
|
107
126
|
].filter(Boolean).join('\n'),
|
|
@@ -109,7 +128,7 @@ async function untakenMessage(review, clock, stage) {
|
|
|
109
128
|
1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
|
|
110
129
|
2: patient,
|
|
111
130
|
3: doctor,
|
|
112
|
-
4: question
|
|
131
|
+
4: [question && `Falta saber: ${question}`, action, note].filter(Boolean).join(' · '),
|
|
113
132
|
5: link,
|
|
114
133
|
},
|
|
115
134
|
};
|
|
@@ -140,9 +159,11 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
140
159
|
await claimStage(review, clock, stage, now, taken);
|
|
141
160
|
return false;
|
|
142
161
|
}
|
|
143
|
-
const message = await untakenMessage(review, clock, stage);
|
|
162
|
+
const message = await untakenMessage(review, clock, stage, now);
|
|
163
|
+
// Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
|
|
164
|
+
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
144
165
|
if (!await claimStage(review, clock, stage, now)) return false;
|
|
145
|
-
const result = await sendTeamAlert({ message, operator: OPERATOR });
|
|
166
|
+
const result = await sendTeamAlert({ message, operator: OPERATOR, quoted });
|
|
146
167
|
const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
|
|
147
168
|
await getEscalationReview().updateOne(
|
|
148
169
|
{ _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
|
|
@@ -155,13 +176,13 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
155
176
|
BOOKKEEPING,
|
|
156
177
|
);
|
|
157
178
|
await audit(review, {
|
|
158
|
-
action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage,
|
|
179
|
+
action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage, threaded: Boolean(quoted),
|
|
159
180
|
delivered: result.delivered, groupDelivered: result.group.delivered, phonesDelivered, phones: result.phones.length,
|
|
160
181
|
});
|
|
161
182
|
return true;
|
|
162
183
|
}
|
|
163
184
|
|
|
164
|
-
// Alerts the whole team at each stage of a case nobody took (asap also
|
|
185
|
+
// Alerts the whole team at each stage of a case nobody took (asap also early); being with the doctor is not taken.
|
|
165
186
|
async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
166
187
|
const alerts = escalationUntakenAlertsLive();
|
|
167
188
|
const graveShadow = escalationGravePendingShadow();
|
|
@@ -171,7 +192,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
171
192
|
closedAt: null,
|
|
172
193
|
status: { $in: PRE_DECISION_STATUSES },
|
|
173
194
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
174
|
-
}, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, 'updates.at': 1,
|
|
195
|
+
}, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
175
196
|
'drafts.createdAt': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
176
197
|
})
|
|
177
198
|
.sort({ _id: -1 })
|