@peopl-health/nexus 6.5.3 → 6.5.4
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 +2 -1
- package/lib/clinical/flags/escalationFlags.js +5 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +14 -0
- package/lib/models/escalationReviewModel.js +9 -0
- package/lib/services/characterizationOutcomeService.js +19 -9
- package/lib/services/stillNeededService.js +35 -0
- package/lib/services/untakenAlertService.js +1 -1
- package/package.json +1 -1
|
@@ -149,7 +149,8 @@ class AssistantProcessor {
|
|
|
149
149
|
|
|
150
150
|
maybeWarmPatientRisk({ code: thread.code, turnId: runOptions.runId || null });
|
|
151
151
|
|
|
152
|
-
|
|
152
|
+
// Only the live patient turn may take the review's pending question; shadows, replays and staff reads build context too.
|
|
153
|
+
const runConfig = { ...runOptions, phiProcessor: this.phiProcessor, contingencySnapshot, followUpSnapshot, claimStillNeeded: !runOptions.shadow && isPatientTurn };
|
|
153
154
|
const bridgeArmed = Boolean(!runOptions.shadow && message?.body && this.sendMessage);
|
|
154
155
|
let bridgeDecision = null;
|
|
155
156
|
let bridgeReasoning = null;
|
|
@@ -28,6 +28,10 @@ function escalationAutoHandoffLive() {
|
|
|
28
28
|
return flagNotOff('ESCALATION_AUTO_HANDOFF_LIVE');
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
function escalationInTurnAskLive() {
|
|
32
|
+
return flagNotOff('ESCALATION_IN_TURN_ASK_LIVE');
|
|
33
|
+
}
|
|
34
|
+
|
|
31
35
|
function escalationUntakenAlertsLive() {
|
|
32
36
|
return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
|
|
33
37
|
}
|
|
@@ -49,6 +53,7 @@ module.exports = {
|
|
|
49
53
|
escalationApproverAlertLive,
|
|
50
54
|
escalationAssessmentLive,
|
|
51
55
|
escalationAutoHandoffLive,
|
|
56
|
+
escalationInTurnAskLive,
|
|
52
57
|
escalationPatientTimerLive,
|
|
53
58
|
escalationUntakenAlertsLive,
|
|
54
59
|
escalationUpdateModeLive,
|
|
@@ -52,6 +52,9 @@ const PENDING_INSTRUCTION_NOTE = `${OPERATOR_TURN_PREFIX} Hay un mensaje del sis
|
|
|
52
52
|
const deliveredWhileWaitingNote = (text) =>
|
|
53
53
|
`${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
|
|
54
54
|
|
|
55
|
+
const stillNeededNote = (question) =>
|
|
56
|
+
`${OPERATOR_TURN_PREFIX} La revisión del equipo médico todavía necesita saber: "${question}". Si el paciente no lo contestó en este mensaje, pregúntalo con tus palabras al final de tu respuesta, como tu única pregunta, y no digas que el equipo ya tiene todo. Si ya lo contestó, no lo preguntes.`;
|
|
57
|
+
|
|
55
58
|
function readComorbidities(value) {
|
|
56
59
|
const parsed = typeof value === 'string' ? safeParse(value, null) : value;
|
|
57
60
|
if (!isPlainObject(parsed)) return inline(value);
|
|
@@ -130,6 +133,8 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
130
133
|
content: formatPatientMessage(turnLines),
|
|
131
134
|
type: 'message'
|
|
132
135
|
});
|
|
136
|
+
const question = config.claimStillNeeded ? await this._stillNeeded(thread.code, config.runId) : null;
|
|
137
|
+
if (question) context.push({ [CURRENT_TURN]: true, role: 'user', content: stillNeededNote(inline(question)), type: 'message' });
|
|
133
138
|
}
|
|
134
139
|
|
|
135
140
|
for (const msg of await this._outboundTail(thread.code, beforeCheckpoint, config)) {
|
|
@@ -152,6 +157,15 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
152
157
|
}
|
|
153
158
|
}
|
|
154
159
|
|
|
160
|
+
async _stillNeeded(code, turnId) {
|
|
161
|
+
try {
|
|
162
|
+
return await require('../../services/stillNeededService').claimStillNeeded(code, turnId);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
logger.warn('[DefaultMemoryManager] still-needed datum unavailable', { error: error.message });
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
155
169
|
_hasPendingInstruction(code, beforeCheckpoint, config) {
|
|
156
170
|
return Boolean(beforeCheckpoint) && !config.beforeCheckpoint && hasInstructionInFlight(code);
|
|
157
171
|
}
|
|
@@ -112,6 +112,14 @@ const blockingAskSchema = new mongoose.Schema({
|
|
|
112
112
|
outcome: { type: String, default: null },
|
|
113
113
|
}, { _id: false });
|
|
114
114
|
|
|
115
|
+
const inTurnAskSchema = new mongoose.Schema({
|
|
116
|
+
draftAt: { type: Date, required: true },
|
|
117
|
+
key: { type: String, required: true },
|
|
118
|
+
question: { type: String, required: true },
|
|
119
|
+
turnId: { type: String, default: null },
|
|
120
|
+
at: { type: Date, required: true },
|
|
121
|
+
}, { _id: false });
|
|
122
|
+
|
|
115
123
|
const reviewUpdateSchema = new mongoose.Schema({
|
|
116
124
|
turnId: { type: String, required: true },
|
|
117
125
|
tools: { type: [String], default: [] },
|
|
@@ -362,6 +370,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
362
370
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
363
371
|
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
364
372
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
373
|
+
inTurnAsks: { type: [inTurnAskSchema], default: [] },
|
|
365
374
|
feverPromptStartedAt: { type: Date, default: null },
|
|
366
375
|
approverViewedAt: { type: Date, default: null },
|
|
367
376
|
previousReviewId: { type: String, default: null },
|
|
@@ -117,14 +117,17 @@ function outcomeOf(review, clock, now) {
|
|
|
117
117
|
if (latest.sufficientForDoctor !== false) return null;
|
|
118
118
|
// The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
|
|
119
119
|
const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
120
|
+
// The bot asked this draft's question in its own reply when no redraft followed that reply.
|
|
121
|
+
const inTurn = (review.inTurnAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
120
122
|
const sent = ask && !ask.skippedReason;
|
|
123
|
+
const askedAt = sent ? ask.sentAt : inTurn?.at ?? latest.createdAt;
|
|
121
124
|
// A first handoff with a question waits for its ask (recorded once the bot's reply is in), or in flight, up to twice the wait.
|
|
122
|
-
if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(
|
|
123
|
-
if (minutesSince(
|
|
125
|
+
if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(askedAt, now) < 2 * wait) return null;
|
|
126
|
+
if (minutesSince(askedAt, now) < wait) return null;
|
|
124
127
|
const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
|
|
125
128
|
// An update's draft is never asked about, so it says only what is missing.
|
|
126
129
|
if (update) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(noteOf(missing)) };
|
|
127
|
-
const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open';
|
|
130
|
+
const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open' || Boolean(inTurn);
|
|
128
131
|
return { grave: [], update, notify, note: noteOf(`${missing} (${asked ? 'no contestó' : 'no se le preguntó'})`) };
|
|
129
132
|
}
|
|
130
133
|
|
|
@@ -385,13 +388,12 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
385
388
|
await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
|
|
386
389
|
}
|
|
387
390
|
|
|
388
|
-
|
|
389
|
-
async function askBlockingQuestion(review, clock, now) {
|
|
391
|
+
function pendingAskOf(review, clock) {
|
|
390
392
|
// With the doctor, only a case the bot handed over is still asked, and only its grave data.
|
|
391
393
|
const withDoctor = review.status === 'awaiting_doctor';
|
|
392
|
-
if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
|
|
394
|
+
if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return null;
|
|
393
395
|
const latest = (review.drafts ?? []).at(-1);
|
|
394
|
-
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
|
|
396
|
+
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return null;
|
|
395
397
|
// A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
|
|
396
398
|
const settled = new Set([
|
|
397
399
|
...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
|
|
@@ -401,8 +403,16 @@ async function askBlockingQuestion(review, clock, now) {
|
|
|
401
403
|
: pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
|
|
402
404
|
const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
|
|
403
405
|
const question = graveFlags.join('; ') || blocking || null;
|
|
406
|
+
if (!question) return null;
|
|
404
407
|
const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
|
|
405
|
-
|
|
408
|
+
return { latest, withDoctor, graveFlags, blocking, question, flags };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
|
|
412
|
+
async function askBlockingQuestion(review, clock, now) {
|
|
413
|
+
const pending = pendingAskOf(review, clock);
|
|
414
|
+
if (!pending) return;
|
|
415
|
+
const { latest, withDoctor, graveFlags, blocking, question, flags } = pending;
|
|
406
416
|
const asks = review.blockingAsks ?? [];
|
|
407
417
|
if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
408
418
|
const last = await lastChatMessage(review.patientCode);
|
|
@@ -470,4 +480,4 @@ async function settleCharacterization(review, clock, now) {
|
|
|
470
480
|
await askBlockingQuestion(review, clock, now);
|
|
471
481
|
}
|
|
472
482
|
|
|
473
|
-
module.exports = { outcomeOf, settleCharacterization };
|
|
483
|
+
module.exports = { outcomeOf, pendingAskOf, settleCharacterization };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const { normalizedKeyOf } = require('../utils/coercionUtils');
|
|
2
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
4
|
+
const { escalationInTurnAskLive } = require('../clinical/flags/escalationFlags');
|
|
5
|
+
|
|
6
|
+
const { BOOKKEEPING, caseTakenReason } = require('./escalationReviewService');
|
|
7
|
+
const { pendingAskOf } = require('./characterizationOutcomeService');
|
|
8
|
+
const { responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
9
|
+
const { UNTAKEN_PROJECTION, untakenClockOf } = require('./untakenAlertService');
|
|
10
|
+
|
|
11
|
+
// The review's blocking question the bot asks in its own reply: not grave, and served once per episode.
|
|
12
|
+
async function claimStillNeeded(code, turnId = null, now = new Date()) {
|
|
13
|
+
if (!escalationInTurnAskLive()) return null;
|
|
14
|
+
const review = await getEscalationReview().findOne({ patientCode: ensureWhatsAppFormat(code), closedAt: null, status: 'draft_ready' }, UNTAKEN_PROJECTION).lean();
|
|
15
|
+
if (!review) return null;
|
|
16
|
+
const clock = untakenClockOf(review, responseDeadlinePolicy());
|
|
17
|
+
const pending = clock && pendingAskOf(review, clock);
|
|
18
|
+
if (!pending?.blocking) return null;
|
|
19
|
+
const key = normalizedKeyOf(pending.latest.blockingFlag || pending.blocking);
|
|
20
|
+
const served = { key, draftAt: { $gte: clock.since } };
|
|
21
|
+
const earlier = (review.inTurnAsks ?? []).find((entry) => entry.key === key && new Date(entry.draftAt) >= clock.since);
|
|
22
|
+
// A retry of the same turn rebuilds its context, so it gets the question its first attempt claimed.
|
|
23
|
+
if (earlier) return turnId && earlier.turnId === turnId ? earlier.question : null;
|
|
24
|
+
// A case the team already took is theirs to ask; a missing thread does not count as taken.
|
|
25
|
+
const taken = await caseTakenReason(review, clock.since, clock.level);
|
|
26
|
+
if (taken && taken !== 'thread_missing') return null;
|
|
27
|
+
const claimed = await getEscalationReview().updateOne(
|
|
28
|
+
{ _id: review._id, closedAt: null, inTurnAsks: { $not: { $elemMatch: served } } },
|
|
29
|
+
{ $push: { inTurnAsks: { draftAt: pending.latest.createdAt, key, question: pending.blocking, turnId, at: now } } },
|
|
30
|
+
BOOKKEEPING,
|
|
31
|
+
);
|
|
32
|
+
return claimed.modifiedCount ? pending.blocking : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { claimStillNeeded };
|
|
@@ -27,7 +27,7 @@ const ACTIONS = {
|
|
|
27
27
|
};
|
|
28
28
|
const MAX_QUESTION_LENGTH = 200;
|
|
29
29
|
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
30
|
-
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
30
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
31
31
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
32
32
|
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
33
33
|
};
|