@peopl-health/nexus 5.61.0-dev.11184 → 5.61.0-dev.11186

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,4 +51,24 @@ function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText =
51
51
  };
52
52
  }
53
53
 
54
- module.exports = { reviewUpdateOf };
54
+ // The agent's own reading of each case since the escalation, handed to the draft so it builds on it
55
+ // instead of re-deriving it: the latest impression per case, the safety flags and what the patient said.
56
+ function characterizationSeedOf(updates = []) {
57
+ if (!Array.isArray(updates) || !updates.length) return null;
58
+ // Clinical order is the turn time, not the order the writes landed in.
59
+ const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
60
+ const latestByCase = new Map();
61
+ byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
62
+ const key = impression.caseId || impression.ctcaeTerm;
63
+ if (key) latestByCase.set(key, { ...impression, at: update.at });
64
+ }));
65
+ return {
66
+ cases: [...latestByCase.values()],
67
+ safetyFlags: [...new Set(updates.flatMap((update) => update.safetyFlags || []))],
68
+ newSinceEscalation: byTime
69
+ .filter((update) => update.patientText)
70
+ .map((update) => ({ at: update.at, patientText: update.patientText })),
71
+ };
72
+ }
73
+
74
+ module.exports = { characterizationSeedOf, reviewUpdateOf };
@@ -45,7 +45,14 @@ function settleProposal(parsed) {
45
45
  return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
46
46
  }
47
47
 
48
- function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
48
+ const textList = (value) => (Array.isArray(value) ? value.map(trimmed).filter(Boolean) : []);
49
+
50
+ function suggestCallOf(value) {
51
+ if (typeof value?.value !== 'boolean') return null;
52
+ return { value: value.value, reason: trimmed(value.reason) || null };
53
+ }
54
+
55
+ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
49
56
  const conversation = Array.isArray(context?.conversation)
50
57
  ? context.conversation.slice(-CONVERSATION_TURNS)
51
58
  : context?.conversation ?? null;
@@ -58,6 +65,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
58
65
  protocolVersion: FORMULARY_VERSION,
59
66
  protocol,
60
67
  alarms,
68
+ agentCharacterization,
61
69
  patient: {
62
70
  clinicalContext: context?.agentContext ?? null,
63
71
  conversation,
@@ -83,7 +91,9 @@ function draftProvider() {
83
91
  }
84
92
  }
85
93
 
86
- async function generateEscalationDraft({ code, callLogs = [], alarms = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
94
+ async function generateEscalationDraft({
95
+ code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
96
+ } = {}) {
87
97
  const { presetId } = await getEscalationDraft();
88
98
  const llm = provider ?? draftProvider();
89
99
 
@@ -92,7 +102,7 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
92
102
  }
93
103
 
94
104
  const context = await getEscalationContext({ code, now });
95
- const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
105
+ const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms, agentCharacterization });
96
106
 
97
107
  // Past this point a generation run was issued. Whether the request actually left the process is
98
108
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -165,6 +175,10 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
165
175
  doctorText,
166
176
  patientMessage,
167
177
  protocolVersion: FORMULARY_VERSION,
178
+ keyQuestions: textList(parsed?.keyQuestions),
179
+ unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
180
+ missingCharacterization: textList(parsed?.missingCharacterization),
181
+ suggestCall: suggestCallOf(parsed?.suggestCall),
168
182
  sectionsUnavailable: context.degradedSections ?? [],
169
183
  };
170
184
  }
@@ -102,10 +102,14 @@ function resolvedDrugs(proposals) {
102
102
  });
103
103
  }
104
104
 
105
+ function drugsNamedIn(text) {
106
+ const padded = ` ${key(text)} `;
107
+ return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
108
+ }
109
+
105
110
  function unproposedDrugsIn(text, proposals) {
106
111
  const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
107
- const padded = ` ${key(text)} `;
108
- return DRUG_NAMES.filter((name) => !proposed.has(name) && padded.includes(` ${name} `));
112
+ return drugsNamedIn(text).filter((name) => !proposed.has(name));
109
113
  }
110
114
 
111
115
  function crossSymptomIssues(proposals) {
@@ -127,5 +131,6 @@ function crossSymptomIssues(proposals) {
127
131
  module.exports = {
128
132
  validateProposal,
129
133
  unproposedDrugsIn,
134
+ drugsNamedIn,
130
135
  crossSymptomIssues,
131
136
  };
@@ -6,6 +6,7 @@ const { _clearClinicalContextCache } = require('../helpers/patientInformationHel
6
6
  const { setPreprocessingHandler } = require('../services/preprocessingService');
7
7
  const { clearTriageHistoryCache } = require('../services/triageHistoryService');
8
8
  const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
9
+ const { stopReviewDraftSweep } = require('../services/reviewDraftSweepService');
9
10
  const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
10
11
  const { _resetDefaultInstance } = require('../core/NexusMessaging');
11
12
  const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
@@ -20,7 +21,9 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
20
21
  const SWEEP_STOP_MS = 2000;
21
22
 
22
23
  function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
23
- const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep()]);
24
+ const stopped = Promise.allSettled([
25
+ stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(),
26
+ ]);
24
27
  return withTimeout(stopped, timeoutMs, 'sweeps.stop')
25
28
  .catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
26
29
  }
@@ -7,6 +7,7 @@ const {
7
7
  cancelEscalationReview,
8
8
  closeEscalationReview,
9
9
  getEscalationReviewById,
10
+ getReviewTimeline,
10
11
  handOffToDoctor,
11
12
  listEscalationReviews,
12
13
  openEscalationReview,
@@ -53,6 +54,15 @@ const getEscalationReviewController = async (req, res) => {
53
54
  }
54
55
  };
55
56
 
57
+ const getReviewTimelineController = async (req, res) => {
58
+ try {
59
+ const timeline = await getReviewTimeline({ id: req.params.id });
60
+ res.status(200).json({ success: true, timeline });
61
+ } catch (error) {
62
+ respondWithError(res, error, 'reading the escalation review timeline', { reviewId: req.params?.id });
63
+ }
64
+ };
65
+
56
66
  const listEscalationReviewsController = async (req, res) => {
57
67
  try {
58
68
  const reviews = await listEscalationReviews({ code: req.params.code });
@@ -143,6 +153,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
143
153
  comment = null,
144
154
  doctorName = null,
145
155
  doctorReply = null,
156
+ reason = null,
157
+ draftNumber = null,
146
158
  triggeredBy,
147
159
  } = req.body || {};
148
160
  const review = await recordDoctorDecision({
@@ -153,6 +165,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
153
165
  comment,
154
166
  doctorName,
155
167
  doctorReply,
168
+ reason,
169
+ draftNumber,
156
170
  recordedBy: triggeredBy,
157
171
  requestId: req.requestId,
158
172
  });
@@ -224,6 +238,7 @@ module.exports = {
224
238
  cancelEscalationReviewController,
225
239
  closeEscalationReviewController,
226
240
  getEscalationReviewController,
241
+ getReviewTimelineController,
227
242
  handOffEscalationReviewController,
228
243
  listEscalationReviewsController,
229
244
  openEscalationReviewController,
@@ -2,6 +2,7 @@ const moment = require('moment-timezone');
2
2
  const mongoose = require('mongoose');
3
3
 
4
4
  const { logger } = require('../utils/logger');
5
+ const { withTimeout } = require('../utils/timeoutUtils');
5
6
 
6
7
  const { ScheduledMessage } = require('../models/agendaMessageModel.js');
7
8
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
@@ -13,6 +14,9 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
13
14
 
14
15
  const { getRecordByFilter } = require('../services/airtableService');
15
16
  const { getMessages } = require('../services/messageService');
17
+ const { recordDirectIndication } = require('../services/escalationReviewService');
18
+
19
+ const INDICATION_WAIT_MS = 5000;
16
20
 
17
21
  const { sendMessage, sendScheduledMessage, getDefaultInstance } = require('../core/NexusMessaging');
18
22
 
@@ -69,7 +73,8 @@ const sendMessageController = async (req, res) => {
69
73
  frontendId = null,
70
74
  triggeredBy = null,
71
75
  idempotencyKey = null,
72
- contactCode = null
76
+ contactCode = null,
77
+ asIndication = false
73
78
  } = req.body || {};
74
79
 
75
80
  const formattedCode = ensureWhatsAppFormat(code);
@@ -100,6 +105,21 @@ const sendMessageController = async (req, res) => {
100
105
  variables: finalVariables, code: formattedCode,
101
106
  frontendId, triggeredBy, idempotencyKey, ...contact
102
107
  });
108
+ // Only a message the approver explicitly sent as the indication resolves the clinical review.
109
+ if (asIndication === true && result?.success && triggeredBy && message && !contentSid && !contact.contactCode) {
110
+ // Awaited so the review is usually settled before the reply returns, but never for long: the
111
+ // message already went out, and a slow lookup finishes in the background. It never throws.
112
+ await withTimeout(recordDirectIndication({
113
+ code: formattedCode,
114
+ triggeredBy,
115
+ body: message,
116
+ messageId: _pickMessageId(result, null),
117
+ status: result?.status ?? null,
118
+ deferred: result?.deferred === true || result?.preemptive === true,
119
+ }), INDICATION_WAIT_MS, 'clinical review resolution').catch((error) => {
120
+ logger.warn('[sendMessageController] The clinical review is still resolving in the background', { error: error.message });
121
+ });
122
+ }
103
123
  return res.status(200).json({
104
124
  success: result?.success ?? true,
105
125
  messageId: _pickMessageId(result, null),
package/lib/index.d.ts CHANGED
@@ -355,6 +355,8 @@ declare module '@peopl-health/nexus' {
355
355
  ner?: NerOptions;
356
356
  recommendationRecovery?: RecommendationRecoveryOptions;
357
357
  inboundRecovery?: InboundRecoveryOptions;
358
+ reviewDrafts?: ReviewDraftsOptions;
359
+ reviewAlerts?: ReviewAlertsOptions;
358
360
  }
359
361
 
360
362
  export interface RecommendationRecoveryOptions {
@@ -362,6 +364,18 @@ declare module '@peopl-health/nexus' {
362
364
  intervalMs?: number;
363
365
  }
364
366
 
367
+ export interface ReviewDraftsOptions {
368
+ /** Writes the clinical review draft automatically after each alarm or agent update. */
369
+ enabled?: boolean;
370
+ intervalMs?: number;
371
+ }
372
+
373
+ export interface ReviewAlertsOptions {
374
+ /** WhatsApps the approver on stat/asap reviews and re-alerts an unanswered stat review. */
375
+ enabled?: boolean;
376
+ intervalMs?: number;
377
+ }
378
+
365
379
  export interface InboundRecoveryOptions {
366
380
  enabled: boolean;
367
381
  intervalMs?: number;
package/lib/index.js CHANGED
@@ -32,6 +32,8 @@ const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNet
32
32
  const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
33
  const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
34
34
  const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
35
+ const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
36
+ const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
35
37
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
36
38
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
37
39
  const { DrainingError } = require('./core/BatchingManager');
@@ -203,6 +205,24 @@ class Nexus {
203
205
  logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
204
206
  }
205
207
 
208
+ try {
209
+ if (options.reviewDrafts?.enabled === true) {
210
+ startReviewDraftSweep({ intervalMs: options.reviewDrafts.intervalMs });
211
+ logger.info('[Nexus] clinical review draft sweep armed');
212
+ }
213
+ } catch (e) {
214
+ logger.warn('Warning: failed to arm the clinical review draft sweep:', e?.message || e);
215
+ }
216
+
217
+ try {
218
+ if (options.reviewAlerts?.enabled === true) {
219
+ startReviewAlertSweep({ intervalMs: options.reviewAlerts.intervalMs });
220
+ logger.info('[Nexus] clinical review doctor alert sweep armed');
221
+ }
222
+ } catch (e) {
223
+ logger.warn('Warning: failed to arm the clinical review doctor alert sweep:', e?.message || e);
224
+ }
225
+
206
226
  try {
207
227
  if (options.inboundRecovery?.enabled === true) {
208
228
  startInboundRecoverySweep({
@@ -10,8 +10,9 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
10
10
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
11
11
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
12
12
  const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
13
- const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
14
- const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
13
+ const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'direct_chat'];
14
+ const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
15
+ const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
15
16
 
16
17
  const alarmSchema = new mongoose.Schema({
17
18
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
@@ -36,6 +37,17 @@ const impressionUpdateSchema = new mongoose.Schema({
36
37
  checkInQuestion: { type: String, default: null },
37
38
  }, { _id: false });
38
39
 
40
+ const doctorAlertSchema = new mongoose.Schema({
41
+ kind: { type: String, enum: ['initial', 'realert'], required: true },
42
+ urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
43
+ physicianEmail: { type: String, default: null },
44
+ transport: { type: String, default: null },
45
+ messageId: { type: String, default: null },
46
+ error: { type: String, default: null },
47
+ teamAlerted: { type: Boolean, default: false },
48
+ sentAt: { type: Date, required: true },
49
+ }, { _id: false });
50
+
39
51
  const reviewUpdateSchema = new mongoose.Schema({
40
52
  turnId: { type: String, required: true },
41
53
  tools: { type: [String], default: [] },
@@ -65,10 +77,21 @@ const callLogSchema = new mongoose.Schema({
65
77
  loggedBy: { type: String, required: true },
66
78
  }, { timestamps: { createdAt: true, updatedAt: false } });
67
79
 
80
+ const suggestCallSchema = new mongoose.Schema({
81
+ value: { type: Boolean, required: true },
82
+ reason: { type: String, default: null },
83
+ }, { _id: false });
84
+
68
85
  const draftSchema = new mongoose.Schema({
69
86
  doctorText: { type: String, required: true },
70
87
  patientMessage: { type: String, required: true },
71
88
  writtenBy: { type: String, required: true },
89
+ protocolVersion: { type: String, default: null },
90
+ keyQuestions: { type: [String], default: undefined },
91
+ unassessedRedFlags: { type: [String], default: undefined },
92
+ missingCharacterization: { type: [String], default: undefined },
93
+ suggestCall: { type: suggestCallSchema, default: undefined },
94
+ sectionsUnavailable: { type: [String], default: undefined },
72
95
  }, { timestamps: { createdAt: true, updatedAt: false } });
73
96
 
74
97
  const doctorHandoffSchema = new mongoose.Schema({
@@ -89,6 +112,8 @@ const decisionSchema = new mongoose.Schema({
89
112
  finalText: { type: String, default: null },
90
113
  comment: { type: String, default: null },
91
114
  doctorReply: { type: String, default: null },
115
+ returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
116
+ warnings: { type: [String], default: undefined },
92
117
  decidedBy: { type: String, required: true },
93
118
  recordedBy: { type: String, required: true },
94
119
  }, { timestamps: { createdAt: true, updatedAt: false } });
@@ -149,6 +174,16 @@ const escalationReviewSchema = new mongoose.Schema({
149
174
  alarms: { type: [alarmSchema], default: [] },
150
175
  updates: { type: [reviewUpdateSchema], default: [] },
151
176
  updatedSinceSeen: { type: Boolean, default: false },
177
+ followUpCases: { type: [String], default: undefined },
178
+ // The decision the follow-up cases were fixed for; a later indication extends them.
179
+ followUpDecision: { type: Number, default: null },
180
+ draftDueAt: { type: Date, default: null },
181
+ draftAttempts: { type: Number, default: 0 },
182
+ doctorAlerts: { type: [doctorAlertSchema], default: [] },
183
+ doctorAlertDueAt: { type: Date, default: null },
184
+ doctorAlertKind: { type: String, enum: ['initial', 'realert', null], default: null },
185
+ doctorAlertAttempts: { type: Number, default: 0 },
186
+ approverViewedAt: { type: Date, default: null },
152
187
  previousReviewId: { type: String, default: null },
153
188
  callLogs: { type: [callLogSchema], default: [] },
154
189
  noteFacts: { type: [noteFactSchema], default: [] },
@@ -165,6 +200,8 @@ const escalationReviewSchema = new mongoose.Schema({
165
200
  }, { timestamps: true });
166
201
 
167
202
  escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
203
+ escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
204
+ escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
168
205
  escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
169
206
 
170
207
  const getEscalationReview = () => {
@@ -182,6 +219,7 @@ module.exports = {
182
219
  DOCTOR_DECISIONS,
183
220
  HANDOFF_MODES,
184
221
  INTERRUPTED_STATUSES,
222
+ RETURN_REASONS,
185
223
  getEscalationReview,
186
224
  escalationReviewSchema,
187
225
  };
@@ -122,6 +122,7 @@ const escalationReviewRouteDefinitions = {
122
122
  'POST /': 'openEscalationReviewController',
123
123
  'GET /by-patient/:code': 'listEscalationReviewsController',
124
124
  'GET /:id': 'getEscalationReviewController',
125
+ 'GET /:id/timeline': 'getReviewTimelineController',
125
126
  'POST /:id/cases': 'setEscalationReviewCasesController',
126
127
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
127
128
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
@@ -295,6 +296,7 @@ const builtInControllers = {
295
296
  openEscalationReviewController: escalationReviewController.openEscalationReviewController,
296
297
  listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
297
298
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
299
+ getReviewTimelineController: escalationReviewController.getReviewTimelineController,
298
300
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
299
301
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
300
302
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,