@peopl-health/nexus 5.72.5 → 5.72.7

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.
@@ -1,4 +1,5 @@
1
1
  const { createLLMProvider } = require('../providers/createLLMProvider');
2
+ const { REQUEST_MAX_RETRIES, resolveRequestTimeoutMs } = require('../providers/AnthropicProvider');
2
3
  const runtimeConfig = require('../../config/runtimeConfig');
3
4
 
4
5
  const { logger } = require('../../utils/logger');
@@ -50,7 +51,7 @@ const getAnthropicClient = () => {
50
51
  if (!apiKey) return null;
51
52
  try {
52
53
  const { Anthropic } = require('@anthropic-ai/sdk');
53
- state.anthropicClient = new Anthropic({ apiKey });
54
+ state.anthropicClient = new Anthropic({ apiKey, timeout: resolveRequestTimeoutMs(), maxRetries: REQUEST_MAX_RETRIES });
54
55
  logger.info('[llmConfig] Anthropic client initialised');
55
56
  } catch (error) {
56
57
  logger.warn('[llmConfig] Failed to initialise Anthropic client', { error: error?.message });
@@ -2,6 +2,7 @@ const fs = require('fs');
2
2
  const path = require('path');
3
3
 
4
4
  const llmConfig = require('../config/llmConfig.js');
5
+ const { resolveRequestTimeoutMs, structuredTimeoutMs } = require('../providers/AnthropicProvider');
5
6
 
6
7
  const { composePrompt } = require('../services/promptComposerService');
7
8
 
@@ -30,6 +31,7 @@ const DISPLAYED_NUMBER = /^-?\d+(?:[.,]\d+)?$/;
30
31
 
31
32
  const ANALYSIS_MODEL = 'claude-sonnet-5';
32
33
  const MAX_ANALYSIS_TOKENS = 4096;
34
+ const IMAGE_MAX_RETRIES = 1;
33
35
 
34
36
  const ANALYSIS_PROMPT = `Eres un oncólogo clínico con experiencia. Recibirás una imagen que un paciente envió por WhatsApp. Puede ser una receta, un resultado de laboratorio, un estudio de imagen, una nota clínica, la pantalla de un aparato de medición casero, la caja de un medicamento, o algo sin relación médica.
35
37
 
@@ -199,7 +201,7 @@ async function analyzeImage(imagePath, isSticker = false, contentType = null) {
199
201
  { type: 'image', source: { type: 'base64', media_type: mimeType, data: base64Image } },
200
202
  { type: 'text', text: prompt }
201
203
  ]}]
202
- });
204
+ }, { timeout: structuredTimeoutMs(maxTokens, resolveRequestTimeoutMs()), maxRetries: IMAGE_MAX_RETRIES });
203
205
 
204
206
  if (isSticker) {
205
207
  const result = await createImageMessage('Describe the image in detail.', ANALYSIS_MODEL, MAX_ANALYSIS_TOKENS);
@@ -627,4 +627,7 @@ class AnthropicProvider extends BaseLLMProvider {
627
627
 
628
628
  module.exports = {
629
629
  AnthropicProvider,
630
+ REQUEST_MAX_RETRIES,
631
+ resolveRequestTimeoutMs,
632
+ structuredTimeoutMs,
630
633
  };
@@ -16,6 +16,7 @@ const {
16
16
  requestBotDraft,
17
17
  sendApprovedIndications,
18
18
  setReviewCases,
19
+ listReviewCaseCandidates,
19
20
  suggestDraft,
20
21
  suggestKeyQuestions,
21
22
  confirmNoteFacts,
@@ -97,6 +98,15 @@ const setEscalationReviewCasesController = async (req, res) => {
97
98
  }
98
99
  };
99
100
 
101
+ const listEscalationReviewCaseCandidatesController = async (req, res) => {
102
+ try {
103
+ const candidates = await listReviewCaseCandidates({ id: req.params.id });
104
+ res.status(200).json({ success: true, candidates });
105
+ } catch (error) {
106
+ respondWithError(res, error, 'listing escalation review case candidates', { reviewId: req.params?.id });
107
+ }
108
+ };
109
+
100
110
  const addEscalationReviewCallLogController = async (req, res) => {
101
111
  try {
102
112
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
@@ -289,6 +299,7 @@ module.exports = {
289
299
  recordEscalationReviewDecisionController,
290
300
  sendEscalationReviewIndicationsController,
291
301
  setEscalationReviewCasesController,
302
+ listEscalationReviewCaseCandidatesController,
292
303
  suggestEscalationReviewDraftController,
293
304
  suggestEscalationReviewQuestionsController,
294
305
  syncEscalationReviewCaseController,
@@ -0,0 +1,51 @@
1
+ // Triage cases a review can cover: the patient's cases raised from a day before the review opened, plus
2
+ // the ones it already covers. A case is only suggested; the team decides which ones the review covers.
3
+ const LOOKBACK_MS = 24 * 60 * 60 * 1000;
4
+ const NEAR_ALARM_MS = 2 * 60 * 60 * 1000;
5
+ const STEM_LENGTH = 5;
6
+ // Stems too common in symptom names and alarm text to tell two symptoms apart.
7
+ const GENERIC_STEMS = new Set(['dolor', 'grado', 'sinto', 'para', 'del', 'con', 'las', 'los', 'una', 'que', 'por', 'sin', 'dific', 'frecu']);
8
+
9
+ const words = (text) => String(text ?? '')
10
+ .toLowerCase()
11
+ .normalize('NFD')
12
+ .replace(/[̀-ͯ]/g, '')
13
+ .split(/[^a-z]+/)
14
+ .filter((word) => word.length >= 3)
15
+ .map((word) => word.slice(0, STEM_LENGTH))
16
+ .filter((stem) => !GENERIC_STEMS.has(stem));
17
+
18
+ const symptomOf = (description) => String(description ?? '').replace(/\s*Grado\s*-\s*\d+\s*$/i, '');
19
+
20
+ // Suggested when an alarm of the review came within two hours of the case and names the same symptom.
21
+ function isSuggested(patientCase, alarms) {
22
+ const caseWords = words(symptomOf(patientCase.description));
23
+ const createdAt = Date.parse(patientCase.createdAt);
24
+ if (!caseWords.length || !Number.isFinite(createdAt)) return false;
25
+ return alarms.some((alarm) => {
26
+ if (!(Math.abs(new Date(alarm.raisedAt).getTime() - createdAt) <= NEAR_ALARM_MS)) return false;
27
+ const alarmWords = new Set(words(`${alarm.symptom ?? ''} ${alarm.suspectedCondition ?? ''}`));
28
+ return caseWords.some((word) => alarmWords.has(word));
29
+ });
30
+ }
31
+
32
+ function caseCandidates({ review, cases, linkedIds }) {
33
+ const since = new Date(review.createdAt).getTime() - LOOKBACK_MS;
34
+ const linked = new Set(linkedIds);
35
+ return cases
36
+ .filter((patientCase) => linked.has(patientCase.recordId) || Date.parse(patientCase.createdAt) >= since)
37
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
38
+ .map((patientCase) => ({
39
+ recordId: patientCase.recordId,
40
+ number: patientCase.number,
41
+ createdAt: patientCase.createdAt,
42
+ description: patientCase.description,
43
+ grade: patientCase.grade,
44
+ status: patientCase.status,
45
+ operationsStatus: patientCase.operationsStatus,
46
+ isLinked: linked.has(patientCase.recordId),
47
+ isSuggested: !linked.has(patientCase.recordId) && isSuggested(patientCase, review.alarms ?? []),
48
+ }));
49
+ }
50
+
51
+ module.exports = { caseCandidates };
@@ -128,6 +128,7 @@ const escalationReviewRouteDefinitions = {
128
128
  'GET /by-patient/:code': 'listEscalationReviewsController',
129
129
  'GET /:id': 'getEscalationReviewController',
130
130
  'GET /:id/timeline': 'getReviewTimelineController',
131
+ 'GET /:id/case-candidates': 'listEscalationReviewCaseCandidatesController',
131
132
  'POST /:id/cases': 'setEscalationReviewCasesController',
132
133
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
133
134
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
@@ -311,6 +312,7 @@ const builtInControllers = {
311
312
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
312
313
  requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
313
314
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
315
+ listEscalationReviewCaseCandidatesController: escalationReviewController.listEscalationReviewCaseCandidatesController,
314
316
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
315
317
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
316
318
  suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
@@ -24,6 +24,7 @@ const {
24
24
  } = require('../models/escalationReviewModel');
25
25
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
26
26
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
27
+ const { caseCandidates } = require('../helpers/reviewCaseCandidateHelper');
27
28
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
28
29
  const { DrainingError } = require('../core/BatchingManager');
29
30
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
@@ -45,7 +46,7 @@ const { composePrompt } = require('../clinical/services/promptComposerService');
45
46
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
46
47
 
47
48
  const { getPatientInformation, logPatientChange } = require('./patientService');
48
- const { MAX_NOTE_LENGTH, getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
49
+ const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
49
50
  const { countMessages } = require('./messageService');
50
51
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
51
52
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
@@ -68,6 +69,8 @@ const BOOKKEEPING = { timestamps: false };
68
69
  const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
69
70
  const DUPLICATE_KEY_ERROR = 11000;
70
71
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
72
+ // The cases a review covers can change while it is open and no operation is in flight.
73
+ const CASE_SELECTABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor', 'approved', 'needs_intervention', ...FOLLOWUP_STATUSES];
71
74
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
72
75
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
73
76
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
@@ -450,7 +453,7 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
450
453
  const recordIds = [...new Set(requested.map((recordId) => String(recordId ?? '').trim()).filter(Boolean))];
451
454
  if (!recordIds.length) return [];
452
455
 
453
- const { cases } = await getPatientTasks(patientCode);
456
+ const cases = await readPatientCases(patientCode);
454
457
  const known = new Set(cases.map((patientCase) => patientCase.recordId));
455
458
  const stranger = recordIds.find((recordId) => !known.has(recordId));
456
459
  if (stranger) throw httpError(404, 'Patient case not found for this patient');
@@ -796,7 +799,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
796
799
  const operator = requiredText(updatedBy, 'updatedBy');
797
800
  if (!Array.isArray(patientCaseRecordIds)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
798
801
  const current = await loadReview(reviewId);
799
- if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
802
+ if (!CASE_SELECTABLE_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
800
803
 
801
804
  const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
802
805
  const casesChanged = {
@@ -814,7 +817,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
814
817
  };
815
818
  const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
816
819
 
817
- const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
820
+ const review = await updateReview(reviewId, CASE_SELECTABLE_STATUSES, [{
818
821
  $set: {
819
822
  patientCaseRecordIds: recordIds,
820
823
  status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
@@ -835,6 +838,12 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
835
838
  return review;
836
839
  }
837
840
 
841
+ async function listReviewCaseCandidates({ id } = {}) {
842
+ const review = await loadReview(reviewIdOf(id));
843
+ const cases = await readPatientCases(review.patientCode);
844
+ return caseCandidates({ review, cases, linkedIds: caseIdsOf(review) });
845
+ }
846
+
838
847
  async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
839
848
  const reviewId = reviewIdOf(id);
840
849
  const operator = requiredText(loggedBy, 'loggedBy');
@@ -2089,6 +2098,7 @@ module.exports = {
2089
2098
  sendApprovedIndications,
2090
2099
  setAlarmAppliedLevel,
2091
2100
  setReviewCases,
2101
+ listReviewCaseCandidates,
2092
2102
  suggestDraft,
2093
2103
  suggestKeyQuestions,
2094
2104
  confirmNoteFacts,
@@ -158,8 +158,10 @@ async function readTasks(kind, whatsappId) {
158
158
  };
159
159
  }
160
160
 
161
+ const readPatientCases = (code) => readAllTasks('cases', validWhatsappId(code));
162
+
161
163
  async function openCaseIds(code) {
162
- const cases = await readAllTasks('cases', validWhatsappId(code));
164
+ const cases = await readPatientCases(code);
163
165
  return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
164
166
  }
165
167
 
@@ -212,6 +214,7 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
212
214
  module.exports = {
213
215
  MAX_NOTE_LENGTH,
214
216
  openCaseIds,
217
+ readPatientCases,
215
218
  getPatientTasks,
216
219
  updatePatientTask,
217
220
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.5",
3
+ "version": "5.72.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",