@peopl-health/nexus 5.56.18 → 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
  };
@@ -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
 
@@ -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.18",
3
+ "version": "5.56.20",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",