@peopl-health/nexus 5.56.17 → 5.56.20

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.
@@ -8,7 +8,12 @@ function isConversationalDraftReuseLive() {
8
8
  return runtimeConfig.get('CONVERSATIONAL_DRAFT_REUSE_ENABLED', 'true') === 'true';
9
9
  }
10
10
 
11
+ function isDeclarationModelCheckLive() {
12
+ return runtimeConfig.get('DECLARATION_MODEL_CHECK_ENABLED', 'true') === 'true';
13
+ }
14
+
11
15
  module.exports = {
12
16
  isConversationalDeclarationLive,
13
17
  isConversationalDraftReuseLive,
18
+ isDeclarationModelCheckLive,
14
19
  };
@@ -38,6 +38,8 @@ const triageRecommendationEventSchema = new mongoose.Schema({
38
38
  droppedComboCount: { type: Number, default: null },
39
39
  rankReordered: { type: Number, default: null },
40
40
  classifierPending: { type: Boolean, default: null },
41
+ classifierOutcome: { type: String, enum: ['ready', 'timeout', 'no_free_text', null], default: null },
42
+ classifierWaitMs: { type: Number, default: null },
41
43
  deniedCardsDropped: { type: Number, default: null },
42
44
  deniedTargetsStripped: { type: Number, default: null },
43
45
  adherenceRecorded: { type: Number, default: null },
@@ -53,10 +53,13 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
53
53
  getExtractor(),
54
54
  ]);
55
55
 
56
- const flags = new Set(detectSafetyFlags(text || '', patterns));
56
+ const regexFlags = detectSafetyFlags(text || '', patterns);
57
+ const flags = new Set(regexFlags);
58
+ const modelFlags = new Set();
59
+ const sources = () => ({ regex: [...regexFlags], model: [...modelFlags] });
57
60
 
58
61
  if (!text || !text.trim() || !presetId || !provider?.runStructured) {
59
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
62
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
60
63
  }
61
64
 
62
65
  try {
@@ -81,21 +84,32 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
81
84
  const parsed = safeParse(outputText, null);
82
85
  if (outputText && outputText.trim() && parsed === null) {
83
86
  logger.warn('[clinicalExtraction] model output did not parse as JSON; no mentions extracted', { turnId });
84
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
87
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
85
88
  }
86
- const rawMentions = Array.isArray(parsed?.mentions) ? parsed.mentions : [];
89
+ const wellFormed = Array.isArray(parsed?.mentions);
90
+ const rawMentions = wellFormed ? parsed.mentions : [];
87
91
 
88
92
  const now = new Date().toISOString();
89
93
  const clinicalMentions = [];
90
94
  const pendingMentions = [];
91
95
  let unanchored = 0;
96
+ let unusable = 0;
92
97
  let forcedPending = 0;
93
98
  rawMentions.forEach((raw, index) => {
94
- if (!raw || typeof raw !== 'object') return;
95
- for (const f of raw.safety_flags || []) flags.add(f);
99
+ if (!raw || typeof raw !== 'object') {
100
+ unusable += 1;
101
+ return;
102
+ }
103
+ for (const f of raw.safety_flags || []) {
104
+ flags.add(f);
105
+ modelFlags.add(f);
106
+ }
96
107
  const options = { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm };
97
108
  let mention = toClinicalMention(raw, options);
98
- if (!mention) return;
109
+ if (!mention) {
110
+ unusable += 1;
111
+ return;
112
+ }
99
113
  const quotes = mention.provenance.verbatimQuotes;
100
114
  if (!quotes.some((quote) => isQuoteAnchored(quote, text))) {
101
115
  unanchored += 1;
@@ -136,10 +150,13 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
136
150
  pendingMentions,
137
151
  askAgenda: buildAskAgenda({ pendingMentions, contextGaps, safetyFlags: [...flags] }),
138
152
  safetyFlags: [...flags],
153
+ safetyFlagSources: sources(),
154
+ wellFormed,
155
+ discardedMentions: unanchored + unusable,
139
156
  };
140
157
  } catch (err) {
141
158
  logger.error('[clinicalExtraction] extraction failed; returning deterministic safety flags only', { turnId, error: err?.message });
142
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
159
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
143
160
  }
144
161
  }
145
162
 
@@ -72,6 +72,9 @@ const GATE_MAX_ATTEMPTS = 2;
72
72
  const PLAN_MAX_ATTEMPTS = 2;
73
73
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
74
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
75
+ const DEFAULT_CLASSIFIER_WAIT_MS = [15000, 30000, 45000, 60000, 90000];
76
+ const CLASSIFIER_WINDOW_MS = 4 * 60 * 1000;
77
+ const DEFAULT_CLASSIFIER_DEADLINE_MS = 5 * 60 * 1000;
75
78
  const RAW_EXCERPT_MAX = 2000;
76
79
  const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
77
80
  const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
@@ -247,15 +250,20 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
247
250
  const code = payload.patientCode;
248
251
  const settle = { runId: rid };
249
252
 
250
- const classifier = await readFreeTextDerivedSymptoms(payload.triageRecordId, code);
253
+ const catalog = getCatalog();
254
+ const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
255
+ settle.unmappedAnswerCount = unmappedQuestionIds.length;
256
+
257
+ const hasFreeText = Boolean(triageResponse.otherSymptomsText || triageResponse.otherSymptomsNotProctcae.length
258
+ || triageResponse.pain?.otherText);
259
+ const classifier = await awaitFreeTextClassifier(payload.triageRecordId, code, { hasFreeText });
251
260
  if (classifier === null) {
252
261
  return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
253
262
  }
254
263
  const freeTextDerivedSymptoms = classifier.terms;
255
264
  settle.classifierPending = classifier.pending;
256
- const catalog = getCatalog();
257
- const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
258
- settle.unmappedAnswerCount = unmappedQuestionIds.length;
265
+ settle.classifierOutcome = classifier.outcome;
266
+ settle.classifierWaitMs = classifier.waitMs;
259
267
 
260
268
  let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
261
269
  let supportPromise;
@@ -536,7 +544,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
536
544
  affirmedKeys: reportedKeys,
537
545
  riskAssessment,
538
546
  riskReadFailed: riskRead.failed,
539
- freeTextPending: settle.classifierPending === true && freeTextBits.length > 0,
547
+ freeTextPending: classifier.outcome === 'timeout',
540
548
  };
541
549
 
542
550
  supportContext = { ...supportContext, case: casoBaseFor('support-routing') };
@@ -961,13 +969,47 @@ function stripOtcOffers(elements, repairs) {
961
969
 
962
970
  // auna calls handleTriageCompleted directly, so the classifier's rows are resolved here rather
963
971
  // than in the controller: 989 of 1002 production runs never pass through it.
972
+ async function awaitFreeTextClassifier(triageRecordId, code, { hasFreeText }) {
973
+ const startedAt = Date.now();
974
+ let read = await readFreeTextDerivedSymptoms(triageRecordId, code);
975
+ if (!hasFreeText) return read && { ...read, outcome: 'no_free_text', waitMs: 0 };
976
+ const schedule = backoffSchedule('TRIAGE_CLASSIFIER_WAIT_MS', DEFAULT_CLASSIFIER_WAIT_MS);
977
+ const deadlineMs = Number(runtimeConfig.get('TRIAGE_CLASSIFIER_DEADLINE_MS')) || DEFAULT_CLASSIFIER_DEADLINE_MS;
978
+ for (let tries = 0; read && !classifierSettled(read) && tries < schedule.length; tries += 1) {
979
+ if (Date.now() - startedAt + schedule[tries] > deadlineMs) break;
980
+ await sleep(schedule[tries], { keepAlive: true });
981
+ try {
982
+ read = await readFreeTextDerivedSymptoms(triageRecordId, code);
983
+ } catch (err) {
984
+ logger.warn('[triageRecommendation] free-text classifier re-read failed; keeping the last read', {
985
+ code, triageRecordId, error: err?.message,
986
+ });
987
+ }
988
+ }
989
+ if (!read) return read;
990
+ const outcome = classifierSettled(read) ? 'ready' : 'timeout';
991
+ if (outcome === 'timeout') {
992
+ logger.warn('[triageRecommendation] free-text classifier did not settle; cards built without its symptoms', {
993
+ code, triageRecordId, pending: read.pending, derived: read.derived,
994
+ });
995
+ }
996
+ return { ...read, outcome, waitMs: Date.now() - startedAt };
997
+ }
998
+
999
+ function classifierSettled(read) {
1000
+ if (read.pending !== false) return false;
1001
+ if (read.derived > 0) return true;
1002
+ const createdMs = Date.parse(read.createdAt || '');
1003
+ return !Number.isFinite(createdMs) || Date.now() - createdMs >= CLASSIFIER_WINDOW_MS;
1004
+ }
1005
+
964
1006
  async function readFreeTextDerivedSymptoms(triageRecordId, code) {
965
- if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null };
1007
+ if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null, derived: 0, createdAt: null };
966
1008
  const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${triageRecordId}'`);
967
1009
  const row = Array.isArray(rows) ? rows[0] : rows;
968
1010
  if (!row) {
969
1011
  logger.warn('[triageRecommendation] triage row unreadable; no classifier anchors', { code, triageRecordId });
970
- return { terms: [], pending: null };
1012
+ return { terms: [], pending: null, derived: 0, createdAt: null };
971
1013
  }
972
1014
  const owner = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
973
1015
  if (owner && owner !== code) {
@@ -976,19 +1018,18 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
976
1018
  }
977
1019
  // The classifier writes its rows ~96 s after the triage: an unfinished one is not an empty one.
978
1020
  const pending = row.symptoms_processed !== true;
1021
+ const createdAt = row.Created || null;
979
1022
  const ids = (Array.isArray(row.symptoms) ? row.symptoms : []).filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
980
- if (!ids.length) {
981
- if (pending) logger.warn('[triageRecommendation] classifier had not finished; free-text symptoms unavailable', { code, triageRecordId });
982
- return { terms: [], pending };
983
- }
1023
+ if (!ids.length) return { terms: [], pending, derived: 0, createdAt };
984
1024
  const formula = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
985
1025
  const symptoms = await getRecordByFilter(Symptoms_ID, 'symptoms', formula, null, FREE_TEXT_SYMPTOM_FIELDS, true);
986
- const terms = (Array.isArray(symptoms) ? symptoms : [])
987
- .filter((symptom) => symptom.freetext_derived === true && Number(symptom.grade_num) >= 1)
1026
+ const derived = (Array.isArray(symptoms) ? symptoms : []).filter((symptom) => symptom.freetext_derived === true);
1027
+ const terms = derived
1028
+ .filter((symptom) => Number(symptom.grade_num) >= 1)
988
1029
  .map((symptom) => (Array.isArray(symptom.corresponding_CTCAE) ? symptom.corresponding_CTCAE[0] : symptom.corresponding_CTCAE))
989
1030
  .map((term) => String(term ?? '').trim())
990
1031
  .filter(Boolean);
991
- return { terms, pending };
1032
+ return { terms, pending, derived: derived.length, createdAt };
992
1033
  }
993
1034
 
994
1035
  async function readPriorResolutions(adherence = [], patientRecordId = null) {
@@ -6,7 +6,7 @@ const { projectClinicalFacts, renderClinicalIntakeSummary } = require('../helper
6
6
  const { extractClinicalMentions, getConversationalTokens } = require('../services/clinicalExtractionService');
7
7
  const { recordClinicalIntake } = require('../services/clinicalAirtableService');
8
8
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
9
- const { isConversationalDeclarationLive } = require('../flags/turnEfficiencyFlags');
9
+ const { isConversationalDeclarationLive, isDeclarationModelCheckLive } = require('../flags/turnEfficiencyFlags');
10
10
  const { logger } = require('../../utils/logger');
11
11
 
12
12
  const DETECTED_TAG_ENUM = [
@@ -15,6 +15,7 @@ const DETECTED_TAG_ENUM = [
15
15
  ];
16
16
  const NON_CLINICAL_REQUESTS = ['external_booking'];
17
17
  const CONVERSATIONAL_REQUEST = 'conversational';
18
+ const CATEGORIES_A_DECLARATION_CARRIES = { external_booking: ['appointment'] };
18
19
 
19
20
  function declarableRequests() {
20
21
  return isConversationalDeclarationLive() ? [...NON_CLINICAL_REQUESTS, CONVERSATIONAL_REQUEST] : NON_CLINICAL_REQUESTS;
@@ -150,9 +151,19 @@ async function handler(args, context = {}) {
150
151
  if (declaredRequest && trace?.signals?.clinicalFactsExtracted) {
151
152
  return JSON.stringify({ success: false, error: 'This turn already extracted clinical facts, so it cannot be declared a non-clinical request. Continue the clinical workflow those facts require.' });
152
153
  }
154
+ if (declaredRequest && isDeclarationModelCheckLive()) {
155
+ return declareNonClinical({ declaredRequest, rawMessage, intakeSource, priorTurns, runtime, trace });
156
+ }
153
157
  const scannedFlags = await scanSafetyFlags(rawMessage);
154
158
  const safetyFlags = scannedFlags || [];
155
- if (trace?.setSignals) trace.setSignals({ clinicalIntakeCompleted: false, clinicalMentions: [], safetyFlags });
159
+ if (trace?.setSignals) {
160
+ trace.setSignals({
161
+ clinicalIntakeCompleted: false,
162
+ clinicalMentions: [],
163
+ safetyFlags,
164
+ safetyFlagSources: scannedFlags ? { regex: scannedFlags, model: [] } : null,
165
+ });
166
+ }
156
167
 
157
168
  const providerDecision = trace?.signals?.clinicalIntakeDecisionRequired;
158
169
  let conversationalInbound = providerDecision === false;
@@ -203,7 +214,7 @@ async function handler(args, context = {}) {
203
214
  provider: requireGatewayProvider(),
204
215
  trace,
205
216
  });
206
- const { clinicalMentions, safetyFlags, askAgenda = null } = extraction;
217
+ const { clinicalMentions, safetyFlags, safetyFlagSources = null, askAgenda = null } = extraction;
207
218
  const pendingMentions = extraction.pendingMentions || [];
208
219
  const intakeCompleted = extraction.completed !== false;
209
220
 
@@ -212,6 +223,7 @@ async function handler(args, context = {}) {
212
223
  clinicalIntakeCompleted: intakeCompleted,
213
224
  clinicalMentions: [...clinicalMentions, ...pendingMentions],
214
225
  safetyFlags,
226
+ safetyFlagSources,
215
227
  ...(clinicalMentions.length || pendingMentions.length ? { clinicalFactsExtracted: true } : {}),
216
228
  });
217
229
  } else {
@@ -256,6 +268,58 @@ async function handler(args, context = {}) {
256
268
  return JSON.stringify(envelope);
257
269
  }
258
270
 
271
+ async function declareNonClinical({ declaredRequest, rawMessage, intakeSource, priorTurns, runtime, trace }) {
272
+ let check = null;
273
+ if (runtime?.turnId && runtime?.patientCode) {
274
+ try {
275
+ check = await extractClinicalMentions({
276
+ text: rawMessage,
277
+ detectedTags: DETECTED_TAG_ENUM,
278
+ intakeSource,
279
+ priorTurns,
280
+ turnId: runtime.turnId,
281
+ code: runtime.patientCode,
282
+ provider: requireGatewayProvider(),
283
+ trace,
284
+ persist: false,
285
+ });
286
+ } catch (err) {
287
+ logger.warn('[extractClinicalInfo] declaration check failed; refusing the declaration', { turnId: runtime?.turnId, error: err?.message });
288
+ }
289
+ }
290
+ const carried = CATEGORIES_A_DECLARATION_CARRIES[declaredRequest] || [];
291
+ const usable = check?.completed && check.wellFormed === true && !check.discardedMentions;
292
+ const found = usable
293
+ ? [...(check.clinicalMentions || []), ...(check.pendingMentions || [])].filter((mention) => !carried.includes(mention.fact?.category))
294
+ : null;
295
+ const safetyFlags = check?.safetyFlags || [];
296
+ const categories = found ? [...new Set(found.map((mention) => mention.fact?.category).filter(Boolean))] : [];
297
+ trace?.setSignals?.({
298
+ declarationCheck: { request: declaredRequest, completed: Boolean(usable), categories, safetyFlags },
299
+ safetyFlagSources: check?.safetyFlagSources || null,
300
+ });
301
+
302
+ if (found && !found.length && !safetyFlags.length) {
303
+ trace?.setSignals?.({ clinicalIntakeCompleted: true, clinicalMentions: [], safetyFlags: [] });
304
+ return JSON.stringify({
305
+ success: true,
306
+ data: { degraded: false, non_clinical_request: declaredRequest, clinical_facts: [] },
307
+ });
308
+ }
309
+
310
+ trace?.setSignals?.({ clinicalIntakeCompleted: false, clinicalMentions: [], safetyFlags });
311
+ const supported = [...SUPPORTED_TAGS].sort();
312
+ const reason = found
313
+ ? `the clinical check found content in it (${[...categories, ...safetyFlags].join(', ')})`
314
+ : 'the clinical check could not run';
315
+ return JSON.stringify({
316
+ success: false,
317
+ error: `This message cannot be declared a non-clinical request: ${reason}. Re-call extractClinicalInfo with every applicable supported tag (${supported.join(', ')}).`,
318
+ supported_tags: supported,
319
+ received_tags: [],
320
+ });
321
+ }
322
+
259
323
  async function scanSafetyFlags(text) {
260
324
  try {
261
325
  const patterns = await getSafetyFlagPatterns();
@@ -240,17 +240,17 @@ async function sweepColdUnansweredInbound({
240
240
  }
241
241
  }
242
242
 
243
- if (!waiting.length) return { waiting: 0, alerted: 0 };
244
-
245
243
  waiting.sort((a, b) => new Date(a.inbound.createdAt) - new Date(b.inbound.createdAt));
246
244
 
247
245
  if (mode === 'report') {
248
- logger.error('[inboundRecovery] patients have been waiting since long before this sweep looked', {
249
- waiting: waiting.length, oldest: waiting[0].inbound.createdAt, atCeiling, mode,
246
+ logger.error('[inboundRecovery] counted the patients waiting far longer than the live pass looks', {
247
+ waiting: waiting.length, oldest: waiting[0]?.inbound?.createdAt ?? null, atCeiling, mode,
250
248
  });
251
249
  return { waiting: waiting.length, alerted: 0 };
252
250
  }
253
251
 
252
+ if (!waiting.length) return { waiting: 0, alerted: 0 };
253
+
254
254
  let alerted = 0;
255
255
  for (const { code, inbound } of waiting) {
256
256
  if (alerted >= COLD_TICKETS_PER_PASS) break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.17",
3
+ "version": "5.56.20",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",