@peopl-health/nexus 5.64.0 → 5.65.0-dev.11559

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.
@@ -19,6 +19,7 @@ const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
19
19
  const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
20
20
  const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
21
21
  const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
22
+ const ESCALATION_PATTERN_FLOOR_DEFAULTS = { presetId: '' };
22
23
 
23
24
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
24
25
 
@@ -74,7 +75,12 @@ async function load() {
74
75
  if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
75
76
  const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
76
77
 
77
- const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
78
+ const parsedPatternFloor = safeParse(byKey.ESCALATION_PATTERN_FLOOR, null);
79
+ const isPatternFloorValid = !byKey.ESCALATION_PATTERN_FLOOR || isPlainObject(parsedPatternFloor);
80
+ if (!isPatternFloorValid) logger.error('[subAgentsConfig] ESCALATION_PATTERN_FLOOR is not a JSON object; the clinical pattern floor stays unconfigured');
81
+ const escalationPatternFloor = { ...ESCALATION_PATTERN_FLOOR_DEFAULTS, ...(isPatternFloorValid ? parsedPatternFloor || {} : {}) };
82
+
83
+ const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight, ESCALATION_PATTERN_FLOOR: escalationPatternFloor };
78
84
  cache.set(CACHE_KEY, config);
79
85
  return config;
80
86
  }
@@ -94,4 +100,5 @@ module.exports = {
94
100
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
95
101
  getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
96
102
  getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
103
+ getEscalationPatternFloor: () => get('ESCALATION_PATTERN_FLOOR'),
97
104
  };
@@ -0,0 +1,9 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ function clinicalPatternFloorLive() {
4
+ return String(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
5
+ }
6
+
7
+ module.exports = {
8
+ clinicalPatternFloorLive,
9
+ };
@@ -0,0 +1,17 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ const DEFAULT_MAX_HOURS = 6;
4
+
5
+ function triageGateFloorLive() {
6
+ return String(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
7
+ }
8
+
9
+ function triageGateFloorMaxHours() {
10
+ const value = Number(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_MAX_HOURS', DEFAULT_MAX_HOURS));
11
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_HOURS;
12
+ }
13
+
14
+ module.exports = {
15
+ triageGateFloorLive,
16
+ triageGateFloorMaxHours,
17
+ };
@@ -15,6 +15,8 @@ const triageRecommendationEventSchema = new mongoose.Schema({
15
15
  elementCount: { type: Number, default: null },
16
16
  urgentUnder24h: { type: Boolean, default: null },
17
17
  escalationRoute: { type: String, default: null },
18
+ maxActionTimeHours: { type: Number, default: null },
19
+ triageAuthoredAt: { type: Date, default: null },
18
20
  autoRepairs: { type: [String], default: [] },
19
21
  hardRejectIssues: { type: [mongoose.Schema.Types.Mixed], default: [] },
20
22
  rejectedGate: {
@@ -0,0 +1,68 @@
1
+ const { getEscalationPatternFloor } = require('../config/subAgentsConfig');
2
+ const { requireGatewayProvider } = require('../config/llmConfig');
3
+ const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
4
+ const { buildExposureBlock } = require('../helpers/triageCaseBaseHelper');
5
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
6
+ const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
7
+ const { logger } = require('../../utils/logger');
8
+
9
+ const PATTERNS = ['posquirurgico_abdominal', 'toxicidad_gi_quimioterapia', 'toxicidad_gi_inmunoterapia', 'fiebre_quimioterapia'];
10
+ const FLOOR_LEVELS = ['asap', 'stat'];
11
+
12
+ const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
13
+
14
+ function buildPatternInput({ profile, details, justification, today }) {
15
+ const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
16
+ const exposure = buildExposureBlock(profile);
17
+ return [
18
+ `Fecha de hoy: ${today}`,
19
+ '',
20
+ '## Escalación que el agente está registrando',
21
+ `Síntoma: ${text(details.symptom) || 'no especificado'}`,
22
+ `Palabras del paciente: ${text(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
23
+ `Indicadores: ${indicators.length ? indicators.join('; ') : 'ninguno'}`,
24
+ `Sospecha del agente: ${text(details.suspected_condition) || 'no especificada'}`,
25
+ `Justificación del agente: ${text(justification) || 'no especificada'}`,
26
+ '',
27
+ '## Contexto clínico del paciente',
28
+ JSON.stringify(profile),
29
+ ...(exposure ? ['', '## Exposición antineoplásica y medicación documentadas', exposure] : []),
30
+ ].join('\n');
31
+ }
32
+
33
+ async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
34
+ try {
35
+ const { presetId } = await getEscalationPatternFloor();
36
+ if (!presetId) {
37
+ logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
38
+ return null;
39
+ }
40
+ const profile = await readClinicalProfile(code);
41
+ if (!profile) {
42
+ logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: profile === undefined ? 'unreadable' : 'missing_or_unparseable' });
43
+ return null;
44
+ }
45
+ const result = await (provider || requireGatewayProvider()).runStructured({
46
+ presetId,
47
+ input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
48
+ metadata: { subAgent: 'escalation-pattern-floor', turnId },
49
+ });
50
+ if (result?.status && result.status !== 'completed') throw new Error(`pattern floor incomplete: status=${result.status}`);
51
+ const parsed = safeParse(readStructuredText(result), null);
52
+ if (!isPlainObject(parsed)) {
53
+ logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
54
+ return null;
55
+ }
56
+ if (parsed.min_level == null && parsed.pattern == null) return null;
57
+ if (!FLOOR_LEVELS.includes(parsed.min_level) || !PATTERNS.includes(parsed.pattern)) {
58
+ logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level or pattern', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
59
+ return null;
60
+ }
61
+ return { level: parsed.min_level, pattern: parsed.pattern, evidence: text(parsed.evidence), reason: text(parsed.reason) };
62
+ } catch (error) {
63
+ logger.error('[clinicalPatternFloor] The clinical pattern check failed', { turnId, error: error.message });
64
+ return null;
65
+ }
66
+ }
67
+
68
+ module.exports = { clinicalPatternFloor, buildPatternInput, PATTERNS };
@@ -0,0 +1,43 @@
1
+ const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
2
+ const { triageGateFloorMaxHours } = require('../flags/triageGateFloorFlags');
3
+ const { logger } = require('../../utils/logger');
4
+
5
+ const HOUR_MS = 60 * 60 * 1000;
6
+ const LOOKBACK_MS = 24 * HOUR_MS;
7
+ const FLOOR_LEVEL = 'asap';
8
+ const PROMPT_ROUTES = ['urgencias', 'emergencia'];
9
+
10
+ const settledAt = (event) => new Date(event.createdAt).getTime();
11
+ const gateTime = (event) => Math.min(new Date(event.triageAuthoredAt || event.createdAt).getTime(), settledAt(event));
12
+
13
+ async function activeTriageGateFloor(code, now = new Date()) {
14
+ try {
15
+ const gates = await getTriageRecommendationEventModel()
16
+ .find({ patientCode: code, gateVerdict: { $ne: null }, createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } })
17
+ .select('runId triageRecordId urgentUnder24h escalationRoute maxActionTimeHours triageAuthoredAt createdAt')
18
+ .lean();
19
+ const latest = gates.reduce((best, event) => (!best || gateTime(event) > gateTime(best)
20
+ || (gateTime(event) === gateTime(best) && settledAt(event) > settledAt(best)) ? event : best), null);
21
+ if (!latest?.urgentUnder24h) return null;
22
+
23
+ const hours = Number.isFinite(latest.maxActionTimeHours) ? latest.maxActionTimeHours : null;
24
+ const promptRoute = PROMPT_ROUTES.includes(latest.escalationRoute);
25
+ if (!promptRoute && (hours === null || hours > triageGateFloorMaxHours())) return null;
26
+
27
+ const windowMs = (hours ?? 24) * HOUR_MS;
28
+ if (now.getTime() - gateTime(latest) > windowMs) return null;
29
+
30
+ return {
31
+ level: FLOOR_LEVEL,
32
+ runId: latest.runId,
33
+ triageRecordId: latest.triageRecordId,
34
+ escalationRoute: latest.escalationRoute,
35
+ maxActionTimeHours: hours,
36
+ };
37
+ } catch (error) {
38
+ logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message });
39
+ return null;
40
+ }
41
+ }
42
+
43
+ module.exports = { activeTriageGateFloor };
@@ -575,6 +575,8 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
575
575
  settle.gateVerdict = gate.urgentUnder24h ? 'urgent' : 'clear';
576
576
  settle.urgentUnder24h = gate.urgentUnder24h;
577
577
  settle.escalationRoute = gate.escalationRoute;
578
+ settle.maxActionTimeHours = gate.maxActionTimeHours;
579
+ settle.triageAuthoredAt = payload.authored || null;
578
580
  settle.qualityWarnings = gateWarnings;
579
581
  settle.supportSafetyCleared = !gate.urgentUnder24h
580
582
  && gate.redFlags.every((flag) => flag.verificationStatus === 'denied');
@@ -7,7 +7,11 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
7
7
  const { dispatcherService } = require('../services/dispatcherService');
8
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
+ const { activeTriageGateFloor } = require('../services/triageGateFloorService');
11
+ const { clinicalPatternFloor } = require('../services/clinicalPatternFloorService');
10
12
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
13
+ const { triageGateFloorLive } = require('../flags/triageGateFloorFlags');
14
+ const { clinicalPatternFloorLive } = require('../flags/clinicalPatternFloorFlags');
11
15
  const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
16
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
17
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
@@ -308,8 +312,16 @@ async function handler(args, context = {}) {
308
312
  : null;
309
313
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
310
314
  const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
311
- const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
312
- const raisesOpen = !anchor || (URGENCY_RANK[requestedLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
315
+ const agentLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
316
+ const gateFloor = triageGateFloorLive() && runtime.patientCode ? await activeTriageGateFloor(runtime.patientCode) : null;
317
+ const raisedByGate = Boolean(gateFloor) && (URGENCY_RANK[gateFloor.level] || 0) > (URGENCY_RANK[agentLevel] || 0);
318
+ const flooredLevel = raisedByGate ? gateFloor.level : agentLevel;
319
+ const patternFloor = clinicalPatternFloorLive() && runtime.patientCode && (URGENCY_RANK[flooredLevel] || 0) < URGENCY_RANK.stat
320
+ ? await clinicalPatternFloor({ code: runtime.patientCode, turnId: runtime.turnId, details, justification: args?.urgency_justification })
321
+ : null;
322
+ const raisedByPattern = Boolean(patternFloor) && (URGENCY_RANK[patternFloor.level] || 0) > (URGENCY_RANK[flooredLevel] || 0);
323
+ const urgencyLevel = raisedByPattern ? patternFloor.level : flooredLevel;
324
+ const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
313
325
 
314
326
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
315
327
  trace.setSignals({
@@ -331,6 +343,8 @@ async function handler(args, context = {}) {
331
343
  detailsArg,
332
344
  ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
333
345
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
346
+ ...(gateFloor ? { triageGateFloor: { ...gateFloor, raised: raisedByGate } } : {}),
347
+ ...(patternFloor ? { clinicalPatternFloor: { ...patternFloor, raised: raisedByPattern } } : {}),
334
348
  },
335
349
  });
336
350
 
@@ -372,7 +386,9 @@ async function handler(args, context = {}) {
372
386
  recommendedAction: details.recommended_action || '',
373
387
  urgencyFhir: urgencyLevel,
374
388
  documentation: [
375
- keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
389
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${agentLevel}.` : '',
390
+ raisedByGate ? `Piso del triaje: el gate de seguridad pidió acción en ${gateFloor.maxActionTimeHours ?? '<24'} h (${gateFloor.escalationRoute}); se aplica ${flooredLevel} aunque el bot sugirió ${agentLevel}.` : '',
391
+ raisedByPattern ? `Piso clínico (${patternFloor.pattern}): ${patternFloor.reason || 'patrón de riesgo cumplido'}; se aplica ${urgencyLevel} en lugar de ${flooredLevel}${raisedByGate ? ' (nivel ya elevado por el triaje)' : ''}.` : '',
376
392
  args?.urgency_justification || '',
377
393
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
378
394
  assessmentNote(clinicalAssessment),
@@ -381,24 +397,26 @@ async function handler(args, context = {}) {
381
397
  keepOpenRow: keptOpenLevel,
382
398
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
383
399
  });
384
- if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId });
385
- try {
386
- const net = queued ? await armEscalationNet({
387
- patientCode: runtime.patientCode,
388
- urgencyLevel,
389
- symptom: details.symptom || '',
390
- suspectedCondition: details.suspected_condition || null,
391
- checkIn: args?.patient_check_in || null,
392
- trace,
393
- isLive: runtime.isLive?.bind(runtime),
394
- }) : { armed: false, reason: 'emergency_row_not_recorded' };
395
- netArmed = Boolean(net?.armed);
396
- netReason = netArmed ? null : (net?.reason || 'unknown');
397
- logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
398
- } catch (netErr) {
399
- netArmed = false;
400
- netReason = 'arm_failed';
401
- logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
400
+ if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
401
+ if (agentLevel !== 'routine') {
402
+ try {
403
+ const net = queued ? await armEscalationNet({
404
+ patientCode: runtime.patientCode,
405
+ urgencyLevel: agentLevel,
406
+ symptom: details.symptom || '',
407
+ suspectedCondition: details.suspected_condition || null,
408
+ checkIn: args?.patient_check_in || null,
409
+ trace,
410
+ isLive: runtime.isLive?.bind(runtime),
411
+ }) : { armed: false, reason: 'emergency_row_not_recorded' };
412
+ netArmed = Boolean(net?.armed);
413
+ netReason = netArmed ? null : (net?.reason || 'unknown');
414
+ logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
415
+ } catch (netErr) {
416
+ netArmed = false;
417
+ netReason = 'arm_failed';
418
+ logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
419
+ }
402
420
  }
403
421
  }
404
422
  } else if (urgencyLevel !== 'routine') {
@@ -418,6 +436,16 @@ async function handler(args, context = {}) {
418
436
  follow_up: followUpNote(netArmed, netReason),
419
437
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
420
438
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
439
+ ...(raisedByGate ? {
440
+ raised_by_triage_gate: true,
441
+ requested_urgency_level: requestedLevel,
442
+ triage_gate: { escalation_route: gateFloor.escalationRoute, max_action_time_hours: gateFloor.maxActionTimeHours },
443
+ } : {}),
444
+ ...(raisedByPattern ? {
445
+ raised_by_clinical_pattern: true,
446
+ requested_urgency_level: requestedLevel,
447
+ clinical_pattern: { pattern: patternFloor.pattern, reason: patternFloor.reason },
448
+ } : {}),
421
449
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
422
450
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
423
451
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
@@ -29,6 +29,7 @@ const alarmSchema = new mongoose.Schema({
29
29
  turnId: { type: String, default: null },
30
30
  clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
31
31
  emergencyRecordId: { type: String, default: null },
32
+ appliedLevel: { type: String, default: null },
32
33
  raisedAt: { type: Date, required: true },
33
34
  }, { _id: false });
34
35
 
@@ -549,18 +549,19 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
549
549
  function escalationAnchorOf(review, alarmId) {
550
550
  const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
551
551
  if (!prior.length) return null;
552
- const rankOf = (alarm) => URGENCY_RANK[alarm.urgencyLevel] || 0;
552
+ const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
553
+ const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
553
554
  const topRank = Math.max(...prior.map(rankOf));
554
555
  const top = prior.filter((alarm) => rankOf(alarm) === topRank);
555
556
  const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
556
- return { urgencyLevel: top[0].urgencyLevel, emergencyRecordId: topRow?.emergencyRecordId || null };
557
+ return { urgencyLevel: levelOf(top[0]), emergencyRecordId: topRow?.emergencyRecordId || null };
557
558
  }
558
559
 
559
- async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId }) {
560
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, appliedLevel = null }) {
560
561
  try {
561
562
  await getEscalationReview().updateOne(
562
563
  { _id: reviewId, 'alarms.alarmId': alarmId },
563
- { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId } },
564
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId, 'alarms.$.appliedLevel': appliedLevel } },
564
565
  { timestamps: false },
565
566
  );
566
567
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.64.0",
3
+ "version": "5.65.0-dev.11559",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",