@peopl-health/nexus 5.55.0-dev.8069 → 5.55.0-dev.8090

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.
@@ -14,6 +14,7 @@ const PATTERN_CONSULT_DEFAULTS = { presetId: '' };
14
14
  const RISK_ASSESSMENT_DEFAULTS = { presetId: '' };
15
15
  const TRIAGE_GATE_DEFAULTS = { presetId: '' };
16
16
  const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
17
+ const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
17
18
 
18
19
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
19
20
 
@@ -51,7 +52,11 @@ async function load() {
51
52
  if (byKey.TRIAGE_PLAN && !isPlainObject(parsedTriagePlan)) throw new Error('subAgents config TRIAGE_PLAN is not a JSON object');
52
53
  const triagePlan = { ...TRIAGE_PLAN_DEFAULTS, ...(parsedTriagePlan || {}) };
53
54
 
54
- const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan };
55
+ const parsedEscalationDraft = safeParse(byKey.ESCALATION_DRAFT, null);
56
+ if (byKey.ESCALATION_DRAFT && !isPlainObject(parsedEscalationDraft)) throw new Error('subAgents config ESCALATION_DRAFT is not a JSON object');
57
+ const escalationDraft = { ...ESCALATION_DRAFT_DEFAULTS, ...(parsedEscalationDraft || {}) };
58
+
59
+ const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft };
55
60
  cache.set(CACHE_KEY, config);
56
61
  return config;
57
62
  }
@@ -67,4 +72,5 @@ module.exports = {
67
72
  getRiskAssessment: () => get('RISK_ASSESSMENT'),
68
73
  getTriageGate: () => get('TRIAGE_GATE'),
69
74
  getTriagePlan: () => get('TRIAGE_PLAN'),
75
+ getEscalationDraft: () => get('ESCALATION_DRAFT'),
70
76
  };
@@ -1,5 +1,7 @@
1
1
  const { ClinicalMention } = require('../../shared/dtos/ClinicalMention');
2
2
 
3
+ const { readStructuredText } = require('./structuredTextHelper');
4
+
3
5
  function buildExtractorInput(text, detectedTags, curated, template, { priorTurns = null, patientContext = null } = {}) {
4
6
  const priorTurnsPayload = Array.isArray(priorTurns) && priorTurns.length ? { prior_turns: priorTurns } : {};
5
7
  const contextPayload = patientContext ? { patient_context: patientContext } : {};
@@ -15,15 +17,6 @@ function buildExtractorInput(text, detectedTags, curated, template, { priorTurns
15
17
  .replace('{{payload}}', () => payload);
16
18
  }
17
19
 
18
- function readOutputText(result) {
19
- if (result?.output_text) return result.output_text;
20
- const output = Array.isArray(result?.output) ? result.output : [];
21
- const message = output.find((item) => item.type === 'message');
22
- const content = Array.isArray(message?.content) ? message.content : [];
23
- const part = content.find((c) => typeof c?.text === 'string');
24
- return part?.text || '';
25
- }
26
-
27
20
  function toClinicalMention(raw, { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm = {} }) {
28
21
  const rawTerm = (raw.ctcae_term || '').trim().toLowerCase();
29
22
  const ctcaeTerm = !rawTerm || rawTerm === 'other' ? null : rawTerm;
@@ -73,6 +66,5 @@ function deriveCanonicalTerm(raw, ctcaeTerm, spanishByTerm) {
73
66
 
74
67
  module.exports = {
75
68
  buildExtractorInput,
76
- readOutputText,
77
69
  toClinicalMention,
78
70
  };
@@ -3,6 +3,8 @@ const { isDeepStrictEqual } = require('node:util');
3
3
  const divergenceConfig = require('../config/divergenceConfig');
4
4
  const { requireOpenAIProvider } = require('../config/llmConfig');
5
5
 
6
+ const { readStructuredText } = require('./structuredTextHelper');
7
+
6
8
  const VERDICT_SCHEMA = {
7
9
  type: 'object',
8
10
  properties: {
@@ -15,15 +17,6 @@ const VERDICT_SCHEMA = {
15
17
 
16
18
  const ungraded = (rationale) => ({ verdict: 'review', rationale, graded: false });
17
19
 
18
- function readVerdictText(result) {
19
- if (result?.output_text) return result.output_text;
20
- const output = Array.isArray(result?.output) ? result.output : [];
21
- const message = output.find((item) => item.type === 'message');
22
- const content = Array.isArray(message?.content) ? message.content : [];
23
- const part = content.find((c) => typeof c?.text === 'string');
24
- return part?.text || '';
25
- }
26
-
27
20
  const COMPARATORS = {
28
21
  scalar: (expected, actual) => expected === actual,
29
22
  set: (expected, actual) => isDeepStrictEqual(new Set(expected || []), new Set(actual || [])),
@@ -84,7 +77,7 @@ async function stochasticDivergence(expectedMessage, actualMessage) {
84
77
  input: [{ role: 'user', content: `ORIGINAL:\n${expected}\n\nREWRITTEN:\n${actual}` }],
85
78
  text: { format: { type: 'json_schema', name: 'stochastic_verdict', schema: VERDICT_SCHEMA, strict: true } },
86
79
  });
87
- const parsed = JSON.parse(readVerdictText(result));
80
+ const parsed = JSON.parse(readStructuredText(result));
88
81
  const verdict = ['pass', 'review', 'fail'].includes(parsed.verdict) ? parsed.verdict : 'review';
89
82
  return { verdict, rationale: parsed.rationale || '', graded: true };
90
83
  } catch (error) {
@@ -0,0 +1,13 @@
1
+ // Every structured sub-agent reads its text back the same way: the envelope carries output_text
2
+ // when the provider flattened it, and otherwise the text lives in the first message part. Keeping
3
+ // one copy is what stops two services from disagreeing when a provider envelope changes.
4
+ function readStructuredText(result) {
5
+ if (result?.output_text) return result.output_text;
6
+ const output = Array.isArray(result?.output) ? result.output : [];
7
+ const message = output.find((item) => item.type === 'message');
8
+ const content = Array.isArray(message?.content) ? message.content : [];
9
+ const part = content.find((candidate) => typeof candidate?.text === 'string');
10
+ return part?.text || '';
11
+ }
12
+
13
+ module.exports = { readStructuredText };
@@ -0,0 +1,216 @@
1
+ const PROTOCOL_VERSION = '2026-09-18';
2
+
3
+ const MEDICAL_REVIEW = 'valoración médica';
4
+
5
+ function deepFreeze(value) {
6
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
7
+ Object.freeze(value);
8
+ for (const nested of Object.values(value)) deepFreeze(nested);
9
+ }
10
+ return value;
11
+ }
12
+
13
+ const SYMPTOM_RELIEF_PROTOCOL = deepFreeze([
14
+ {
15
+ key: 'nausea_vomito',
16
+ label: 'Náusea y vómito',
17
+ options: [
18
+ { grade: 1, brand: 'AMAL', drug: 'Ondansetrón', strength: '8 mg', instructions: '1 tableta cada 24 horas por 5 días' },
19
+ ],
20
+ },
21
+ {
22
+ key: 'reflujo',
23
+ label: 'Reflujo',
24
+ options: [
25
+ {
26
+ grade: 1,
27
+ brand: null,
28
+ drug: 'Esomeprazol',
29
+ strength: '40 mg',
30
+ instructions: '1 cápsula cada 24 horas por 5 días',
31
+ alternative: {
32
+ when: 'la paciente ya está tomando esomeprazol',
33
+ brand: null,
34
+ drug: 'Famotidina',
35
+ strength: '40 mg',
36
+ instructions: '1 tableta cada 24 horas por 5 días',
37
+ },
38
+ },
39
+ ],
40
+ },
41
+ {
42
+ key: 'diarrea',
43
+ label: 'Diarrea',
44
+ options: [
45
+ {
46
+ grade: 1,
47
+ brand: null,
48
+ drug: 'Loperamida',
49
+ strength: '4 mg',
50
+ instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
51
+ consider: true,
52
+ },
53
+ {
54
+ grade: 2,
55
+ brand: null,
56
+ drug: 'Loperamida',
57
+ strength: '4 mg',
58
+ instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
59
+ ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
60
+ },
61
+ ],
62
+ },
63
+ {
64
+ key: 'dolor_abdominal_colico',
65
+ label: 'Dolor abdominal tipo cólico',
66
+ options: [
67
+ {
68
+ grade: 1,
69
+ brand: 'BUSCAPINA COMPUESTA',
70
+ drug: 'Butilhioscina/Metamizol',
71
+ strength: '10/250 mg',
72
+ instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
73
+ },
74
+ ],
75
+ },
76
+ {
77
+ key: 'estrenimiento',
78
+ label: 'Estreñimiento',
79
+ options: [
80
+ { grade: 1, brand: 'SENOKOT', drug: 'Senósidos', strength: null, instructions: '2 tabletas cada noche por 5 días' },
81
+ {
82
+ grade: 2,
83
+ brand: 'LACTULAX',
84
+ drug: 'Lactulosa',
85
+ strength: null,
86
+ instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
87
+ },
88
+ ],
89
+ },
90
+ {
91
+ key: 'mucositis',
92
+ label: 'Mucositis',
93
+ options: [
94
+ {
95
+ grade: 1,
96
+ brand: null,
97
+ drug: 'Colutorios alcalinos',
98
+ strength: '½ L de agua con 1 cucharadita de sal y 2 cucharaditas de bicarbonato',
99
+ instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
100
+ isPharmacological: false,
101
+ },
102
+ {
103
+ grade: 2,
104
+ brand: 'VELIAN',
105
+ drug: 'Dexketoprofeno',
106
+ strength: '25 mg/10 ml en sobres',
107
+ instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
108
+ escalateIf: `si persiste, ${MEDICAL_REVIEW}`,
109
+ },
110
+ ],
111
+ },
112
+ {
113
+ key: 'dolor',
114
+ label: 'Dolor',
115
+ options: [
116
+ {
117
+ grade: 1,
118
+ brand: 'TEMPRA / TYLENOL',
119
+ drug: 'Paracetamol',
120
+ strength: '750 mg',
121
+ instructions: '1 a 2 tabletas cada 8 horas por razón necesaria, por 5 días',
122
+ },
123
+ {
124
+ grade: 2,
125
+ brand: 'CELEBREX',
126
+ drug: 'Celecoxib',
127
+ strength: '200 mg',
128
+ instructions: '1 cápsula cada 24 horas con alimentos por 5 días',
129
+ steppedUpFromGrade: 1,
130
+ escalateIf: `siempre, ${MEDICAL_REVIEW}`,
131
+ },
132
+ ],
133
+ },
134
+ {
135
+ key: 'neuropatia',
136
+ label: 'Neuropatía',
137
+ alwaysEscalate: MEDICAL_REVIEW,
138
+ recognition: 'ardor, sensación de adormecimiento o piquetes; sigue el trayecto de un nervio, o aparece en manos y pies al mismo tiempo',
139
+ options: [],
140
+ },
141
+ {
142
+ key: 'sindrome_mano_pie',
143
+ label: 'Síndrome mano-pie',
144
+ options: [
145
+ {
146
+ grade: 1,
147
+ brand: 'CERAVE',
148
+ drug: 'Ceramidas',
149
+ strength: null,
150
+ instructions: '2 a 3 veces al día de forma continua',
151
+ isPharmacological: false,
152
+ },
153
+ {
154
+ grade: 2,
155
+ brand: 'NUTRAPLUS',
156
+ drug: 'Urea',
157
+ strength: '10%',
158
+ instructions: 'capa fina cada 12 horas de forma continua',
159
+ },
160
+ ],
161
+ },
162
+ {
163
+ key: 'rinitis_alergia',
164
+ label: 'Rinitis o alergia',
165
+ options: [
166
+ { grade: 1, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
167
+ { grade: 2, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
168
+ ],
169
+ },
170
+ {
171
+ key: 'insomnio',
172
+ label: 'Insomnio',
173
+ options: [
174
+ { grade: 1, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
175
+ { grade: 2, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
176
+ ],
177
+ },
178
+ ]);
179
+
180
+ const byKey = new Map(SYMPTOM_RELIEF_PROTOCOL.map((entry) => [entry.key, entry]));
181
+
182
+ function protocolFor(symptomKey, grade) {
183
+ const entry = byKey.get(String(symptomKey ?? '').trim());
184
+ if (!entry) return null;
185
+
186
+ const option = entry.options.find((candidate) => candidate.grade === grade) ?? null;
187
+ return {
188
+ key: entry.key,
189
+ label: entry.label,
190
+ grade,
191
+ option,
192
+ alwaysEscalate: entry.alwaysEscalate ?? null,
193
+ recognition: entry.recognition ?? null,
194
+ hasNoOptionForGrade: option === null,
195
+ };
196
+ }
197
+
198
+ function protocolExcerpt(symptoms = []) {
199
+ const seen = new Set();
200
+ const excerpt = [];
201
+ for (const { key, grade } of symptoms) {
202
+ const id = `${key}:${grade}`;
203
+ if (seen.has(id)) continue;
204
+ seen.add(id);
205
+ const entry = protocolFor(key, grade);
206
+ if (entry) excerpt.push(entry);
207
+ }
208
+ return excerpt;
209
+ }
210
+
211
+ module.exports = {
212
+ PROTOCOL_VERSION,
213
+ SYMPTOM_RELIEF_PROTOCOL,
214
+ protocolFor,
215
+ protocolExcerpt,
216
+ };
@@ -313,7 +313,7 @@ class AnthropicProvider extends BaseLLMProvider {
313
313
  return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
314
314
  }
315
315
 
316
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, model = null } = {}) {
316
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
317
317
  let modelConfig = {};
318
318
  let resolvedInstructions = instructions;
319
319
  if (promptId || presetId) {
@@ -347,8 +347,11 @@ class AnthropicProvider extends BaseLLMProvider {
347
347
  { providerName: this.constructor.name },
348
348
  )
349
349
  );
350
+ // The Messages API takes no free-form metadata, so the caller's correlation keys can only live
351
+ // in the call audit. Dropping them silently is what leaves a generated call unattributable.
352
+ const callerMetadata = Object.fromEntries(Object.entries(metadata || {}).filter(([, value]) => value != null));
350
353
  void appendCall({
351
- metadata: { source: 'structured', iterationIndex: 0, resolvedPromptId: promptId, resolvedPresetId: presetId },
354
+ metadata: { source: 'structured', iterationIndex: 0, resolvedPromptId: promptId, resolvedPresetId: presetId, ...callerMetadata },
352
355
  request: { messages, config: apiConfig },
353
356
  response: result,
354
357
  durationMs,
@@ -1,7 +1,8 @@
1
1
  const { getSafetyFlagPatterns } = require('../config/divergenceConfig');
2
2
  const { getExtractor } = require('../config/subAgentsConfig');
3
3
  const { detectSafetyFlags } = require('../helpers/safetyFlagsHelper');
4
- const { buildExtractorInput, readOutputText, toClinicalMention } = require('../helpers/clinicalMentionHelper');
4
+ const { buildExtractorInput, toClinicalMention } = require('../helpers/clinicalMentionHelper');
5
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
5
6
  const { isQuoteAnchored } = require('../../utils/textMatchUtils');
6
7
  const { foldAccents } = require('../../utils/formatUtils');
7
8
  const { getClinicalContext } = require('../../helpers/patientInformationHelper');
@@ -76,7 +77,7 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
76
77
 
77
78
  if (result?.status && result.status !== 'completed') throw new Error(`clinical extraction incomplete: status=${result.status}`);
78
79
 
79
- const outputText = readOutputText(result);
80
+ const outputText = readStructuredText(result);
80
81
  const parsed = safeParse(outputText, null);
81
82
  if (outputText && outputText.trim() && parsed === null) {
82
83
  logger.warn('[clinicalExtraction] model output did not parse as JSON; no mentions extracted', { turnId });
@@ -2,7 +2,7 @@ const { withTiming } = require('../../utils/tracingDecorator');
2
2
  const { getComposer } = require('../config/subAgentsConfig');
3
3
  const { getPromptBlocks } = require('../config/composerConfig');
4
4
 
5
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
5
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
6
6
  const { safeParse } = require('../../utils/jsonUtils');
7
7
  const { logger } = require('../../utils/logger');
8
8
 
@@ -56,7 +56,7 @@ async function renderMessage({ intentPayload, provider, trace = null }) {
56
56
  return null;
57
57
  }
58
58
 
59
- const outputText = readOutputText(result);
59
+ const outputText = readStructuredText(result);
60
60
  const parsed = safeParse(outputText, null);
61
61
  if (outputText && outputText.trim() && parsed === null) {
62
62
  logger.warn('[composerService] composer output did not parse as JSON; falling back to legacy message_text', { presetId });
@@ -1,4 +1,5 @@
1
1
  const { createLLMProvider } = require('../providers/createLLMProvider');
2
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
2
3
  const runtimeConfig = require('../../config/runtimeConfig');
3
4
  const { logger } = require('../../utils/logger');
4
5
 
@@ -49,13 +50,6 @@ unsure — you cannot tell which it is.
49
50
  Return one verdict per line. Give the line's number in "line" and quote its value back — not the
50
51
  field — in "value".`;
51
52
 
52
- const readText = (result) => {
53
- if (result?.output_text) return result.output_text;
54
- const output = Array.isArray(result?.output) ? result.output : [];
55
- const content = output.find((item) => item.type === 'message')?.content;
56
- return (Array.isArray(content) ? content.find((part) => typeof part?.text === 'string') : null)?.text || '';
57
- };
58
-
59
53
  const chunk = (values, size) => Array.from(
60
54
  { length: Math.ceil(values.length / size) },
61
55
  (_, i) => values.slice(i * size, (i + 1) * size),
@@ -103,7 +97,7 @@ async function verifyNamesSomething(candidateList) {
103
97
  text: { format: { type: 'json_schema', name: 'names_something', schema: VERDICT_SCHEMA, strict: true } },
104
98
  model: model(),
105
99
  });
106
- for (const verdict of JSON.parse(readText(result))?.verdicts ?? []) {
100
+ for (const verdict of JSON.parse(readStructuredText(result))?.verdicts ?? []) {
107
101
  const line = Number.isInteger(verdict.line) ? verdict.line : 0;
108
102
  const candidate = line >= 1 && line <= batch.length ? batch[line - 1] : null;
109
103
  if (!candidate || candidate.value !== verdict.value) { stats.unmatched += 1; continue; }
@@ -0,0 +1,112 @@
1
+ const { getEscalationDraft } = require('../config/subAgentsConfig');
2
+
3
+ const { PROTOCOL_VERSION, SYMPTOM_RELIEF_PROTOCOL } = require('../protocols/symptomReliefProtocol');
4
+
5
+ const { createLLMProvider } = require('../providers/createLLMProvider');
6
+
7
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
8
+
9
+ const { getEscalationContext } = require('../../services/escalationContextService');
10
+
11
+ const { logger } = require('../../utils/logger');
12
+ const { safeParse } = require('../../utils/jsonUtils');
13
+ const { withTiming } = require('../../utils/tracingDecorator');
14
+
15
+ const CONVERSATION_TURNS = 40;
16
+ const TRIAGE_LIMIT = 3;
17
+ const CALL_LOG_LIMIT = 10;
18
+
19
+ const trimmed = (value) => String(value ?? '').trim();
20
+
21
+ function buildDraftInput({ context, callLogs, protocol }) {
22
+ const conversation = Array.isArray(context?.conversation)
23
+ ? context.conversation.slice(-CONVERSATION_TURNS)
24
+ : context?.conversation ?? null;
25
+
26
+ const triages = Array.isArray(context?.triages)
27
+ ? context.triages.slice(0, TRIAGE_LIMIT)
28
+ : context?.triages ?? null;
29
+
30
+ return {
31
+ protocolVersion: PROTOCOL_VERSION,
32
+ protocol,
33
+ patient: {
34
+ clinicalContext: context?.agentContext ?? null,
35
+ conversation,
36
+ triages,
37
+ carePlan: context?.carePlan ?? null,
38
+ history: context?.history ?? null,
39
+ },
40
+ call: callLogs.slice(-CALL_LOG_LIMIT).map((log) => ({
41
+ outcome: log?.outcome ?? null,
42
+ notes: trimmed(log?.notes) || null,
43
+ calledAt: log?.calledAt ?? null,
44
+ })),
45
+ sectionsUnavailable: context?.degradedSections ?? [],
46
+ };
47
+ }
48
+
49
+ function draftProvider() {
50
+ try {
51
+ return createLLMProvider({ variant: 'anthropic' });
52
+ } catch (error) {
53
+ logger.warn('[escalationDraft] no provider available; not generating', { error: error.message });
54
+ return null;
55
+ }
56
+ }
57
+
58
+ async function generateEscalationDraft({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
59
+ const { presetId } = await getEscalationDraft();
60
+ const llm = provider ?? draftProvider();
61
+
62
+ if (!presetId || !llm?.runStructured) {
63
+ return { completed: false, configured: false, reason: 'escalation draft generation is not configured' };
64
+ }
65
+
66
+ const context = await getEscalationContext({ code, now });
67
+ const input = buildDraftInput({ context, callLogs, protocol: SYMPTOM_RELIEF_PROTOCOL });
68
+
69
+ // Past this point a generation run was issued. Whether the request actually left the process is
70
+ // not knowable here — the provider resolves the preset and validates the schema before it calls
71
+ // its client — so every exit reports `attempted`, meaning a run happened and ended this way, and
72
+ // never that the context was certainly disclosed. Over-recording an attempt is the safe direction
73
+ // for an audit trail; missing a real disclosure is not.
74
+ let result;
75
+ let durationMs;
76
+ try {
77
+ ({ result, durationMs } = await withTiming(() => llm.runStructured({
78
+ presetId,
79
+ input: [{ role: 'user', content: JSON.stringify(input) }],
80
+ metadata: { generator: 'escalation-draft', reviewId: reviewId ?? undefined },
81
+ })));
82
+ } catch (error) {
83
+ logger.error('[escalationDraft] the provider failed', { error: error.message, stack: error.stack, reviewId });
84
+ return { completed: false, attempted: true, reason: 'the model could not be reached' };
85
+ }
86
+ trace?.addSubCall({ response: result, durationMs, presetId });
87
+
88
+ if (result?.status && result.status !== 'completed') {
89
+ logger.warn('[escalationDraft] generation did not complete', { status: result.status, reviewId });
90
+ return { completed: false, attempted: true, reason: `generation incomplete: status=${result.status}` };
91
+ }
92
+
93
+ const parsed = safeParse(readStructuredText(result), null);
94
+ const doctorText = trimmed(parsed?.doctorText);
95
+ const patientMessage = trimmed(parsed?.patientMessage);
96
+
97
+ if (!doctorText || !patientMessage) {
98
+ logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
99
+ return { completed: false, attempted: true, reason: 'the model returned no usable text' };
100
+ }
101
+
102
+ return {
103
+ completed: true,
104
+ attempted: true,
105
+ doctorText,
106
+ patientMessage,
107
+ protocolVersion: PROTOCOL_VERSION,
108
+ sectionsUnavailable: context.degradedSections ?? [],
109
+ };
110
+ }
111
+
112
+ module.exports = { generateEscalationDraft, buildDraftInput };
@@ -2,7 +2,7 @@ const crypto = require('node:crypto');
2
2
 
3
3
  const { getPatternConsult } = require('../config/subAgentsConfig');
4
4
  const { patternConsultStore } = require('../models/patternConsultModel');
5
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
5
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
6
6
  const { safeParse } = require('../../utils/jsonUtils');
7
7
  const { logger } = require('../../utils/logger');
8
8
  const { assembleLandscape } = require('./symptomLandscapeService');
@@ -90,7 +90,7 @@ async function requestPatternConsult({ concern, patientId, turnId, provider }) {
90
90
 
91
91
  if (result?.status && result.status !== 'completed') throw new Error(`pattern consult incomplete: status=${result.status}`);
92
92
 
93
- const outputText = readOutputText(result);
93
+ const outputText = readStructuredText(result);
94
94
  const parsed = safeParse(outputText, null);
95
95
  if (outputText && outputText.trim() && parsed === null) {
96
96
  logger.warn('[patternConsult] model output did not parse as JSON; degraded', { turnId });
@@ -6,7 +6,7 @@ const { requireGatewayProvider } = require('../config/llmConfig');
6
6
  const { getRiskWarmupEventModel } = require('../models/riskWarmupEventModel');
7
7
  const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
8
8
  const { isShadowRun } = require('../helpers/shadowHelper');
9
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
9
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
10
10
  const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
11
11
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
12
12
  const { Follow_Up_ID, Symptoms_ID } = require('../../config/airtableConfig');
@@ -105,7 +105,7 @@ async function assessPatientRisk({ code, provider }) {
105
105
  return { stored: false, reason: 'synthesis_incomplete', trigger };
106
106
  }
107
107
 
108
- const rawOutput = safeParse(readOutputText(result), null);
108
+ const rawOutput = safeParse(readStructuredText(result), null);
109
109
  if (!isPlainObject(rawOutput)) {
110
110
  logger.warn('[riskAssessment] model output did not parse as JSON', { code });
111
111
  return { stored: false, reason: 'malformed_model_output', trigger };
@@ -1,4 +1,4 @@
1
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
1
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
2
2
  const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
3
3
  const { safeParse } = require('../../utils/jsonUtils');
4
4
 
@@ -100,7 +100,7 @@ async function evaluateSupportRouting({ provider, patientId, origin, sourceId, c
100
100
  text: { format: { type: 'json_schema', name: 'support_routing', strict: true, schema: SUPPORT_ROUTING_SCHEMA } },
101
101
  metadata: { subAgent: 'support-routing', sourceId },
102
102
  });
103
- const parsed = safeParse(readOutputText(result), null);
103
+ const parsed = safeParse(readStructuredText(result), null);
104
104
  if (!parsed || !Array.isArray(parsed.decisions)) throw new Error('support routing response malformed');
105
105
  return new SupportRoutingRecommendation({
106
106
  patientId,
@@ -5,7 +5,7 @@ const { requireGatewayProvider } = require('../config/llmConfig');
5
5
  const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
6
6
  const { getSupportCandidateModel } = require('../models/supportCandidateModel');
7
7
  const { isShadowRun } = require('../helpers/shadowHelper');
8
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
8
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
9
9
  const {
10
10
  str, arr, buildRedFlag, normalizeGateEscalation, applyRouteFloor,
11
11
  } = require('../helpers/recommendationGateHelper');
@@ -752,7 +752,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
752
752
  if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_incomplete' } };
753
753
  continue;
754
754
  }
755
- const parsed = safeParse(readOutputText(result), null);
755
+ const parsed = safeParse(readStructuredText(result), null);
756
756
  if (!isPlainObject(parsed)) {
757
757
  if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' } };
758
758
  continue;
@@ -872,7 +872,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
872
872
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
873
873
  continue;
874
874
  }
875
- const parsed = safeParse(readOutputText(result), null);
875
+ const parsed = safeParse(readStructuredText(result), null);
876
876
  firstEvidence = firstEvidence ?? rawEvidence(result);
877
877
  if (!isPlainObject(parsed)) {
878
878
  lastIssues = [{ path: 'plan', problem: 'la respuesta no es un objeto JSON válido' }];
@@ -931,7 +931,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
931
931
  }
932
932
 
933
933
  function rawEvidence(result) {
934
- const text = str(readOutputText(result)).trim();
934
+ const text = str(readStructuredText(result)).trim();
935
935
  if (text) return text.slice(0, RAW_EXCERPT_MAX);
936
936
  try {
937
937
  const raw = JSON.stringify(result?.raw ?? result ?? null);
@@ -12,6 +12,7 @@ const {
12
12
  openEscalationReview,
13
13
  recordDoctorDecision,
14
14
  sendApprovedIndications,
15
+ suggestDraft,
15
16
  syncEscalationReviewCase,
16
17
  } = require('../services/escalationReviewService');
17
18
 
@@ -62,6 +63,16 @@ const addEscalationReviewCallLogController = async (req, res) => {
62
63
  }
63
64
  };
64
65
 
66
+ const suggestEscalationReviewDraftController = async (req, res) => {
67
+ try {
68
+ const { triggeredBy } = req.body || {};
69
+ const draft = await suggestDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
70
+ res.status(200).json({ success: true, draft });
71
+ } catch (error) {
72
+ respondWithError(res, error, 'generating escalation review draft', { reviewId: req.params?.id });
73
+ }
74
+ };
75
+
65
76
  const addEscalationReviewDraftController = async (req, res) => {
66
77
  try {
67
78
  const { doctorText, patientMessage, triggeredBy } = req.body || {};
@@ -171,5 +182,6 @@ module.exports = {
171
182
  openEscalationReviewController,
172
183
  recordEscalationReviewDecisionController,
173
184
  sendEscalationReviewIndicationsController,
185
+ suggestEscalationReviewDraftController,
174
186
  syncEscalationReviewCaseController,
175
187
  };
@@ -121,6 +121,7 @@ const escalationReviewRouteDefinitions = {
121
121
  'GET /by-patient/:code': 'listEscalationReviewsController',
122
122
  'GET /:id': 'getEscalationReviewController',
123
123
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
124
+ 'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
124
125
  'POST /:id/drafts': 'addEscalationReviewDraftController',
125
126
  'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
126
127
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
@@ -281,6 +282,7 @@ const builtInControllers = {
281
282
  listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
282
283
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
283
284
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
285
+ suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
284
286
  addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
285
287
  handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
286
288
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
@@ -16,6 +16,7 @@ const {
16
16
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
17
17
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
18
18
  const { sendMessage } = require('../core/NexusMessaging');
19
+ const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
19
20
 
20
21
  const { getPatientInformation, logPatientChange } = require('./patientService');
21
22
  const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
@@ -357,6 +358,45 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
357
358
  return review;
358
359
  }
359
360
 
361
+ // Generation writes nothing: it fills the two boxes the navigator then edits and saves with addDraft.
362
+ // It is refused outside the statuses that accept a draft, so no one waits on a model for text that
363
+ // the review could no longer keep.
364
+ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
365
+ const reviewId = reviewIdOf(id);
366
+ const operator = requiredText(requestedBy, 'requestedBy');
367
+ const review = await loadReview(reviewId);
368
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
369
+
370
+ const draft = await generateEscalationDraft({
371
+ code: review.patientCode,
372
+ callLogs: review.callLogs ?? [],
373
+ reviewId: String(review._id),
374
+ });
375
+ // A generation run sends the patient's context to a model. That is what the audit exists to
376
+ // record, so it is written before the failure is reported, not after it.
377
+ if (draft.attempted) {
378
+ const recorded = await audit(review, operator, requestId, draft.completed
379
+ ? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
380
+ : { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
381
+ // logPatientChange swallows its own failures and answers null, so an unrecorded generation is
382
+ // otherwise indistinguishable from a recorded one. Say so where operations will see it.
383
+ if (!recorded) {
384
+ logger.error('[EscalationReview] A draft generation reached a model but was not recorded in the audit log', {
385
+ escalationReviewId: String(review._id),
386
+ completed: Boolean(draft.completed),
387
+ });
388
+ }
389
+ }
390
+ if (!draft.completed) throw httpError(draft.configured === false ? 503 : 502, draft.reason);
391
+
392
+ // Generating takes as long as a model call, and a review can be cancelled underneath it. Saying so
393
+ // here is what stops a navigator from editing text that addDraft would then refuse to keep.
394
+ const settled = await loadReview(reviewId);
395
+ if (!DOCUMENTING_STATUSES.includes(settled.status)) throw httpError(409, STATUS_CONFLICT);
396
+
397
+ return draft;
398
+ }
399
+
360
400
  async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
361
401
  const reviewId = reviewIdOf(id);
362
402
  const operator = requiredText(writtenBy, 'writtenBy');
@@ -583,5 +623,6 @@ module.exports = {
583
623
  openEscalationReview,
584
624
  recordDoctorDecision,
585
625
  sendApprovedIndications,
626
+ suggestDraft,
586
627
  syncEscalationReviewCase,
587
628
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.55.0-dev.8069",
3
+ "version": "5.55.0-dev.8090",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",