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

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,9 +1,19 @@
1
1
  const runtimeConfig = require('../../config/runtimeConfig');
2
2
 
3
+ const DEFAULT_TIMEOUT_MS = 8000;
4
+ const MAX_TIMEOUT_MS = 60000;
5
+
3
6
  function clinicalPatternFloorLive() {
4
7
  return String(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
5
8
  }
6
9
 
10
+ function clinicalPatternFloorTimeoutMs() {
11
+ const value = Number(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_TIMEOUT_MS', DEFAULT_TIMEOUT_MS));
12
+ if (!Number.isFinite(value) || value <= 0) return DEFAULT_TIMEOUT_MS;
13
+ return Math.min(value, MAX_TIMEOUT_MS);
14
+ }
15
+
7
16
  module.exports = {
8
17
  clinicalPatternFloorLive,
18
+ clinicalPatternFloorTimeoutMs,
9
19
  };
@@ -3,14 +3,16 @@ const { requireGatewayProvider } = require('../config/llmConfig');
3
3
  const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
4
4
  const { buildExposureBlock } = require('../helpers/triageCaseBaseHelper');
5
5
  const { readStructuredText } = require('../helpers/structuredTextHelper');
6
+ const { clinicalPatternFloorTimeoutMs } = require('../flags/clinicalPatternFloorFlags');
7
+ const { cleanText } = require('../../fhir/helpers/triagePayloadHelper');
6
8
  const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
7
9
  const { logger } = require('../../utils/logger');
10
+ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
11
+ const { withTimeout } = require('../../utils/timeoutUtils');
8
12
 
9
13
  const PATTERNS = ['posquirurgico_abdominal', 'toxicidad_gi_quimioterapia', 'toxicidad_gi_inmunoterapia', 'fiebre_quimioterapia'];
10
14
  const FLOOR_LEVELS = ['asap', 'stat'];
11
15
 
12
- const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
13
-
14
16
  function buildPatternInput({ profile, details, justification, today }) {
15
17
  const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
16
18
  const exposure = buildExposureBlock(profile);
@@ -18,11 +20,11 @@ function buildPatternInput({ profile, details, justification, today }) {
18
20
  `Fecha de hoy: ${today}`,
19
21
  '',
20
22
  '## 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
+ `Síntoma: ${cleanText(details.symptom) || 'no especificado'}`,
24
+ `Palabras del paciente: ${cleanText(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
23
25
  `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
+ `Sospecha del agente: ${cleanText(details.suspected_condition) || 'no especificada'}`,
27
+ `Justificación del agente: ${cleanText(justification) || 'no especificada'}`,
26
28
  '',
27
29
  '## Contexto clínico del paciente',
28
30
  JSON.stringify(profile),
@@ -30,37 +32,47 @@ function buildPatternInput({ profile, details, justification, today }) {
30
32
  ].join('\n');
31
33
  }
32
34
 
35
+ async function evaluatePatternFloor({ code, turnId, details, justification, provider, now }) {
36
+ const { presetId } = await getEscalationPatternFloor();
37
+ if (!presetId) {
38
+ logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
39
+ return null;
40
+ }
41
+ const profile = await readClinicalProfile(code);
42
+ if (!profile) {
43
+ logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: profile === undefined ? 'unreadable' : 'missing_or_unparseable' });
44
+ return null;
45
+ }
46
+ const result = await (provider || requireGatewayProvider()).runStructured({
47
+ presetId,
48
+ input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
49
+ metadata: { subAgent: 'escalation-pattern-floor', turnId },
50
+ });
51
+ if (result?.status && result.status !== 'completed') throw new Error(`pattern floor incomplete: status=${result.status}`);
52
+ const parsed = safeParse(readStructuredText(result), null);
53
+ if (!isPlainObject(parsed)) {
54
+ logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
55
+ return null;
56
+ }
57
+ if (parsed.min_level == null && parsed.pattern == null) return null;
58
+ if (!FLOOR_LEVELS.includes(parsed.min_level) || !PATTERNS.includes(parsed.pattern)) {
59
+ logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level or pattern', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
60
+ return null;
61
+ }
62
+ return { level: parsed.min_level, pattern: parsed.pattern, evidence: cleanText(parsed.evidence), reason: cleanText(parsed.reason) };
63
+ }
64
+
33
65
  async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
34
66
  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) };
67
+ return await withTimeout(
68
+ evaluatePatternFloor({ code, turnId, details, justification, provider, now }),
69
+ clinicalPatternFloorTimeoutMs(),
70
+ 'clinical pattern floor',
71
+ );
62
72
  } catch (error) {
63
- logger.error('[clinicalPatternFloor] The clinical pattern check failed', { turnId, error: error.message });
73
+ logger.error('[clinicalPatternFloor] The clinical pattern check failed', {
74
+ turnId, error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')),
75
+ });
64
76
  return null;
65
77
  }
66
78
  }
@@ -1,6 +1,7 @@
1
1
  const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
2
2
  const { triageGateFloorMaxHours } = require('../flags/triageGateFloorFlags');
3
3
  const { logger } = require('../../utils/logger');
4
+ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
4
5
 
5
6
  const HOUR_MS = 60 * 60 * 1000;
6
7
  const LOOKBACK_MS = 24 * HOUR_MS;
@@ -35,7 +36,7 @@ async function activeTriageGateFloor(code, now = new Date()) {
35
36
  maxActionTimeHours: hours,
36
37
  };
37
38
  } catch (error) {
38
- logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message });
39
+ logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')) });
39
40
  return null;
40
41
  }
41
42
  }
@@ -125,6 +125,7 @@ function buildPayloadFromTriageRow(row = {}, { patientCode, triageRecordId, addi
125
125
  }
126
126
 
127
127
  module.exports = {
128
+ cleanText,
128
129
  normalizeAnswerToken,
129
130
  buildTriageResponse,
130
131
  buildPayloadFromTriageRow,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.65.0-dev.11559",
3
+ "version": "5.65.0-dev.11560",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",